Redactable
redactable is a redaction library for Rust. It lets you mark sensitive data in your
structs and enums and produce a safe, redacted version of the same type.
Logging and telemetry
are the most common use cases, but redaction is not tied to any logging framework.
Table of Contents
- Core traits
- Design philosophy
- How it works
- Walkthrough
- Outputs (structured vs logging)
- Sensitive vs SensitiveDisplay
- SensitiveDisplay in depth
- Decision guide
- Logging output (explicit boundary)
- Integrations
- Logging with maximum security
- Reference
- License
Core traits
RedactableContainer: composite types (structs, enums) that are traversed field-by-fieldRedactableLeaf: terminal values that can be converted to/from a string for redactionRedactionPolicy: types that define how a leaf is transformed (full redaction, keep last N chars, etc.)
Design philosophy
- Traversal is automatic: nested containers are handled automatically. For
Sensitive, they're walked viaRedactableContainer. ForSensitiveDisplay, they're formatted viaRedactableDisplay. - Redaction is opt-in: leaf values (scalars, strings) pass through unchanged unless explicitly marked with
#[sensitive(Policy)]. Redaction only happens where you ask for it. - Consistent annotation workflow: both
SensitiveandSensitiveDisplayfollow the same pattern—unannotated scalars pass through, unannotated containers are handled via their trait, and#[sensitive(Policy)]applies redaction. - Types are preserved:
Sensitive's.redact()returns the same type, not a string or wrapper.
How it works
The Sensitive derive macro generates traversal code. For each field, it calls RedactableContainer::redact_with. This uniform interface is what makes everything compose.
| Field kind | What happens |
|---|---|
Containers (structs/enums deriving Sensitive) |
Traversal walks into them recursively, visiting each field |
| Unannotated leaves (String, primitives, etc.) | These implement RedactableContainer as a passthrough - they return themselves unchanged |
Annotated leaves (#[sensitive(Policy)]) |
The macro generates transformation code that applies the policy, bypassing the normal RedactableContainer::redact_with call |
This is why every field must implement RedactableContainer: containers need it for traversal, and leaves provide passthrough implementations that satisfy the requirement without doing anything.
SensitiveDisplay follows the same principle but uses RedactableDisplay instead: nested types format via their fmt_redacted() method, and scalars pass through unchanged. See SensitiveDisplay in depth for details.
Walkthrough
Trait bounds on containers
As described in How it works, every field must implement RedactableContainer. Here's what that looks like in practice:
If a field's type does not implement RedactableContainer, you get a compilation error:
Blanket implementations
Two kinds of types get RedactableContainer for free.
Standard leaf types
String, primitives (u32, bool, etc.) implement RedactableContainer as a passthrough - they return themselves unchanged. This is why unannotated leaves compile and are left as-is:
let profile = Profile ;
let redacted = profile.redact;
assert_eq!;
assert_eq!;
Standard container types
Option, Vec, Box, Arc, etc. implement RedactableContainer by calling redact_with on their inner value(s). They do not change how the inner value is treated: the inner type (and any #[sensitive(...)] on the leaf value) decides whether it is a leaf, a nested container, or classified. Some examples:
Option<String>still treats theStringas a passthrough leafOption<MyStruct>still walks intoMyStruct#[sensitive(Default)]on anOption<String>leaf applies the policy to the string inside
let outer = Outer ;
let redacted = outer.redact;
assert_eq!; // unchanged
assert_eq!; // walked and redacted
assert_eq!; // policy applied
The #[sensitive(Policy)] attribute
The #[sensitive(Policy)] attribute marks a leaf as sensitive and applies a redaction policy. When present, the derive macro generates transformation code that applies the policy directly, bypassing the normal redact_with passthrough:
#[sensitive(Default)]on scalars: replaces the value with a default (0, false,'*')#[sensitive(Default)]on strings: replaces with"[REDACTED]"#[sensitive(Policy)]on strings: applies the policy's redaction rules
⚠️ Qualified primitive paths don't work with #[sensitive(Default)]
The derive macro decides how to handle #[sensitive(Default)] based on a syntactic check of how you wrote the type. Only bare primitive names like u32, bool, char are recognized as scalars. Qualified paths like std::primitive::u32 are not.
This matters because:
- Unannotated leaves: Both
u32andstd::primitive::u32work identically (passthrough viaRedactableContainer) #[sensitive(Default)]leaves:u32→ recognized as scalar → redacts to0✅std::primitive::u32→ not recognized → tries to usePolicyApplicable→ compile error ❌
Workaround: Always use bare primitive names (u32, bool, etc.) when applying #[sensitive(Default)].
How RedactableLeaf fits in
When you write #[sensitive(Policy)], the generated code needs to:
- Extract a string from the value (to apply the policy)
- Reconstruct the original type from the redacted string (so you get back your original type, not
String)
RedactableLeaf provides this interface:
use RedactableLeaf;
;
String already implements RedactableLeaf, which is why #[sensitive(Token)] works on String leaves out of the box. Implement it for your own types if you want policies to work on them.
Opting out with NotSensitive
Some types you own need to satisfy Redactable bounds but have no sensitive data. Use #[derive(NotSensitive)] to generate a no-op RedactableContainer impl:
use ;
Wrapper types for foreign types
Two wrapper types handle types you don't own (Rust's orphan rules prevent deriving Sensitive or implementing RedactableLeaf on foreign types):
NotSensitiveValue<T>: Wraps T and passes through unchangedSensitiveValue<T, P>: Wraps T and applies policy P when redacted
Foreign types with no sensitive data
Use NotSensitiveValue<T> to satisfy RedactableContainer bounds:
use ;
// (pretend this is from another crate)
Foreign leaf types that need redaction
For string-like foreign types (IDs, tokens), use RedactableWithPolicy<P> with SensitiveValue<T, P>:
// ❌ ERROR: can't implement RedactableLeaf (foreign trait) for ForeignId (foreign type)
// ✅ OK: RedactableWithPolicy<MyPolicy> is "local enough" because MyPolicy is yours
Then wrap the leaf:
Here's a complete example:
use ;
; // (pretend this comes from another crate)
// 1. Define a local policy (can reuse built-in logic)
;
// 2. Implement RedactableWithPolicy for the foreign type
// 3. Create a type alias for ergonomics
type SensitiveForeignId = ;
// 4. Use the alias
let wrapped = from;
⚠️ Wrappers treat their inner type as a leaf, not a container. Neither walks nested containers - if T derives Sensitive, its internal #[sensitive(...)] annotations would not be applied. This is ok because if a type derives Sensitive it should not be wrapped.
💡 These wrappers can also be used for types you own to provide additional logging safety guarantees. See Logging with maximum security for details.
Outputs (structured vs logging)
- Structured redaction (
Redactabletrait,.redact()method): returns the same type with sensitive leaves redacted - Logging output (
ToRedactedOutputtrait,RedactedOutputenum): converts to a safe-to-log representation - Structured logging adapters: see Integrations for slog and tracing
The RedactedOutput enum represents safe-to-log output:
use ;
let output: RedactedOutput = sensitive_value.to_redacted_output;
match output
⚠️ The Json variant uses serde_json::Value, which integrates well with slog's structured logging. For tracing, the Json variant is converted to a string since tracing's Value trait is sealed.
Sensitive vs SensitiveDisplay
There are two derive macros for redaction. Pick the one that matches your constraints:
Sensitive |
SensitiveDisplay |
|
|---|---|---|
| Output | Same type with redacted leaves | Redacted string |
Requires Clone |
Yes | No |
| Traverses containers | Yes (walks all fields) | No (only template placeholders) |
| Unannotated scalars | Passthrough | Passthrough |
| Unannotated containers | Walked via RedactableContainer |
Formatted via RedactableDisplay |
| Best for | Structured data | Display strings, non-Clone types |
Sensitive (structured redaction)
Use Sensitive when you can guarantee Clone. Nested containers are traversed automatically; leaves are only redacted when annotated with #[sensitive(Policy)].
use Sensitive;
let attempt = LoginAttempt ;
let redacted = attempt.redact;
assert_eq!;
assert_eq!;
SensitiveDisplay (string formatting)
Use SensitiveDisplay when you need a redacted string representation without Clone. It formats from a template and uses RedactableDisplay for unannotated placeholders. Common scalar-like types implement RedactableDisplay as passthrough.
use SensitiveDisplay;
let err = Invalid ;
// err.redacted_display() → "login failed for alice [REDACTED]"
See SensitiveDisplay in depth for template syntax and field annotations.
Nested SensitiveDisplay types are redacted automatically without extra annotations:
use ;
let err = RequestFailed ;
// err.redacted_display() → "request failed: db password [REDACTED]"
SensitiveDisplay in depth
SensitiveDisplay derives RedactableDisplay, which provides fmt_redacted() and redacted_display(). Unlike Sensitive, it produces a string rather than a redacted copy of the same type.
The annotation workflow mirrors Sensitive:
- Unannotated scalars → passthrough (unchanged)
- Unannotated nested types → use their
RedactableDisplayimplementation #[sensitive(Policy)]→ apply redaction policy
Template syntax
The display template comes from one of two sources:
1. #[error("...")] attribute (thiserror-style):
2. Doc comment (displaydoc-style):
Both support:
- Named placeholders:
{field_name} - Positional placeholders:
{0},{1} - Debug formatting:
{field:?}
Field annotations
Unannotated placeholders use RedactableDisplay:
| Annotation | Behavior |
|---|---|
| (none) | Uses RedactableDisplay: scalars pass through unchanged; nested SensitiveDisplay types are redacted |
#[not_sensitive] |
Renders with raw Display (or Debug if {:?}) — use for types without RedactableDisplay |
#[sensitive(Default)] |
Scalars → default value; strings → "[REDACTED]" |
#[sensitive(Policy)] |
Applies the policy's redaction rules |
This matches Sensitive behavior: scalars pass through, nested containers use their redaction trait.
Unannotated fields that do not implement RedactableDisplay produce a compile error:
;
This prevents accidental exposure when adding new fields while still making nested redaction ergonomic.
Decision guide
Which derive macro?
| Situation | Use |
|---|---|
Structured data with Clone |
#[derive(Sensitive)] |
Types without Clone |
#[derive(SensitiveDisplay)] |
| Type with no sensitive data | #[derive(NotSensitive)] |
Error types are a common case: use Sensitive if your error type implements Clone, otherwise use SensitiveDisplay.
How to handle foreign types?
| Situation | Use |
|---|---|
| Foreign type, no sensitive data | NotSensitiveValue<T> wrapper |
| Foreign type, needs redaction | SensitiveValue<T, Policy> + RedactableWithPolicy |
How to produce logging output?
| Situation | Use |
|---|---|
| Container → redacted text | .redacted_output() |
| Container → redacted JSON | .redacted_json() (requires json feature) |
| Non-sensitive value | .not_sensitive() / .not_sensitive_debug() / .not_sensitive_json() |
| SensitiveDisplay type | .redacted_display() or .to_redacted_output() |
Logging output (explicit boundary)
ToRedactedOutput is the single logging-safe bound. It produces a RedactedOutput:
RedactedOutput::Text(String)RedactedOutput::Json(serde_json::Value)(requires thejsonfeature)
Several wrappers produce RedactedOutput:
SensitiveValue<T, Policy>(Text)RedactedOutputRef/.redacted_output()(Text)RedactedJsonRef/.redacted_json()(Json,jsonfeature)NotSensitiveDisplay/.not_sensitive()(Text)NotSensitiveDebug/.not_sensitive_debug()(Text)NotSensitiveJson/.not_sensitive_json()(Json,jsonfeature)
use ;
;
let event = Event ;
log_redacted;
log_redacted;
log_redacted;
log_redacted;
log_redacted;
log_redacted;
Notes:
redacted_output()usesDebugformatting on the redacted value;redacted_json()provides structured output when JSON is available- This crate does not override
Display, so bypassingToRedactedOutputand logging raw values directly can still leak data - For stronger guarantees, route all logging through helpers that require
T: ToRedactedOutput
Integrations
slog
The slog feature enables automatic redaction - just log your values and they're redacted:
[]
= { = "0.1", = ["slog"] }
Containers - the Sensitive derive generates slog::Value automatically:
let event = PaymentEvent ;
// Just log it - slog::Value impl handles redaction automatically
info!;
// Logged JSON: {"customer_email":"al***@example.com","card_number":"************1234","amount":9999}
Leaf wrappers - SensitiveValue<T, P> also implements slog::Value:
let api_token: = from;
// Also automatic - SensitiveValue has its own slog::Value impl
info!;
// Logged: "*********-key"
Both work because they implement slog::Value - containers via the derive macro, wrappers via a manual implementation. No explicit conversion needed.
tracing
For structured logging with tracing, use the valuable integration:
[]
= { = "0.1", = ["tracing-valuable"] }
use TracingValuableExt;
let event = AuthEvent ;
// Redacts and logs as structured data - subscriber can traverse containers
info!;
// Logged: {api_key: "***************2345", user_email: "al***@example.com", action: "login"}
Unlike slog where slog::Value can be implemented automatically via the derive macro, tracing's Value trait is sealed. The valuable crate provides the structured data path - .tracing_redacted_valuable() redacts first, then wraps for valuable inspection.
For individual values (without valuable):
use TracingRedactedExt;
let api_key: = from;
let user_email: = from;
info!;
// Logged: api_key="***************2345" user_email="al***@example.com" action="login"
⚠️ Note: The valuable integration in tracing is still marked as unstable and requires a compatible subscriber.
Logging with maximum security
For high-security domains (finance, healthcare, compliance-sensitive systems), you need guarantees that sensitive data can't be accidentally logged. This section covers two approaches to achieve that.
The logging footgun
With #[sensitive(P)] attributes, the value is still the bare type at runtime:
let user = User ;
// ❌ Nothing stops you from logging the value directly
info!; // Logs "alice@example.com" unredacted!
// You must remember to redact the container first
let redacted = user.redact;
info!; // Now it's "al***@example.com"
Option A: Enforce ToRedactedOutput at the logging boundary (recommended)
The strongest approach is to make it impossible to log raw types by requiring T: ToRedactedOutput at the logging boundary:
use ;
// This function ONLY accepts types that implement ToRedactedOutput
Now the compiler enforces what you can pass:
// ✅ Containers: .redacted_output() redacts first, then produces safe output
log_safe;
// ✅ SensitiveValue wrappers: they carry their policy and redact on output
log_safe; // where api_token: SensitiveValue<String, Token>
// ✅ Known non-sensitive values: explicitly mark them as safe to log
// Use this for values you KNOW are not sensitive (IDs, timestamps, status codes)
log_safe;
log_safe;
// ❌ Raw types won't compile - forces you to make an explicit choice
log_safe; // ERROR: User doesn't implement ToRedactedOutput
log_safe; // ERROR: String doesn't implement ToRedactedOutput
Why .not_sensitive() matters: Raw String and primitives don't implement ToRedactedOutput because the compiler can't know if they're sensitive. By calling .not_sensitive(), you're explicitly declaring "I've reviewed this value and it's safe to log." This creates an audit trail in your code.
To adopt this pattern:
- Create logging helpers that require
T: ToRedactedOutput - Disallow direct use of
log::info!("{}", value)for potentially sensitive data (via code review or lints) - All logging goes through your safe helpers
Option B: Use SensitiveValue<T, P> wrappers for sensitive leaves
If you can't enforce trait bounds at the logging boundary, you can use SensitiveValue<T, P> wrappers instead of #[sensitive(P)] attributes:
let user = User ;
// ✅ Safe: Debug shows "[REDACTED]"
info!;
// ✅ Safe: explicit call for redacted form
info!;
// ⚠️ Intentional: .expose() for raw access (code review catches this)
info!;
Trade-offs: attributes vs wrappers
#[sensitive(P)] |
SensitiveValue<T, P> |
|
|---|---|---|
| Ergonomics | ✅ Work with actual types | ❌ Need .expose() everywhere |
Display ({}) |
❌ Shows raw value | ✅ Not implemented (won't compile) |
Debug ({:?}) |
❌ Shows raw value | ✅ Shows [REDACTED] |
| Serialization | Shows raw value | Shows raw value |
⚠️ Neither approach protects serialization. Both #[sensitive(P)] and SensitiveValue<T, P> serialize to raw values. This is intentional: serialization is used for much more than logging (API responses, database persistence, message queues, caching, etc.). Automatic redaction during serialization would break these use cases. If you need redacted serialization, call .redact() before serializing, or build wrapper functions/traits that enforce this for your specific context.
Practical wrappers for slog and tracing
You can enforce ToRedactedOutput at the logging boundary using macros (which enforce the bound by calling .to_redacted_output()).
slog:
slog_safe!; // ✅
slog_safe!; // ❌ Won't compile
slog_safe!; // ❌ Won't compile
tracing:
trace_safe!; // ✅ Container via .redacted_output()
trace_safe!; // ✅ SensitiveValue<T, P>
trace_safe!; // ✅ Explicitly non-sensitive
trace_safe!; // ❌ Won't compile - raw container
trace_safe!; // ❌ Won't compile - raw String
💡 Tip: Combine these wrappers with code review rules or clippy lints that flag direct use of tracing::info! or slog::info! with potentially sensitive data.
When to use which:
- Option A (
ToRedactedOutputenforcement) - Strongest guarantee. Use when you control the logging layer and can enforce the trait bound. - Option B (
SensitiveValuewrappers) - Field-level protection. Debug shows redacted, Display won't compile. Use when you can't control the logging layer. #[sensitive(P)]attributes - Most ergonomic. Use when your team logs containers (not individual values) and enforces this via code review.
Reference
Trait map
Domain layer (what is sensitive):
| Trait | Purpose | Implemented By |
|---|---|---|
RedactableContainer |
Walkable containers | Structs/enums deriving Sensitive, NotSensitiveValue<T> |
RedactableLeaf |
String-like leaves | String, Cow<str>, custom newtypes |
Policy layer (how to redact):
| Trait | Purpose | Implemented By |
|---|---|---|
RedactionPolicy |
Maps policy marker -> redaction | Your custom policies |
TextRedactionPolicy |
Concrete string transformations | Built-ins (Full/Keep/Mask) |
Application layer (redaction machinery):
| Trait | Purpose | Implemented By |
|---|---|---|
PolicyApplicable |
Applies policy through wrappers | String, Option, Vec, etc. |
Redactable |
User-facing .redact() |
Auto-implemented for RedactableContainer |
RedactableWithPolicy |
Policy-aware leaf redaction | RedactableLeaf types and external types |
ToRedactedOutput |
Logging output boundary | SensitiveValue<T,P>, RedactedOutputRef, RedactedJsonRef, NotSensitive*, RedactableDisplay |
RedactableMapper |
Internal traversal | #[doc(hidden)] |
Types:
| Type | Purpose |
|---|---|
RedactedOutput |
Enum for logging output: Text(String) or Json(serde_json::Value) |
SensitiveValue<T, P> |
Wrapper that applies policy P to leaf type T |
NotSensitiveValue<T> |
Wrapper that passes T through unchanged |
Display/logging layer:
| Trait | Purpose | Implemented By |
|---|---|---|
RedactableDisplay |
Redacted string formatting | SensitiveDisplay derive, scalars (passthrough) |
SlogRedactedExt |
slog structured JSON logging | Types implementing Redactable + Serialize |
TracingRedactedExt |
tracing display string logging | Types implementing ToRedactedOutput |
TracingValuableExt |
tracing structured logging via valuable |
Types implementing Redactable + Valuable |
Note: SensitiveDisplay also generates slog::Value when the slog feature is enabled, emitting the redacted display string.
Supported types
Leaves (implement RedactableLeaf):
String,Cow<'_, str>- Custom newtypes (implement
RedactableLeafyourself) - Note:
&stris not supported forSensitive; use owned strings orCow
Scalars (with #[sensitive(Default)]):
- Integers →
0, floats →0.0,bool→false,char→'*'
Scalars (implement RedactableDisplay as passthrough):
String,str,bool,char, integers, floats,Cow<str>,PhantomData,()- Feature-gated:
chronotypes,timetypes,Uuid
Containers (implement RedactableContainer):
Option<T>,Vec<T>,Box<T>,Arc<T>,Result<T, E>HashMap,BTreeMap,HashSet,BTreeSet- All walked automatically; policy annotations apply through them
External types: NotSensitiveValue<T> for passthrough, SensitiveValue<T, Policy> with RedactableWithPolicy for redaction.
Precedence and edge cases
#[sensitive(Policy)] on strings works with String and Cow<str> (and their wrappers like Option<String>). Scalars can only use #[sensitive(Default)]. For custom types, use the SensitiveValue<T, Policy> wrapper instead.
A type can implement both RedactableLeaf and derive Sensitive. This is useful when you want the option to either traverse the type's containers or redact it as a unit depending on context. Which trait is used depends on how the value is declared:
- Bare type (unannotated): uses
RedactableContainer, containers are traversed SensitiveValue<T, Policy>wrapper: usesRedactableLeaf, redacted as a unit
Unannotated containers whose type derives Sensitive are still walked. If a nested type has #[sensitive(Policy)] annotations on its leaves, those are applied even when the outer container is unannotated.
Implementing RedactableLeaf on a struct or enum makes it a terminal value. Its fields will not be traversed or individually redacted. This is useful when you want to redact the entire value as a unit, but nested #[sensitive(Policy)] annotations inside that type are ignored when it's used as a leaf.
Sets can collapse after redaction. HashSet/BTreeSet are redacted element-by-element and then collected back into a set. If redaction makes elements equal (e.g., multiple values redact to "[REDACTED]"), the resulting set may shrink. If cardinality matters, prefer a Vec.
Built-in policies
| Policy | Use for | Example output |
|---|---|---|
Default |
Scalars or generic redaction | 0 / false / '*' / [REDACTED] |
Token |
API keys | ...f456 (last 4) |
Email |
Email addresses | al***@example.com |
CreditCard |
Card numbers | ...1234 (last 4) |
Pii |
Generic PII (names, addresses) | ...oe (last 2) |
PhoneNumber |
Phone numbers | ...4567 (last 4) |
IpAddress |
IP addresses | ....100 (last 4) |
BlockchainAddress |
Wallet addresses | ...abcdef (last 6) |
Custom policies
use ;
;
License
Licensed under the MIT license (LICENSE.md or opensource.org/licenses/MIT).