From e4761084940abd47dc23bacb193357d77bec7d14 Mon Sep 17 00:00:00 2001 From: RA <70325462+RAprogramm@users.noreply.github.com> Date: Sat, 27 Sep 2025 17:00:21 +0700 Subject: [PATCH] Optimize context metadata redaction handling --- src/app_error/context.rs | 7 ++++--- src/app_error/tests.rs | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/app_error/context.rs b/src/app_error/context.rs index 160127e..7d20c15 100644 --- a/src/app_error/context.rs +++ b/src/app_error/context.rs @@ -173,9 +173,10 @@ impl Context { if !fields.is_empty() { Self::apply_field_redactions(&mut fields, &field_policies); error.metadata.extend(fields); - } - for &(name, redaction) in &field_policies { - error = error.redact_field(name, redaction); + } else if !field_policies.is_empty() { + for &(name, redaction) in &field_policies { + error = error.redact_field(name, redaction); + } } if matches!(edit_policy, MessageEditPolicy::Redact) { error.edit_policy = MessageEditPolicy::Redact; diff --git a/src/app_error/tests.rs b/src/app_error/tests.rs index 92ed1e6..6938bae 100644 --- a/src/app_error/tests.rs +++ b/src/app_error/tests.rs @@ -335,6 +335,21 @@ fn context_redact_field_overrides_policy() { assert_eq!(metadata.redaction("token"), Some(FieldRedaction::Redact)); } +#[test] +fn context_redact_field_before_insertion_applies_policy() { + let err = super::Context::new(AppErrorKind::Service) + .redact_field("token", FieldRedaction::Hash) + .with(field::str("token", "super-secret")) + .into_error(DummyError); + + let metadata = err.metadata(); + assert_eq!( + metadata.get("token"), + Some(&FieldValue::Str(Cow::Borrowed("super-secret"))) + ); + assert_eq!(metadata.redaction("token"), Some(FieldRedaction::Hash)); +} + #[test] fn context_redact_field_mut_applies_policies() { let mut context = super::Context::new(AppErrorKind::Service);