Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions tests/tests/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,86 @@ fn test_transparent() {
assert!(matches!(Valuable::as_value(&T('a')), Value::Char('a')));
}

#[test]
fn test_mask_default_struct() {
#[derive(Valuable)]
struct User {
name: &'static str,
#[valuable(mask)]
password: &'static str,
}

#[derive(Valuable)]
struct Tuple(#[valuable(mask)] &'static str);

let v = User {
name: "alice",
password: "secret123",
};
assert_eq!(
format!("{:?}", v.as_value()),
r#"User { name: "alice", password: "<redacted>" }"#
);

let v = Tuple("hidden");
assert_eq!(format!("{:?}", v.as_value()), r#"Tuple("<redacted>")"#);
}

#[test]
fn test_mask_custom_fn_struct() {
fn mask_email(email: &&str) -> String {
if let Some(at) = email.find('@') {
format!("{}...{}", &email[..1], &email[at..])
} else {
"***".to_string()
}
}

#[derive(Valuable)]
struct Contact {
name: &'static str,
#[valuable(mask = "mask_email")]
email: &'static str,
}

let v = Contact {
name: "bob",
email: "bob@example.com",
};
assert_eq!(
format!("{:?}", v.as_value()),
r#"Contact { name: "bob", email: "b...@example.com" }"#
);
}

#[test]
fn test_mask_enum() {
#[derive(Valuable)]
enum Event {
Login {
user: &'static str,
#[valuable(mask)]
token: &'static str,
},
Data(#[valuable(mask)] &'static str),
}

let v = Event::Login {
user: "alice",
token: "abc123",
};
assert_eq!(
format!("{:?}", v.as_value()),
r#"Event::Login { user: "alice", token: "<redacted>" }"#
);

let v = Event::Data("sensitive");
assert_eq!(
format!("{:?}", v.as_value()),
r#"Event::Data("<redacted>")"#
);
}

#[rustversion::attr(not(stable), ignore)]
#[test]
fn ui() {
Expand Down
52 changes: 51 additions & 1 deletion valuable-derive/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ static ATTRS: &[AttrDef] = &[
// #[valuable(skip)]
AttrDef {
name: "skip",
conflicts_with: &["rename"],
conflicts_with: &["rename", "mask"],
position: &[
// TODO: How do we implement Enumerable::variant and Valuable::as_value if a variant is skipped?
// Position::Variant,
Expand All @@ -42,12 +42,28 @@ static ATTRS: &[AttrDef] = &[
],
style: &[MetaStyle::Ident],
},
// #[valuable(mask)] or #[valuable(mask = "...")]
AttrDef {
name: "mask",
conflicts_with: &["skip"],
position: &[Position::NamedField, Position::UnnamedField],
style: &[MetaStyle::Ident, MetaStyle::NameValue],
},
];

#[derive(Debug)]
pub(crate) enum Mask {
/// `#[valuable(mask)]` — use default mask string `"***"`
Default,
/// `#[valuable(mask = "path::to::fn")]` — use custom mask function
Custom(syn::Path),
}

pub(crate) struct Attrs {
rename: Option<(syn::MetaNameValue, syn::LitStr)>,
transparent: Option<Span>,
skip: Option<Span>,
mask: Option<Mask>,
}

impl Attrs {
Expand All @@ -65,12 +81,17 @@ impl Attrs {
pub(crate) fn skip(&self) -> bool {
self.skip.is_some()
}

pub(crate) fn mask(&self) -> Option<&Mask> {
self.mask.as_ref()
}
}

pub(crate) fn parse_attrs(cx: &Context, attrs: &[syn::Attribute], pos: Position) -> Attrs {
let mut rename = None;
let mut transparent = None;
let mut skip = None;
let mut mask = None;

let attrs = filter_attrs(cx, attrs, pos);
for (def, meta) in &attrs {
Expand Down Expand Up @@ -104,6 +125,34 @@ pub(crate) fn parse_attrs(cx: &Context, attrs: &[syn::Attribute], pos: Position)
"transparent" => transparent = Some(meta.span()),
// #[valuable(skip)]
"skip" => skip = Some(meta.span()),
// #[valuable(mask)] or #[valuable(mask = "...")]
"mask" => match meta {
Meta::Path(_) => {
mask = Some(Mask::Default);
}
Meta::NameValue(m) => {
let lit = match &m.value {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(l),
..
}) => l,
l => {
cx.error(format_err!(l, "expected string literal"));
continue;
}
};
match lit.parse::<syn::Path>() {
Ok(path) => {
mask = Some(Mask::Custom(path));
}
Err(e) => {
cx.error(format_err!(lit, "expected valid path: {}", e));
continue;
}
}
}
_ => unreachable!(),
},

_ => unreachable!("{}", def.name),
}
Expand All @@ -113,6 +162,7 @@ pub(crate) fn parse_attrs(cx: &Context, attrs: &[syn::Attribute], pos: Position)
rename,
transparent,
skip,
mask,
}
}

Expand Down
64 changes: 40 additions & 24 deletions valuable-derive/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{Error, Ident, Result};

use crate::attr::{parse_attrs, Attrs, Context, Position};
use crate::attr::{parse_attrs, Attrs, Context, Mask, Position};

pub(crate) fn derive_valuable(input: &mut syn::DeriveInput) -> TokenStream {
let cx = Context::default();
Expand Down Expand Up @@ -97,43 +97,42 @@ fn derive_struct(
)
};

let fields = data
let as_values: Vec<_> = data
.fields
.iter()
.enumerate()
.filter(|(i, _)| !field_attrs[*i].skip())
.map(|(_, field)| {
.map(|(i, field)| {
let f = field.ident.as_ref();
let tokens = quote! {
&self.#f
};
respan(tokens, &field.ty)
});
let field_ref = quote! { &self.#f };
let field_ref = respan(field_ref, &field.ty);
field_as_value(field_ref, &field_attrs[i])
})
.collect();
visit_fields = quote! {
visitor.visit_named_fields(&::valuable::NamedValues::new(
#named_fields_static_name,
&[
#(::valuable::Valuable::as_value(#fields),)*
#(#as_values,)*
],
));
}
}
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
let indices: Vec<_> = data
let as_values: Vec<_> = data
.fields
.iter()
.enumerate()
.filter(|(i, _)| !field_attrs[*i].skip())
.map(|(i, field)| {
let index = syn::Index::from(i);
let tokens = quote! {
&self.#index
};
respan(tokens, &field.ty)
let field_ref = quote! { &self.#index };
let field_ref = respan(field_ref, &field.ty);
field_as_value(field_ref, &field_attrs[i])
})
.collect();

let len = indices.len();
let len = as_values.len();
struct_def = quote! {
::valuable::StructDef::new_static(
#name_literal,
Expand All @@ -144,7 +143,7 @@ fn derive_struct(
visit_fields = quote! {
visitor.visit_unnamed_fields(
&[
#(::valuable::Valuable::as_value(#indices),)*
#(#as_values,)*
],
);
};
Expand Down Expand Up @@ -243,20 +242,21 @@ fn derive_enum(cx: Context, input: &syn::DeriveInput, data: &syn::DataEnum) -> R

let mut fields = Vec::with_capacity(variant.fields.len());
let mut as_value = Vec::with_capacity(variant.fields.len());
for (_, field) in variant
for (i, field) in variant
.fields
.iter()
.enumerate()
.filter(|(i, _)| !field_attrs[variant_index][*i].skip())
{
let f = field.ident.as_ref();
fields.push(f);
let tokens = quote! {
let field_ref = quote! {
// HACK(taiki-e): This `&` is not actually needed to calling as_value,
// but is needed to emulate multi-token span on stable Rust.
&#f
};
as_value.push(respan(tokens, &field.ty));
let field_ref = respan(field_ref, &field.ty);
as_value.push(field_as_value(field_ref, &field_attrs[variant_index][i]));
}
let skipped = if fields.len() == variant.fields.len() {
quote! {}
Expand All @@ -269,7 +269,7 @@ fn derive_enum(cx: Context, input: &syn::DeriveInput, data: &syn::DataEnum) -> R
&::valuable::NamedValues::new(
#named_fields_static_name,
&[
#(::valuable::Valuable::as_value(#as_value),)*
#(#as_value,)*
],
),
);
Expand All @@ -291,13 +291,14 @@ fn derive_enum(cx: Context, input: &syn::DeriveInput, data: &syn::DataEnum) -> R
.zip(&variant.fields)
.enumerate()
.filter(|(i, _)| !field_attrs[variant_index][*i].skip())
.map(|(_, (binding, field))| {
let tokens = quote! {
.map(|(i, (binding, field))| {
let field_ref = quote! {
// HACK(taiki-e): This `&` is not actually needed to calling as_value,
// but is needed to emulate multi-token span on stable Rust.
&#binding
};
respan(tokens, &field.ty)
let field_ref = respan(field_ref, &field.ty);
field_as_value(field_ref, &field_attrs[variant_index][i])
})
.collect();

Expand All @@ -313,7 +314,7 @@ fn derive_enum(cx: Context, input: &syn::DeriveInput, data: &syn::DataEnum) -> R
Self::#variant_name(#(#bindings),*) => {
visitor.visit_unnamed_fields(
&[
#(::valuable::Valuable::as_value(#as_value),)*
#(#as_value,)*
],
);
}
Expand Down Expand Up @@ -396,6 +397,21 @@ fn derive_enum(cx: Context, input: &syn::DeriveInput, data: &syn::DataEnum) -> R
})
}

/// Generates the `as_value` call for a field, applying mask if present.
fn field_as_value(field_ref: TokenStream, attrs: &Attrs) -> TokenStream {
match attrs.mask() {
Some(Mask::Default) => quote! {
::valuable::Valuable::as_value(&"<redacted>")
},
Some(Mask::Custom(path)) => quote! {
::valuable::Valuable::as_value(&#path(#field_ref))
},
None => quote! {
::valuable::Valuable::as_value(#field_ref)
},
}
}

// `static <name>: &[NamedField<'static>] = &[ ... ];`
fn named_fields_static(name: &Ident, fields: &syn::Fields, field_attrs: &[Attrs]) -> TokenStream {
debug_assert!(matches!(fields, syn::Fields::Named(..)));
Expand Down
17 changes: 17 additions & 0 deletions valuable-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ use syn::parse_macro_input;
///
/// Skip the field.
///
/// ## `#[valuable(mask)]`
///
/// Mask the field value with `"<redacted>"` to hide sensitive data.
///
/// ## `#[valuable(mask = "...")]`
///
/// Mask the field value using a custom function. The function receives
/// a reference to the field and should return a value that implements `Valuable`.
///
/// # Examples
///
/// ```
Expand All @@ -42,6 +51,14 @@ use syn::parse_macro_input;
/// HelloWorld,
/// Custom(String),
/// }
///
/// // Mask sensitive fields
/// #[derive(Valuable)]
/// struct User {
/// name: String,
/// #[valuable(mask)]
/// password: String,
/// }
/// ```
#[proc_macro_derive(Valuable, attributes(valuable))]
pub fn derive_valuable(input: TokenStream) -> TokenStream {
Expand Down
Loading