use serde_json::Value;
use std::collections::HashSet;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RedactionPolicy {
RedactionTraceOnly,
RedactionNone,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OutputStyle {
#[default]
Readable,
Raw,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Redactor {
policy: Option<RedactionPolicy>,
secret_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
}
pub fn policy(mut self, policy: RedactionPolicy) -> Self {
self.policy = Some(policy);
self
}
pub fn value(&self, value: &Value) -> Value {
let mut v = value.clone();
self.redact_in_place(&mut v);
v
}
pub fn url(&self, url: &str) -> String {
let context = RedactionContext::from_redactor(self);
redact_url_in_str(url, &context).unwrap_or_else(|| url.to_string())
}
pub(crate) fn redact_in_place(&self, value: &mut Value) {
let context = RedactionContext::from_redactor(self);
apply_redaction_policy_with_context(value, self.policy, &context);
}
}
impl From<RedactionPolicy> for Redactor {
fn from(policy: RedactionPolicy) -> Self {
Self {
policy: Some(policy),
secret_names: Vec::new(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OutputOptions {
pub redaction: Redactor,
pub style: OutputStyle,
}
impl From<RedactionPolicy> for OutputOptions {
fn from(policy: RedactionPolicy) -> Self {
Self {
redaction: Redactor::from(policy),
style: OutputStyle::default(),
}
}
}
pub fn redacted_value(value: &Value) -> Value {
Redactor::new().value(value)
}
pub fn redact_url_secrets(url: &str) -> String {
Redactor::new().url(url)
}
#[derive(Default)]
pub(crate) struct RedactionContext {
secret_names: HashSet<String>,
}
impl RedactionContext {
fn from_redactor(redactor: &Redactor) -> Self {
let secret_names = redactor.secret_names.iter().cloned().collect();
Self { secret_names }
}
fn is_secret_key(&self, key: &str) -> bool {
key_has_secret_suffix(key) || self.secret_names.contains(key)
}
}
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")
}
#[cfg(feature = "cli-help")]
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_secret_key(&key) {
map.insert(key, Value::String("***".into()));
} else if key_has_url_suffix(&key) {
if let Some(Value::String(s)) = map.get_mut(&key) {
*s = redact_url_field_value(s, context);
} else if let Some(v) = map.get_mut(&key) {
redact_secrets_with_context_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_in_str(s: &str, context: &RedactionContext) -> Option<String> {
if !s.contains("://") || !is_single_url(s) {
return None;
}
let scheme_sep = s.find("://")?;
let scheme = &s[..scheme_sep];
let rest = &s[scheme_sep + 3..];
let auth_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..auth_end];
let remainder = &rest[auth_end..];
let new_authority = redact_userinfo_password(authority);
let new_remainder = match remainder.find('?') {
Some(q) => {
let (path, q_onwards) = remainder.split_at(q);
let query_body = &q_onwards[1..];
let (query, fragment) = match query_body.find('#') {
Some(h) => (&query_body[..h], &query_body[h..]),
None => (query_body, ""),
};
format!("{path}?{}{fragment}", redact_query(query, context))
}
None => remainder.to_string(),
};
Some(format!("{scheme}://{new_authority}{new_remainder}"))
}
fn redact_url_field_value(s: &str, context: &RedactionContext) -> String {
if let Some(redacted) = redact_url_in_str(s, context) {
return redacted;
}
let trimmed = s.trim();
if trimmed != s
&& let Some(redacted) = redact_url_in_str(trimmed, context)
{
return redacted;
}
if s.chars().any(char::is_whitespace) || s.contains('@') {
return "***".to_string();
}
s.to_string()
}
fn redact_userinfo_password(authority: &str) -> String {
let Some(at) = authority.rfind('@') else {
return authority.to_string();
};
let userinfo = &authority[..at];
match userinfo.find(':') {
Some(colon) => format!("{}:***{}", &authority[..colon], &authority[at..]),
None => authority.to_string(),
}
}
fn redact_query(query: &str, context: &RedactionContext) -> String {
query
.split('&')
.map(|segment| {
let Some(eq) = segment.find('=') else {
return segment.to_string();
};
let raw_key = &segment[..eq];
let name = url::form_urlencoded::parse(segment.as_bytes())
.next()
.map(|(k, _)| k.into_owned())
.unwrap_or_default();
if context.is_secret_key(&name) {
format!("{raw_key}=***")
} else {
segment.to_string()
}
})
.collect::<Vec<_>>()
.join("&")
}
fn is_single_url(s: &str) -> bool {
if s.bytes().any(|b| b.is_ascii_whitespace()) {
return false;
}
let bytes = s.as_bytes();
if !bytes.first().is_some_and(|b| b.is_ascii_alphabetic()) {
return false;
}
let mut i = 1;
while i < bytes.len() {
let c = bytes[i];
if c.is_ascii_alphanumeric() || matches!(c, b'+' | b'-' | b'.') {
i += 1;
} else {
break;
}
}
s[i..].starts_with("://")
}
fn apply_redaction_policy_with_context(
value: &mut Value,
redaction_policy: Option<RedactionPolicy>,
context: &RedactionContext,
) {
match redaction_policy {
Some(RedactionPolicy::RedactionTraceOnly) => {
if let Value::Object(map) = value
&& let Some(trace) = map.get_mut("trace")
{
redact_secrets_with_context(trace, context);
}
}
Some(RedactionPolicy::RedactionNone) => {}
None => redact_secrets_with_context(value, context),
}
}