redaction-derive 0.1.9

Proc-macro derive for Sensitive classification traversal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Derive macros for `redaction`.
//!
//! This crate generates traversal code behind `#[derive(Sensitive)]` and
//! `#[derive(SensitiveError)]`. It:
//! - reads `#[sensitive(...)]` field attributes
//! - emits a `SensitiveType` implementation that calls into a mapper
//!
//! It does **not** define classifications or policies. Those live in the main
//! `redaction` crate and are applied at runtime.

// <https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html>
#![warn(
    anonymous_parameters,
    bare_trait_objects,
    elided_lifetimes_in_paths,
    missing_copy_implementations,
    rust_2018_idioms,
    trivial_casts,
    trivial_numeric_casts,
    unreachable_pub,
    unsafe_code,
    unused_extern_crates,
    unused_import_braces
)]
// <https://rust-lang.github.io/rust-clippy/stable>
#![warn(
    clippy::all,
    clippy::cargo,
    clippy::dbg_macro,
    clippy::float_cmp_const,
    clippy::get_unwrap,
    clippy::mem_forget,
    clippy::nursery,
    clippy::pedantic,
    clippy::todo,
    clippy::unwrap_used,
    clippy::uninlined_format_args
)]
// Allow some clippy lints
#![allow(
    clippy::default_trait_access,
    clippy::doc_markdown,
    clippy::if_not_else,
    clippy::module_name_repetitions,
    clippy::multiple_crate_versions,
    clippy::must_use_candidate,
    clippy::needless_pass_by_value,
    clippy::needless_ifs,
    clippy::use_self,
    clippy::cargo_common_metadata,
    clippy::missing_errors_doc,
    clippy::enum_glob_use,
    clippy::struct_excessive_bools,
    clippy::missing_const_for_fn,
    clippy::redundant_pub_crate,
    clippy::result_large_err,
    clippy::future_not_send,
    clippy::option_if_let_else,
    clippy::from_over_into,
    clippy::manual_inspect
)]
// Allow some lints while testing
#![cfg_attr(test, allow(clippy::non_ascii_literal, clippy::unwrap_used))]

#[allow(unused_extern_crates)]
extern crate proc_macro;

#[cfg(feature = "slog")]
use proc_macro2::Span;
use proc_macro2::{Ident, TokenStream};
use proc_macro_crate::{crate_name, FoundCrate};
use quote::{format_ident, quote};
#[cfg(feature = "slog")]
use syn::parse_quote;
use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput, Result};

mod container;
mod derive_enum;
mod derive_struct;
mod generics;
mod redacted_display;
mod strategy;
mod transform;
mod types;
use container::{parse_container_options, ContainerOptions};
use derive_enum::derive_enum;
use derive_struct::derive_struct;
use generics::{
    add_classified_value_bounds, add_clone_bounds, add_container_bounds, add_debug_bounds,
    add_display_bounds, add_redacted_display_bounds,
};
use redacted_display::derive_redacted_display;

/// Derives `redaction::SensitiveType` (and related impls) for structs and enums.
///
/// # Container Attributes
///
/// These attributes are placed on the struct/enum itself:
///
/// - `#[sensitive(skip_debug)]` - Opt out of `Debug` impl generation. Use this when you need a
///   custom `Debug` implementation or the type already derives `Debug` elsewhere.
///
/// # Field Attributes
///
/// - **No annotation**: The field passes through unchanged. Use this for fields that don't contain
///   sensitive data, including external types like `chrono::DateTime` or `rust_decimal::Decimal`.
///
/// - `#[sensitive]`: For scalar types (i32, bool, char, etc.), redacts to default values (0, false,
///   'X'). For struct/enum types that derive `Sensitive`, walks into them using `SensitiveType`.
///
/// - `#[sensitive(Classification)]`: Treats the field as a sensitive string-like value and applies
///   the classification's policy. Works for `String`, `Option<String>`, `Vec<String>`, `Box<String>`.
///   The type must implement `SensitiveValue`.
///
/// - `#[sensitive]` on `Box<dyn Trait>`: The derive detects the specific syntax
///   `Box<dyn Trait>` and calls `redaction::redact_boxed`. This only matches the
///   unqualified form (not `std::boxed::Box<dyn Trait>` or aliases). The trait
///   object must implement `RedactableBoxed`.
///
/// Unions are rejected at compile time.
///
/// # Additional Generated Impls
///
/// - `Debug`: when *not* building with `cfg(any(test, feature = "testing"))`, sensitive fields are
///   formatted as the string `"[REDACTED]"` rather than their values. Use `#[sensitive(skip_debug)]`
///   on the container to opt out.
/// - `slog::Value` (behind `cfg(feature = "slog")`): implemented by cloning the value and routing
///   it through `redaction::slog::IntoRedactedJson`. **Note:** this impl requires `Clone` and
///   `serde::Serialize` because it emits structured JSON. The derive first looks for a top-level
///   `slog` crate; if not found, it checks the `REDACTION_SLOG_CRATE` env var for an alternate path
///   (e.g., `my_log::slog`). If neither is available, compilation fails with a clear error.
#[proc_macro_derive(Sensitive, attributes(sensitive))]
pub fn derive_sensitive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand(input, SlogMode::RedactedJson) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.into_compile_error().into(),
    }
}

