mod url;
pub(crate) use url::valid_url_field;
use self::url::{redact_url_field_value, redact_url_in_str, redact_urls_in_text_with_context};
use crate::document::PathStep;
use serde_json::Value;
use std::collections::HashSet;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RedactionPolicy {
#[default]
All,
TraceOnly,
Off,
}
impl RedactionPolicy {
fn redacts_unscoped_input(self) -> bool {
!matches!(self, RedactionPolicy::Off)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlainStyle {
#[default]
Readable,
Raw,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Redactor {
policy: RedactionPolicy,
secret_names: Vec<String>,
url_names: Vec<String>,
reveal_names: Vec<String>,
}
impl Redactor {
pub fn new() -> Self {
Self::default()
}
pub fn secret_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
self.secret_names = names.into_iter().map(|s| s.into()).collect();
self
}
#[must_use]
pub fn url_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
self.url_names = names.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn reveal_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
self.reveal_names = names.into_iter().map(Into::into).collect();
self
}
pub fn policy(mut self, policy: RedactionPolicy) -> Self {
self.policy = policy;
self
}
pub fn value(&self, value: &Value) -> Value {
let mut v = value.clone();
self.redact_in_place(&mut v);
v
}
pub fn value_at(&self, path: &[PathStep], value: &Value) -> Value {
let mut v = value.clone();
self.redact_in_place_at(path, &mut v);
v
}
pub fn redact_in_place_at(&self, path: &[PathStep], value: &mut Value) {
if path.is_empty() {
return self.redact_in_place(value);
}
let context = RedactionContext::from_redactor(self);
let Some(scope) = self.scope_of(path, &context) else {
return;
};
match judge_route(scope, &context) {
Route::Masked { at_node } => {
if !(at_node && value.is_null()) {
*value = Value::String(REDACTED_MARKER.into());
}
}
Route::TooDeep => *value = Value::String(MAX_DEPTH_MARKER.into()),
Route::Url => redact_url_value_depth(value, &context, scope.len()),
Route::Plain => redact_secrets_with_context_depth(value, &context, scope.len()),
}
}
pub fn is_secret_path(&self, path: &[PathStep]) -> bool {
let context = RedactionContext::from_redactor(self);
let Some(scope) = self.scope_of(path, &context) else {
return false;
};
scope.iter().any(|step| match step {
PathStep::Field(key) => context.is_masked_key(key),
PathStep::Element => false,
})
}
fn scope_of<'p>(
&self,
path: &'p [PathStep],
context: &RedactionContext,
) -> Option<&'p [PathStep]> {
match self.policy {
RedactionPolicy::All => Some(path),
RedactionPolicy::TraceOnly => match path.split_first() {
Some((PathStep::Field(key), rest)) if key == "trace" => {
Some(if context.is_masked_key(key) {
path
} else {
rest
})
}
_ => None,
},
RedactionPolicy::Off => None,
}
}
pub fn url(&self, url: &str) -> String {
if !self.policy.redacts_unscoped_input() {
return url.to_string();
}
let context = RedactionContext::from_redactor(self);
redact_url_in_str(url, &context).unwrap_or_else(|| url.to_string())
}
pub fn urls_in_text(&self, text: &str) -> String {
if !self.policy.redacts_unscoped_input() {
return text.to_string();
}
let context = RedactionContext::from_redactor(self);
redact_urls_in_text_with_context(text, &context)
}
pub fn redact_in_place(&self, value: &mut Value) {
let context = RedactionContext::from_redactor(self);
apply_redaction_policy_with_context(value, self.policy, &context);
}
pub fn argv<S: AsRef<str>>(&self, args: &[S]) -> Vec<String> {
if !self.policy.redacts_unscoped_input() {
return args.iter().map(|arg| arg.as_ref().to_string()).collect();
}
let context = RedactionContext::from_redactor(self);
let mut out = Vec::with_capacity(args.len());
let mut redact_next = false;
for arg in args {
let arg = arg.as_ref();
if redact_next {
redact_next = false;
if !arg.starts_with("--") {
out.push(REDACTED_MARKER.to_string());
continue;
}
}
if let Some(rest) = arg.strip_prefix("--") {
if let Some((name, _)) = rest.split_once('=') {
if is_secret_flag_name(name, &context) {
out.push(format!("--{name}={REDACTED_MARKER}"));
continue;
}
} else if is_secret_flag_name(rest, &context) {
redact_next = true;
}
}
out.push(arg.to_string());
}
out
}
pub fn is_secret_name(&self, name: &str) -> bool {
RedactionContext::from_redactor(self).is_secret_key(name)
}
pub fn is_url_name(&self, name: &str) -> bool {
RedactionContext::from_redactor(self).is_url_key(name)
}
}
impl From<RedactionPolicy> for Redactor {
fn from(policy: RedactionPolicy) -> Self {
Self {
policy,
secret_names: Vec::new(),
url_names: Vec::new(),
reveal_names: Vec::new(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OutputOptions {
pub redaction: Redactor,
pub style: PlainStyle,
}
impl From<RedactionPolicy> for OutputOptions {
fn from(policy: RedactionPolicy) -> Self {
Self {
redaction: Redactor::from(policy),
style: PlainStyle::default(),
}
}
}
pub fn redacted_value(value: &Value) -> Value {
Redactor::new().value(value)
}
pub fn redact_argv<S: AsRef<str>>(args: &[S]) -> Vec<String> {
Redactor::new().argv(args)
}
pub fn redact_url_secrets(url: &str) -> String {
Redactor::new().url(url)
}
pub fn redact_urls_in_text(text: &str) -> String {
Redactor::new().urls_in_text(text)
}
pub(crate) const REDACTED_MARKER: &str = "***";
#[derive(Default)]
pub(crate) struct RedactionContext {
secret_names: HashSet<String>,
url_names: HashSet<String>,
reveal_names: HashSet<String>,
}
impl RedactionContext {
fn from_redactor(redactor: &Redactor) -> Self {
let secret_names = redactor.secret_names.iter().cloned().collect();
let url_names = redactor.url_names.iter().cloned().collect();
Self {
secret_names,
url_names,
reveal_names: redactor.reveal_names.iter().cloned().collect(),
}
}
fn is_secret_key(&self, key: &str) -> bool {
key_has_secret_suffix(key) || self.secret_names.contains(key)
}
fn is_url_key(&self, key: &str) -> bool {
key_has_url_suffix(key) || self.url_names.contains(key)
}
fn is_masked_key(&self, key: &str) -> bool {
self.is_secret_key(key) && !self.reveal_names.contains(key)
}
}
enum Route {
Masked { at_node: bool },
TooDeep,
Url,
Plain,
}
fn judge_route(route: &[PathStep], context: &RedactionContext) -> Route {
let mut in_url = false;
for (depth, step) in route.iter().enumerate() {
if depth >= MAX_DEPTH {
return Route::TooDeep;
}
let PathStep::Field(key) = step else {
continue;
};
if context.is_masked_key(key) {
return Route::Masked {
at_node: depth + 1 == route.len(),
};
}
if context.is_url_key(key) {
in_url = true;
}
}
if in_url { Route::Url } else { Route::Plain }
}
fn key_has_secret_suffix(key: &str) -> bool {
key.ends_with("_secret") || key.ends_with("_SECRET")
}
fn key_has_url_suffix(key: &str) -> bool {
key.ends_with("_url") || key.ends_with("_URL")
}
pub(crate) fn is_secret_flag_name(flag_name: &str, context: &RedactionContext) -> bool {
let normalized = flag_name.replace('-', "_");
context.is_secret_key(&normalized) || context.is_secret_key(flag_name)
}
const MAX_DEPTH: usize = 256;
const MAX_DEPTH_MARKER: &str = "<afdata:max-depth>";
fn redact_secrets_with_context(value: &mut Value, context: &RedactionContext) {
redact_secrets_with_context_depth(value, context, 0);
}
fn redact_secrets_with_context_depth(value: &mut Value, context: &RedactionContext, depth: usize) {
if depth >= MAX_DEPTH {
*value = Value::String(MAX_DEPTH_MARKER.into());
return;
}
match value {
Value::Object(map) => {
let keys: Vec<String> = map.keys().cloned().collect();
for key in keys {
if context.is_masked_key(&key) {
if !map.get(&key).is_some_and(Value::is_null) {
map.insert(key, Value::String(REDACTED_MARKER.into()));
}
} else if context.is_url_key(&key) {
if let Some(v) = map.get_mut(&key) {
redact_url_value_depth(v, context, depth + 1);
}
} else if let Some(v) = map.get_mut(&key) {
redact_secrets_with_context_depth(v, context, depth + 1);
}
}
}
Value::Array(arr) => {
for v in arr {
redact_secrets_with_context_depth(v, context, depth + 1);
}
}
_ => {}
}
}
fn redact_url_value_depth(value: &mut Value, context: &RedactionContext, depth: usize) {
if depth >= MAX_DEPTH {
*value = Value::String(MAX_DEPTH_MARKER.into());
return;
}
match value {
Value::String(text) => {
*text = redact_url_field_value(text, context);
}
Value::Array(values) => {
for value in values {
redact_url_value_depth(value, context, depth + 1);
}
}
Value::Object(values) => {
let keys = values.keys().cloned().collect::<Vec<_>>();
for key in keys {
if context.is_masked_key(&key) {
if !values.get(&key).is_some_and(Value::is_null) {
values.insert(key, Value::String(REDACTED_MARKER.into()));
}
} else if let Some(value) = values.get_mut(&key) {
redact_url_value_depth(value, context, depth + 1);
}
}
}
_ => {}
}
}
fn apply_redaction_policy_with_context(
value: &mut Value,
redaction_policy: RedactionPolicy,
context: &RedactionContext,
) {
match redaction_policy {
RedactionPolicy::All => redact_secrets_with_context(value, context),
RedactionPolicy::TraceOnly => {
if let Value::Object(map) = value
&& let Some(trace) = map.get_mut("trace")
{
if context.is_masked_key("trace") {
if !trace.is_null() {
*trace = Value::String(REDACTED_MARKER.into());
}
} else {
redact_secrets_with_context(trace, context);
}
}
}
RedactionPolicy::Off => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn routed_document() -> Value {
json!({
"name": "console",
"endpoint_url": "https://reviewer:pw@h/?token_secret=t&page=2",
"mirror_url": [
"https://u:pw@a/",
{"nested": "https://u:pw@b/", "key_secret": "k", "plain": "mailto:x@y.z"}
],
"vault_secret": {"inner": {"leaf": "x"}, "list": [1, 2], "gone": null},
"absent_secret": null,
"api_token": "configured-name",
"servers": [
{"name": "api_secret", "port": 1, "password_secret": "p", "hook_url": "https://u:pw@d/"}
],
"trace": {"session_secret": "s", "callback_url": "https://u:pw@c/", "step": 3},
"shown_secret": "visible"
})
}
fn compare_nodes(redactor: &Redactor, raw: &Value, shown: &Value, route: &mut Vec<PathStep>) {
assert_eq!(redactor.value_at(route, raw), *shown, "{route:?}");
match raw {
Value::Object(map) => {
for (key, child) in map {
route.push(PathStep::Field(key.clone()));
compare_nodes(redactor, child, shown.get(key).unwrap_or(shown), route);
route.pop();
}
}
Value::Array(items) => {
for (index, child) in items.iter().enumerate() {
route.push(PathStep::Element);
compare_nodes(redactor, child, shown.get(index).unwrap_or(shown), route);
route.pop();
}
}
_ => {}
}
}
#[test]
fn a_routed_node_equals_the_same_node_in_the_redacted_whole() {
let document = routed_document();
for policy in [
RedactionPolicy::All,
RedactionPolicy::TraceOnly,
RedactionPolicy::Off,
] {
let redactor = Redactor::new()
.policy(policy)
.secret_names(["api_token"])
.reveal_names(["shown_secret"]);
let whole = redactor.value(&document);
compare_nodes(&redactor, &document, &whole, &mut Vec::new());
}
}
#[test]
fn a_route_carries_secret_ancestors_url_fields_and_absent_secrets() {
let document = routed_document();
let redactor = Redactor::new().secret_names(["api_token"]);
let at = |path: &str| {
let document = crate::document::Value::from(document.clone());
let node =
crate::document::locate(&document, path, crate::document::Addressing::INDEX_ONLY)
.unwrap();
let value = Value::try_from(node.value).unwrap();
(
redactor.value_at(&node.steps, &value),
redactor.is_secret_path(&node.steps),
)
};
let key = |name: &str| PathStep::Field(name.to_string());
assert_eq!(at("vault_secret.inner.leaf"), (json!("***"), true));
assert_eq!(at("vault_secret.list.0"), (json!("***"), true));
assert_eq!(at("vault_secret.gone"), (json!("***"), true));
assert_eq!(at("absent_secret"), (Value::Null, true));
assert_eq!(at("api_token"), (json!("***"), true));
assert_eq!(
at("endpoint_url"),
(
json!("https://reviewer:***@h/?token_secret=***&page=2"),
false
)
);
assert_eq!(at("mirror_url.0"), (json!("https://u:***@a/"), false));
assert_eq!(
at("mirror_url.1.nested"),
(json!("https://u:***@b/"), false)
);
assert_eq!(at("name"), (json!("console"), false));
let revealing = Redactor::new().reveal_names(["shown_secret"]);
assert_eq!(
revealing.value_at(&[key("shown_secret")], &json!("visible")),
json!("visible")
);
assert!(!revealing.is_secret_path(&[key("shown_secret")]));
}
#[test]
fn an_identifier_that_selects_an_element_is_data_not_a_field_name() {
use crate::document::{self, Addressing, KeyedList};
let source = document::Value::from(routed_document());
let lists = [KeyedList {
prefix: "servers",
slug_field: "name",
}];
let located =
document::locate(&source, "servers.api_secret", Addressing::keyed(&lists)).unwrap();
assert_eq!(
located.steps,
vec![PathStep::Field("servers".to_string()), PathStep::Element]
);
let redactor = Redactor::new();
assert!(!redactor.is_secret_path(&located.steps));
let element = Value::try_from(located.value).unwrap();
assert_eq!(
redactor.value_at(&located.steps, &element),
json!({"name": "api_secret", "port": 1, "password_secret": "***", "hook_url": "https://u:***@d/"})
);
let located = document::locate(
&source,
"servers.api_secret.password_secret",
Addressing::keyed(&lists),
)
.unwrap();
assert!(redactor.is_secret_path(&located.steps));
}
#[test]
fn trace_only_judges_a_route_from_inside_trace() {
let redactor = Redactor::new().policy(RedactionPolicy::TraceOnly);
let key = |name: &str| PathStep::Field(name.to_string());
assert!(redactor.is_secret_path(&[key("trace"), key("session_secret")]));
assert!(!redactor.is_secret_path(&[key("result"), key("session_secret")]));
assert_eq!(
redactor.value_at(&[key("trace")], &json!({"session_secret": "s"})),
json!({"session_secret": "***"})
);
assert_eq!(
redactor.value_at(&[key("result"), key("session_secret")], &json!("s")),
json!("s")
);
}
#[test]
fn a_route_past_the_depth_bound_is_cut_like_the_whole() {
let mut document = json!("leaf");
for _ in 0..(MAX_DEPTH + 4) {
document = json!({ "k": document });
}
let redactor = Redactor::new();
let whole = redactor.value(&document);
compare_nodes(&redactor, &document, &whole, &mut Vec::new());
}
#[test]
fn url_fragment_params_redacted_like_query_params() {
assert_eq!(
redact_url_secrets("https://h/p?token_secret=QUERYLEAK#token_secret=FRAGLEAK"),
"https://h/p?token_secret=***#token_secret=***"
);
}
#[test]
fn url_fragment_params_redacted_without_a_query() {
assert_eq!(
redact_url_secrets("https://h/cb#access_token_secret=abc&state=xyz"),
"https://h/cb#access_token_secret=***&state=xyz"
);
}
#[test]
fn url_fragment_without_params_is_preserved() {
for url in [
"https://h/p?a=1#section",
"https://h/p#",
"https://h/p#a/b?c",
] {
assert_eq!(redact_url_secrets(url), url);
}
}
#[test]
fn url_fragment_honors_secret_names() {
let redactor = Redactor::new().secret_names(vec!["token".to_string()]);
assert_eq!(
redactor.url("https://h/cb#token=abc&page=2"),
"https://h/cb#token=***&page=2"
);
}
#[test]
fn url_names_are_exact_and_recurse_through_collections() {
let redactor = Redactor::new().secret_names(["token"]).url_names([
"url",
"relays",
"synapse_selector",
]);
let input = json!({
"url": "https://u:pw@h/?token=one",
"URL": "https://u:visible@h/?token=two",
"relays": [
"wss://relay.example/?token=three",
{"nested": "https://u:pw@nested.example/"}
],
"synapse_selector": "user:pass@host/db",
"other": "https://u:visible@h/?token=four"
});
assert_eq!(
redactor.value(&input),
json!({
"url": "https://u:***@h/?token=***",
"URL": "https://u:visible@h/?token=two",
"relays": [
"wss://relay.example/?token=***",
{"nested": "https://u:***@nested.example/"}
],
"synapse_selector": "***",
"other": "https://u:visible@h/?token=four"
})
);
assert!(redactor.is_url_name("url"));
assert!(!redactor.is_url_name("URL"));
}
#[test]
fn prose_url_redaction_is_explicit_and_preserves_punctuation() {
let message = "connect (https://u:pw@h/?token_secret=one), then wss://h/?token_secret=two. bare user:pw@h stays";
assert_eq!(
redact_urls_in_text(message),
"connect (https://u:***@h/?token_secret=***), then wss://h/?token_secret=***. bare user:pw@h stays"
);
assert_eq!(
redacted_value(&json!({"message": message})),
json!({"message": message})
);
}
#[test]
fn prose_url_redaction_honors_policy_and_secret_names() {
let text = "see https://h/?token=abc";
assert_eq!(
Redactor::new().secret_names(["token"]).urls_in_text(text),
"see https://h/?token=***"
);
assert_eq!(
Redactor::new()
.policy(RedactionPolicy::Off)
.secret_names(["token"])
.urls_in_text(text),
text
);
}
fn scoped_value() -> Value {
json!({
"result": {"api_key_secret": "sk-result"},
"trace": {"api_key_secret": "sk-trace"}
})
}
fn argv() -> Vec<String> {
vec!["tool".to_string(), "--api-key-secret=sk-live".to_string()]
}
#[test]
fn all_policy_redacts_every_path() {
let redactor = Redactor::new().policy(RedactionPolicy::All);
assert_eq!(
redactor.value(&scoped_value()),
json!({
"result": {"api_key_secret": "***"},
"trace": {"api_key_secret": "***"}
})
);
assert_eq!(redactor.argv(&argv()), vec!["tool", "--api-key-secret=***"]);
assert_eq!(
redactor.url("https://u:pw@h/cb?token_secret=abc"),
"https://u:***@h/cb?token_secret=***"
);
}
#[test]
fn trace_only_scopes_a_value_but_redacts_argv_and_url_in_full() {
let redactor = Redactor::new().policy(RedactionPolicy::TraceOnly);
assert_eq!(
redactor.value(&scoped_value()),
json!({
"result": {"api_key_secret": "sk-result"},
"trace": {"api_key_secret": "***"}
})
);
assert_eq!(redactor.argv(&argv()), vec!["tool", "--api-key-secret=***"]);
assert_eq!(
redactor.url("https://u:pw@h/cb?token_secret=abc"),
"https://u:***@h/cb?token_secret=***"
);
}
#[test]
fn off_policy_disables_every_path() {
let redactor = Redactor::new().policy(RedactionPolicy::Off);
assert_eq!(redactor.value(&scoped_value()), scoped_value());
assert_eq!(redactor.argv(&argv()), argv());
assert_eq!(
redactor.url("https://u:pw@h/cb?token_secret=abc"),
"https://u:pw@h/cb?token_secret=abc"
);
}
}