/// Derives `redaction::SensitiveType` for types that should log without `Serialize`.
///
/// This emits the same traversal and redacted `Debug` impls as `Sensitive`, but uses
/// a `slog::Value` implementation that logs a redacted string derived from a
/// display template.
///
/// The display template is taken from `#[error("...")]` (thiserror-style) or from
/// doc comments (displaydoc-style). If neither is present, the derive fails with a
/// compile error to avoid accidental exposure of sensitive fields.
///
/// The generated `Display` implementation suppresses
/// `unused_variables`/`unused_assignments` warnings in its match arm bindings,
/// since omission from the template is often intentional.
///
/// Classified fields referenced in the template are redacted by applying the
/// policy to an owned copy of the field value, so those field types must
/// implement `Clone`.
#[proc_macro_derive(SensitiveError, attributes(sensitive, error))]
pub fn derive_sensitive_error(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand(input, SlogMode::RedactedDisplayString) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.into_compile_error().into(),
    }
}

/// Returns the token stream to reference the redaction crate root.
///
/// Handles crate renaming (e.g., `my_redact = { package = "redaction", ... }`)
/// and internal usage (when derive is used inside the redaction crate itself).
fn crate_root() -> proc_macro2::TokenStream {
    match crate_name("redaction") {
        Ok(FoundCrate::Itself) => quote! { crate },
        Ok(FoundCrate::Name(name)) => {
            let ident = format_ident!("{}", name);
            quote! { ::#ident }
        }
        Err(_) => quote! { ::redaction },
    }
}

/// Returns the token stream to reference the slog crate root.
///
/// Handles crate renaming (e.g., `my_slog = { package = "slog", ... }`).
/// If the top-level `slog` crate is not available, falls back to the
/// `REDACTION_SLOG_CRATE` env var, which should be a path like `my_log::slog`.
#[cfg(feature = "slog")]
fn slog_crate() -> Result<proc_macro2::TokenStream> {
    match crate_name("slog") {
        Ok(FoundCrate::Itself) => Ok(quote! { crate }),
        Ok(FoundCrate::Name(name)) => {
            let ident = format_ident!("{}", name);
            Ok(quote! { ::#ident })
        }
        Err(_) => {
            let env_value = std::env::var("REDACTION_SLOG_CRATE").map_err(|_| {
                syn::Error::new(
                    Span::call_site(),
                    "slog support is enabled, but no top-level `slog` crate was found. \
Set the REDACTION_SLOG_CRATE env var to a path (e.g., `my_log::slog`) or add \
`slog` as a direct dependency.",
                )
            })?;
            let path = syn::parse_str::<syn::Path>(&env_value).map_err(|_| {
                syn::Error::new(
                    Span::call_site(),
                    format!("REDACTION_SLOG_CRATE must be a valid Rust path (got `{env_value}`)"),
                )
            })?;
            Ok(quote! { #path })
        }
    }
}

fn crate_path(item: &str) -> proc_macro2::TokenStream {
    let root = crate_root();
    let item_ident = syn::parse_str::<syn::Path>(item).expect("redaction crate path should parse");
    quote! { #root::#item_ident }
}

struct DeriveOutput {
    redaction_body: TokenStream,
    used_generics: Vec<Ident>,
    classified_generics: Vec<Ident>,
    debug_redacted_body: TokenStream,
    debug_redacted_generics: Vec<Ident>,
    debug_unredacted_body: TokenStream,
    debug_unredacted_generics: Vec<Ident>,
    redacted_display_body: Option<TokenStream>,
    redacted_display_generics: Vec<Ident>,
    redacted_display_debug_generics: Vec<Ident>,
    redacted_display_clone_generics: Vec<Ident>,
    redacted_display_nested_generics: Vec<Ident>,
}

enum SlogMode {
    RedactedJson,
    RedactedDisplayString,
}

#[allow(clippy::too_many_lines)]
fn expand(input: DeriveInput, slog_mode: SlogMode) -> Result<TokenStream> {
    let DeriveInput {
        ident,
        generics,
        data,
        attrs,
        ..
    } = input;

    let ContainerOptions { skip_debug } = parse_container_options(&attrs)?;

    let crate_root = crate_root();

    let redacted_display_output = if matches!(slog_mode, SlogMode::RedactedDisplayString) {
        Some(derive_redacted_display(&ident, &data, &attrs, &generics)?)
    } else {
        None
    };

    let derive_output = match &data {
        Data::Struct(data) => {
            let output = derive_struct(&ident, data.clone(), &generics)?;
            DeriveOutput {
                redaction_body: output.redaction_body,
                used_generics: output.used_generics,
                classified_generics: output.classified_generics,
                debug_redacted_body: output.debug_redacted_body,
                debug_redacted_generics: output.debug_redacted_generics,
                debug_unredacted_body: output.debug_unredacted_body,
                debug_unredacted_generics: output.debug_unredacted_generics,
                redacted_display_body: redacted_display_output
                    .as_ref()
                    .map(|output| output.body.clone()),
                redacted_display_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.display_generics.clone())
                    .unwrap_or_default(),
                redacted_display_debug_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.debug_generics.clone())
                    .unwrap_or_default(),
                redacted_display_clone_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.clone_generics.clone())
                    .unwrap_or_default(),
                redacted_display_nested_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.nested_generics.clone())
                    .unwrap_or_default(),
            }
        }
        Data::Enum(data) => {
            let output = derive_enum(&ident, data.clone(), &generics)?;
            DeriveOutput {
                redaction_body: output.redaction_body,
                used_generics: output.used_generics,
                classified_generics: output.classified_generics,
                debug_redacted_body: output.debug_redacted_body,
                debug_redacted_generics: output.debug_redacted_generics,
                debug_unredacted_body: output.debug_unredacted_body,
                debug_unredacted_generics: output.debug_unredacted_generics,
                redacted_display_body: redacted_display_output
                    .as_ref()
                    .map(|output| output.body.clone()),
                redacted_display_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.display_generics.clone())
                    .unwrap_or_default(),
                redacted_display_debug_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.debug_generics.clone())
                    .unwrap_or_default(),
                redacted_display_clone_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.clone_generics.clone())
                    .unwrap_or_default(),
                redacted_display_nested_generics: redacted_display_output
                    .as_ref()
                    .map(|output| output.nested_generics.clone())
                    .unwrap_or_default(),
            }
        }
        Data::Union(u) => {
            return Err(syn::Error::new(
                u.union_token.span(),
                "`Sensitive` cannot be derived for unions",
            ));
        }
    };

    let classify_generics = add_container_bounds(generics.clone(), &derive_output.used_generics);
    let classify_generics =
        add_classified_value_bounds(classify_generics, &derive_output.classified_generics);
    let (impl_generics, ty_generics, where_clause) = classify_generics.split_for_impl();
    let debug_redacted_generics =
        add_debug_bounds(generics.clone(), &derive_output.debug_redacted_generics);
    let (debug_redacted_impl_generics, debug_redacted_ty_generics, debug_redacted_where_clause) =
        debug_redacted_generics.split_for_impl();
    let debug_unredacted_generics =
        add_debug_bounds(generics.clone(), &derive_output.debug_unredacted_generics);
    let (
        debug_unredacted_impl_generics,
        debug_unredacted_ty_generics,
        debug_unredacted_where_clause,
    ) = debug_unredacted_generics.split_for_impl();
    let redaction_body = &derive_output.redaction_body;
    let debug_redacted_body = &derive_output.debug_redacted_body;
    let debug_unredacted_body = &derive_output.debug_unredacted_body;
    let debug_impl = if skip_debug {
        quote! {}
    } else {
        quote! {
            #[cfg(any(test, feature = "testing"))]
            impl #debug_unredacted_impl_generics ::core::fmt::Debug for #ident #debug_unredacted_ty_generics #debug_unredacted_where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #debug_unredacted_body
                }
            }

            #[cfg(not(any(test, feature = "testing")))]
            #[allow(unused_variables, unused_assignments)]
            impl #debug_redacted_impl_generics ::core::fmt::Debug for #ident #debug_redacted_ty_generics #debug_redacted_where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #debug_redacted_body
                }
            }
        }
    };

    let redacted_display_body = derive_output.redacted_display_body.as_ref();
    let redacted_display_impl = if matches!(slog_mode, SlogMode::RedactedDisplayString) {
        let redacted_display_generics =
            add_display_bounds(generics.clone(), &derive_output.redacted_display_generics);
        let redacted_display_generics = add_debug_bounds(
            redacted_display_generics,
            &derive_output.redacted_display_debug_generics,
        );
        let redacted_display_generics = add_clone_bounds(
            redacted_display_generics,
            &derive_output.redacted_display_clone_generics,
        );
        let redacted_display_generics = add_redacted_display_bounds(
            redacted_display_generics,
            &derive_output.redacted_display_nested_generics,
        );
        let (display_impl_generics, display_ty_generics, display_where_clause) =
            redacted_display_generics.split_for_impl();
        let redacted_display_body = redacted_display_body
            .cloned()
            .unwrap_or_else(TokenStream::new);
        quote! {
            impl #display_impl_generics #crate_root::slog::RedactedDisplay for #ident #display_ty_generics #display_where_clause {
                fn fmt_redacted(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    #redacted_display_body
                }
            }
        }
    } else {
        quote! {}
    };

    // Only generate slog impl when the slog feature is enabled on redaction-derive.
    // If slog is not available, emit a clear error with instructions.
    #[cfg(feature = "slog")]
    let slog_impl = {
        let slog_crate = slog_crate()?;
        let mut slog_generics = generics;
        let slog_where_clause = slog_generics.make_where_clause();
        let self_ty: syn::Type = parse_quote!(#ident #ty_generics);
        match slog_mode {
            SlogMode::RedactedJson => {
                slog_where_clause
                    .predicates
                    .push(parse_quote!(#self_ty: ::core::clone::Clone));
                // IntoRedactedJson requires Self: Serialize, so we add this bound to enable
                // generic types to work with slog when their type parameters implement Serialize.
                slog_where_clause
                    .predicates
                    .push(parse_quote!(#self_ty: ::serde::Serialize));
                slog_where_clause
                    .predicates
                    .push(parse_quote!(#self_ty: #crate_root::slog::IntoRedactedJson));
                let (slog_impl_generics, slog_ty_generics, slog_where_clause) =
                    slog_generics.split_for_impl();
                quote! {
                    impl #slog_impl_generics #slog_crate::Value for #ident #slog_ty_generics #slog_where_clause {
                        fn serialize(
                            &self,
                            _record: &#slog_crate::Record<'_>,
                            key: #slog_crate::Key,
                            serializer: &mut dyn #slog_crate::Serializer,
                        ) -> #slog_crate::Result {
                            let redacted = #crate_root::slog::IntoRedactedJson::into_redacted_json(self.clone());
                            #slog_crate::Value::serialize(&redacted, _record, key, serializer)
                        }
                    }
                }
            }
            SlogMode::RedactedDisplayString => {
                slog_where_clause
                    .predicates
                    .push(parse_quote!(#self_ty: #crate_root::slog::RedactedDisplay));
                let (slog_impl_generics, slog_ty_generics, slog_where_clause) =
                    slog_generics.split_for_impl();
                quote! {
                    impl #slog_impl_generics #slog_crate::Value for #ident #slog_ty_generics #slog_where_clause {
                        fn serialize(
                            &self,
                            _record: &#slog_crate::Record<'_>,
                            key: #slog_crate::Key,
                            serializer: &mut dyn #slog_crate::Serializer,
                        ) -> #slog_crate::Result {
                            let redacted = #crate_root::slog::RedactedDisplay::redacted_display(self);
                            serializer.emit_arguments(key, &format_args!("{}", redacted))
                        }
                    }
                }
            }
        }
    };

    #[cfg(not(feature = "slog"))]
    let slog_impl = quote! {};

    let trait_impl = quote! {
        #[allow(unused_assignments)]
        impl #impl_generics #crate_root::SensitiveType for #ident #ty_generics #where_clause {
            fn redact_with<M: #crate_root::RedactionMapper>(self, mapper: &M) -> Self {
                use #crate_root::SensitiveType as _;
                #redaction_body
            }
        }

        #debug_impl

        #redacted_display_impl

        #slog_impl

        // `slog` already provides `impl<V: Value> Value for &V`, so a reference
        // impl here would conflict with the blanket impl.
    };
    Ok(trait_impl)
}