zeroize_derive-1.4.2/.cargo_vcs_info.json0000644000000001540000000000100140650ustar { "git": { "sha1": "4ac07e8e8d02c61219c7ba3633e15eabfdb0fc11" }, "path_in_vcs": "zeroize/derive" }zeroize_derive-1.4.2/CHANGELOG.md000064400000000000000000000041301046102023000144640ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 1.4.2 (2023-03-30) ### Changed - Inject where clauses; skip unused ([#882]) [#882]: https://github.com/RustCrypto/utils/pull/882 ## 1.4.1 (2023-03-27) ### Changed - Do not automatically inject bounds ([#879]) [#879]: https://github.com/RustCrypto/utils/pull/879 ## 1.4.0 (2023-03-26) ### Changed - 2021 edition upgrade; MSRV 1.56 ([#869]) - Bump `syn` to v2 ([#858]) ### Removed - `synstructure` dependency ([#858]) [#858]: https://github.com/RustCrypto/utils/pull/858 [#869]: https://github.com/RustCrypto/utils/pull/869 ## 1.3.3 (2022-11-30) ### Fixed - Deriving `ZeroizeOnDrop` on items with generics ([#787]) [#787]: https://github.com/RustCrypto/utils/pull/787 ## 1.3.2 (2022-02-18) ### Fixed - Min versions build ([#732]) [#732]: https://github.com/RustCrypto/utils/pull/732 ## 1.3.1 (2021-01-14) [YANKED] ### Removed - `ZeroizeOnDrop` implementation for `#[zeroize(drop)]` ([#715]) [#715]: https://github.com/RustCrypto/utils/pull/715 ## 1.3.0 (2021-01-14) [YANKED] ### Added - `#[zeroize(bound = "T: MyTrait")]` ([#663]) - Custom derive for `ZeroizeOnDrop` ([#699], [#700]) [#663]: https://github.com/RustCrypto/utils/pull/663 [#699]: https://github.com/RustCrypto/utils/pull/699 [#700]: https://github.com/RustCrypto/utils/pull/700 ## 1.2.2 (2021-11-04) [YANKED] ### Added - `#[zeroize(skip)]` attribute ([#654]) [#654]: https://github.com/RustCrypto/utils/pull/654 ## 1.2.1 (2021-11-04) ### Changed - Moved to `RustCrypto/utils` repository ## 1.2.0 (2021-09-21) [YANKED] ### Changed - Bump MSRV to 1.51+ - Reject `#[zeroize(drop)]` on struct/enum fields, enum variants ## 1.1.1 (2021-10-09) [YANKED] ### Changed - Backport 1.2.0 `#[zeroize(drop)]` fixes but with a 1.47+ MSRV. ## 1.1.0 (2021-04-19) ### Changed - Bump MSRV to 1.47+ ## 1.0.1 (2019-09-15) ### Added - Add docs for the `Zeroize` proc macro ## 1.0.0 (2019-10-13) - Initial 1.0 release zeroize_derive-1.4.2/Cargo.toml0000644000000023300000000000100120610ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "zeroize_derive" version = "1.4.2" authors = ["The RustCrypto Project Developers"] description = "Custom derive support for zeroize" readme = "README.md" keywords = [ "memory", "memset", "secure", "volatile", "zero", ] categories = [ "cryptography", "memory-management", "no-std", "os", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/utils/tree/master/zeroize/derive" resolver = "1" [package.metadata.docs.rs] rustdoc-args = ["--document-private-items"] [lib] proc-macro = true [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "2" features = [ "full", "extra-traits", "visit", ] zeroize_derive-1.4.2/Cargo.toml.orig000064400000000000000000000012221046102023000155410ustar 00000000000000[package] name = "zeroize_derive" description = "Custom derive support for zeroize" version = "1.4.2" authors = ["The RustCrypto Project Developers"] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/utils/tree/master/zeroize/derive" readme = "README.md" categories = ["cryptography", "memory-management", "no-std", "os"] keywords = ["memory", "memset", "secure", "volatile", "zero"] edition = "2021" rust-version = "1.56" [lib] proc-macro = true [dependencies] proc-macro2 = "1" quote = "1" syn = {version = "2", features = ["full", "extra-traits", "visit"]} [package.metadata.docs.rs] rustdoc-args = ["--document-private-items"] zeroize_derive-1.4.2/LICENSE-APACHE000064400000000000000000000261361046102023000146110ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. zeroize_derive-1.4.2/LICENSE-MIT000064400000000000000000000021071046102023000143110ustar 00000000000000MIT License Copyright (c) 2019-2023 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. zeroize_derive-1.4.2/README.md000064400000000000000000000031511046102023000141340ustar 00000000000000# [RustCrypto]: `zeroize_derive` [![Crate][crate-image]][crate-link] ![Apache 2.0 Licensed/MIT][license-image] ![MSRV][rustc-image] [![Build Status][build-image]][build-link] Custom derive support for [zeroize]: a crate for securely zeroing memory while avoiding compiler optimizations. This crate isn't intended to be used directly. See [zeroize] crate for documentation. ## Minimum Supported Rust Version Rust **1.56** or newer. In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this crate's SemVer guarantees), however when we do it will be accompanied by a minor version bump. ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/zeroize_derive.svg [crate-link]: https://crates.io/crates/zeroize_derive [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg [build-image]: https://github.com/RustCrypto/utils/actions/workflows/zeroize.yml/badge.svg [build-link]: https://github.com/RustCrypto/utils/actions/workflows/zeroize.yml [//]: # (general links) [RustCrypto]: https://github.com/RustCrypto [zeroize]: https://github.com/RustCrypto/utils/tree/master/zeroize zeroize_derive-1.4.2/src/lib.rs000064400000000000000000000637471046102023000146010ustar 00000000000000//! Custom derive support for `zeroize` #![crate_type = "proc-macro"] #![forbid(unsafe_code)] #![warn(rust_2018_idioms, trivial_casts, unused_qualifications)] use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; use syn::{ parse::{Parse, ParseStream}, parse_quote, punctuated::Punctuated, token::Comma, visit::Visit, Attribute, Data, DeriveInput, Expr, ExprLit, Field, Fields, Lit, Meta, Result, Variant, WherePredicate, }; /// Name of zeroize-related attributes const ZEROIZE_ATTR: &str = "zeroize"; /// Derive the `Zeroize` trait. /// /// Supports the following attributes: /// /// On the item level: /// - `#[zeroize(drop)]`: *deprecated* use `ZeroizeOnDrop` instead /// - `#[zeroize(bound = "T: MyTrait")]`: this replaces any trait bounds /// inferred by zeroize-derive /// /// On the field level: /// - `#[zeroize(skip)]`: skips this field or variant when calling `zeroize()` #[proc_macro_derive(Zeroize, attributes(zeroize))] pub fn derive_zeroize(input: proc_macro::TokenStream) -> proc_macro::TokenStream { derive_zeroize_impl(syn::parse_macro_input!(input as DeriveInput)).into() } fn derive_zeroize_impl(input: DeriveInput) -> TokenStream { let attributes = ZeroizeAttrs::parse(&input); let mut generics = input.generics.clone(); let extra_bounds = match attributes.bound { Some(bounds) => bounds.0, None => attributes .auto_params .iter() .map(|type_param| -> WherePredicate { parse_quote! {#type_param: Zeroize} }) .collect(), }; generics.make_where_clause().predicates.extend(extra_bounds); let ty_name = &input.ident; let (impl_gen, type_gen, where_) = generics.split_for_impl(); let drop_impl = if attributes.drop { quote! { #[doc(hidden)] impl #impl_gen Drop for #ty_name #type_gen #where_ { fn drop(&mut self) { self.zeroize() } } } } else { quote! {} }; let zeroizers = generate_fields(&input, quote! { zeroize }); let zeroize_impl = quote! { impl #impl_gen ::zeroize::Zeroize for #ty_name #type_gen #where_ { fn zeroize(&mut self) { #zeroizers } } }; quote! { #zeroize_impl #drop_impl } } /// Derive the `ZeroizeOnDrop` trait. /// /// Supports the following attributes: /// /// On the field level: /// - `#[zeroize(skip)]`: skips this field or variant when calling `zeroize()` #[proc_macro_derive(ZeroizeOnDrop, attributes(zeroize))] pub fn derive_zeroize_on_drop(input: proc_macro::TokenStream) -> proc_macro::TokenStream { derive_zeroize_on_drop_impl(syn::parse_macro_input!(input as DeriveInput)).into() } fn derive_zeroize_on_drop_impl(input: DeriveInput) -> TokenStream { let zeroizers = generate_fields(&input, quote! { zeroize_or_on_drop }); let (impl_gen, type_gen, where_) = input.generics.split_for_impl(); let name = input.ident.clone(); let drop_impl = quote! { impl #impl_gen Drop for #name #type_gen #where_ { fn drop(&mut self) { use ::zeroize::__internal::AssertZeroize; use ::zeroize::__internal::AssertZeroizeOnDrop; #zeroizers } } }; let zeroize_on_drop_impl = impl_zeroize_on_drop(&input); quote! { #drop_impl #zeroize_on_drop_impl } } /// Custom derive attributes for `Zeroize` #[derive(Default)] struct ZeroizeAttrs { /// Derive a `Drop` impl which calls zeroize on this type drop: bool, /// Custom bounds as defined by the user bound: Option, /// Type parameters in use by fields auto_params: Vec, } /// Parsing helper for custom bounds struct Bounds(Punctuated); impl Parse for Bounds { fn parse(input: ParseStream<'_>) -> Result { Ok(Self(Punctuated::parse_terminated(input)?)) } } struct BoundAccumulator<'a> { generics: &'a syn::Generics, params: Vec, } impl<'ast> Visit<'ast> for BoundAccumulator<'ast> { fn visit_path(&mut self, path: &'ast syn::Path) { if path.segments.len() != 1 { return; } if let Some(segment) = path.segments.first() { for param in &self.generics.params { if let syn::GenericParam::Type(type_param) = param { if type_param.ident == segment.ident && !self.params.contains(&segment.ident) { self.params.push(type_param.ident.clone()); } } } } } } impl ZeroizeAttrs { /// Parse attributes from the incoming AST fn parse(input: &DeriveInput) -> Self { let mut result = Self::default(); let mut bound_accumulator = BoundAccumulator { generics: &input.generics, params: Vec::new(), }; for attr in &input.attrs { result.parse_attr(attr, None, None); } match &input.data { syn::Data::Enum(enum_) => { for variant in &enum_.variants { for attr in &variant.attrs { result.parse_attr(attr, Some(variant), None); } for field in &variant.fields { for attr in &field.attrs { result.parse_attr(attr, Some(variant), Some(field)); } if !attr_skip(&field.attrs) { bound_accumulator.visit_type(&field.ty); } } } } syn::Data::Struct(struct_) => { for field in &struct_.fields { for attr in &field.attrs { result.parse_attr(attr, None, Some(field)); } if !attr_skip(&field.attrs) { bound_accumulator.visit_type(&field.ty); } } } syn::Data::Union(union_) => panic!("Unsupported untagged union {:?}", union_), } result.auto_params = bound_accumulator.params; result } /// Parse attribute and handle `#[zeroize(...)]` attributes fn parse_attr(&mut self, attr: &Attribute, variant: Option<&Variant>, binding: Option<&Field>) { let meta_list = match &attr.meta { Meta::List(list) => list, _ => return, }; // Ignore any non-zeroize attributes if !meta_list.path.is_ident(ZEROIZE_ATTR) { return; } for meta in attr .parse_args_with(Punctuated::::parse_terminated) .unwrap_or_else(|e| panic!("error parsing attribute: {:?} ({})", attr, e)) { self.parse_meta(&meta, variant, binding); } } /// Parse `#[zeroize(...)]` attribute metadata (e.g. `drop`) fn parse_meta(&mut self, meta: &Meta, variant: Option<&Variant>, binding: Option<&Field>) { if meta.path().is_ident("drop") { assert!(!self.drop, "duplicate #[zeroize] drop flags"); match (variant, binding) { (_variant, Some(_binding)) => { // structs don't have a variant prefix, and only structs have bindings outside of a variant let item_kind = match variant { Some(_) => "enum", None => "struct", }; panic!( concat!( "The #[zeroize(drop)] attribute is not allowed on {} fields. ", "Use it on the containing {} instead.", ), item_kind, item_kind, ) } (Some(_variant), None) => panic!(concat!( "The #[zeroize(drop)] attribute is not allowed on enum variants. ", "Use it on the containing enum instead.", )), (None, None) => (), }; self.drop = true; } else if meta.path().is_ident("bound") { assert!(self.bound.is_none(), "duplicate #[zeroize] bound flags"); match (variant, binding) { (_variant, Some(_binding)) => { // structs don't have a variant prefix, and only structs have bindings outside of a variant let item_kind = match variant { Some(_) => "enum", None => "struct", }; panic!( concat!( "The #[zeroize(bound)] attribute is not allowed on {} fields. ", "Use it on the containing {} instead.", ), item_kind, item_kind, ) } (Some(_variant), None) => panic!(concat!( "The #[zeroize(bound)] attribute is not allowed on enum variants. ", "Use it on the containing enum instead.", )), (None, None) => { if let Meta::NameValue(meta_name_value) = meta { if let Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) = &meta_name_value.value { if lit.value().is_empty() { self.bound = Some(Bounds(Punctuated::new())); } else { self.bound = Some(lit.parse().unwrap_or_else(|e| { panic!("error parsing bounds: {:?} ({})", lit, e) })); } return; } } panic!(concat!( "The #[zeroize(bound)] attribute expects a name-value syntax with a string literal value.", "E.g. #[zeroize(bound = \"T: MyTrait\")]." )) } } } else if meta.path().is_ident("skip") { if variant.is_none() && binding.is_none() { panic!(concat!( "The #[zeroize(skip)] attribute is not allowed on a `struct` or `enum`. ", "Use it on a field or variant instead.", )) } } else { panic!("unknown #[zeroize] attribute type: {:?}", meta.path()); } } } fn field_ident(n: usize, field: &Field) -> Ident { if let Some(ref name) = field.ident { name.clone() } else { format_ident!("__zeroize_field_{}", n) } } fn generate_fields(input: &DeriveInput, method: TokenStream) -> TokenStream { let input_id = &input.ident; let fields: Vec<_> = match input.data { Data::Enum(ref enum_) => enum_ .variants .iter() .filter_map(|variant| { if attr_skip(&variant.attrs) { if variant.fields.iter().any(|field| attr_skip(&field.attrs)) { panic!("duplicate #[zeroize] skip flags") } None } else { let variant_id = &variant.ident; Some((quote! { #input_id :: #variant_id }, &variant.fields)) } }) .collect(), Data::Struct(ref struct_) => vec![(quote! { #input_id }, &struct_.fields)], Data::Union(ref union_) => panic!("Cannot generate fields for untagged union {:?}", union_), }; let arms = fields.into_iter().map(|(name, fields)| { let method_field = fields.iter().enumerate().filter_map(|(n, field)| { if attr_skip(&field.attrs) { None } else { let name = field_ident(n, field); Some(quote! { #name.#method() }) } }); let field_bindings = fields .iter() .enumerate() .map(|(n, field)| field_ident(n, field)); let binding = match fields { Fields::Named(_) => quote! { #name { #(#field_bindings),* } }, Fields::Unnamed(_) => quote! { #name ( #(#field_bindings),* ) }, Fields::Unit => quote! { #name }, }; quote! { #[allow(unused_variables)] #binding => { #(#method_field);* } } }); quote! { match self { #(#arms),* _ => {} } } } fn attr_skip(attrs: &[Attribute]) -> bool { let mut result = false; for attr in attrs.iter().map(|attr| &attr.meta) { if let Meta::List(list) = attr { if list.path.is_ident(ZEROIZE_ATTR) { for meta in list .parse_args_with(Punctuated::::parse_terminated) .unwrap_or_else(|e| panic!("error parsing attribute: {:?} ({})", list, e)) { if let Meta::Path(path) = meta { if path.is_ident("skip") { assert!(!result, "duplicate #[zeroize] skip flags"); result = true; } } } } } } result } fn impl_zeroize_on_drop(input: &DeriveInput) -> TokenStream { let name = input.ident.clone(); let (impl_gen, type_gen, where_) = input.generics.split_for_impl(); quote! { #[doc(hidden)] impl #impl_gen ::zeroize::ZeroizeOnDrop for #name #type_gen #where_ {} } } #[cfg(test)] mod tests { use super::*; #[track_caller] fn test_derive( f: impl Fn(DeriveInput) -> TokenStream, input: TokenStream, expected_output: TokenStream, ) { let output = f(syn::parse2(input).unwrap()); assert_eq!(format!("{output}"), format!("{expected_output}")); } #[track_caller] fn parse_zeroize_test(unparsed: &str) -> TokenStream { derive_zeroize_impl(syn::parse_str(unparsed).expect("Failed to parse test input")) } #[test] fn zeroize_without_drop() { test_derive( derive_zeroize_impl, quote! { struct Z { a: String, b: Vec, c: [u8; 3], } }, quote! { impl ::zeroize::Zeroize for Z { fn zeroize(&mut self) { match self { #[allow(unused_variables)] Z { a, b, c } => { a.zeroize(); b.zeroize(); c.zeroize() } _ => {} } } } }, ) } #[test] fn zeroize_with_drop() { test_derive( derive_zeroize_impl, quote! { #[zeroize(drop)] struct Z { a: String, b: Vec, c: [u8; 3], } }, quote! { impl ::zeroize::Zeroize for Z { fn zeroize(&mut self) { match self { #[allow(unused_variables)] Z { a, b, c } => { a.zeroize(); b.zeroize(); c.zeroize() } _ => {} } } } #[doc(hidden)] impl Drop for Z { fn drop(&mut self) { self.zeroize() } } }, ) } #[test] fn zeroize_with_skip() { test_derive( derive_zeroize_impl, quote! { struct Z { a: String, b: Vec, #[zeroize(skip)] c: [u8; 3], } }, quote! { impl ::zeroize::Zeroize for Z { fn zeroize(&mut self) { match self { #[allow(unused_variables)] Z { a, b, c } => { a.zeroize(); b.zeroize() } _ => {} } } } }, ) } #[test] fn zeroize_with_bound() { test_derive( derive_zeroize_impl, quote! { #[zeroize(bound = "T: MyTrait")] struct Z(T); }, quote! { impl ::zeroize::Zeroize for Z where T: MyTrait { fn zeroize(&mut self) { match self { #[allow(unused_variables)] Z(__zeroize_field_0) => { __zeroize_field_0.zeroize() } _ => {} } } } }, ) } #[test] fn zeroize_only_drop() { test_derive( derive_zeroize_on_drop_impl, quote! { struct Z { a: String, b: Vec, c: [u8; 3], } }, quote! { impl Drop for Z { fn drop(&mut self) { use ::zeroize::__internal::AssertZeroize; use ::zeroize::__internal::AssertZeroizeOnDrop; match self { #[allow(unused_variables)] Z { a, b, c } => { a.zeroize_or_on_drop(); b.zeroize_or_on_drop(); c.zeroize_or_on_drop() } _ => {} } } } #[doc(hidden)] impl ::zeroize::ZeroizeOnDrop for Z {} }, ) } #[test] fn zeroize_on_struct() { parse_zeroize_test(stringify!( #[zeroize(drop)] struct Z { a: String, b: Vec, c: [u8; 3], } )); } #[test] fn zeroize_on_enum() { parse_zeroize_test(stringify!( #[zeroize(drop)] enum Z { Variant1 { a: String, b: Vec, c: [u8; 3] }, } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on struct fields")] fn zeroize_on_struct_field() { parse_zeroize_test(stringify!( struct Z { #[zeroize(drop)] a: String, b: Vec, c: [u8; 3], } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on struct fields")] fn zeroize_on_tuple_struct_field() { parse_zeroize_test(stringify!( struct Z(#[zeroize(drop)] String); )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on struct fields")] fn zeroize_on_second_field() { parse_zeroize_test(stringify!( struct Z { a: String, #[zeroize(drop)] b: Vec, c: [u8; 3], } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on enum fields")] fn zeroize_on_tuple_enum_variant_field() { parse_zeroize_test(stringify!( enum Z { Variant(#[zeroize(drop)] String), } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on enum fields")] fn zeroize_on_enum_variant_field() { parse_zeroize_test(stringify!( enum Z { Variant { #[zeroize(drop)] a: String, b: Vec, c: [u8; 3], }, } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on enum fields")] fn zeroize_on_enum_second_variant_field() { parse_zeroize_test(stringify!( enum Z { Variant1 { a: String, b: Vec, c: [u8; 3], }, Variant2 { #[zeroize(drop)] a: String, b: Vec, c: [u8; 3], }, } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on enum variants")] fn zeroize_on_enum_variant() { parse_zeroize_test(stringify!( enum Z { #[zeroize(drop)] Variant, } )); } #[test] #[should_panic(expected = "#[zeroize(drop)] attribute is not allowed on enum variants")] fn zeroize_on_enum_second_variant() { parse_zeroize_test(stringify!( enum Z { Variant1, #[zeroize(drop)] Variant2, } )); } #[test] #[should_panic( expected = "The #[zeroize(skip)] attribute is not allowed on a `struct` or `enum`. Use it on a field or variant instead." )] fn zeroize_skip_on_struct() { parse_zeroize_test(stringify!( #[zeroize(skip)] struct Z { a: String, b: Vec, c: [u8; 3], } )); } #[test] #[should_panic( expected = "The #[zeroize(skip)] attribute is not allowed on a `struct` or `enum`. Use it on a field or variant instead." )] fn zeroize_skip_on_enum() { parse_zeroize_test(stringify!( #[zeroize(skip)] enum Z { Variant1, Variant2, } )); } #[test] #[should_panic(expected = "duplicate #[zeroize] skip flags")] fn zeroize_duplicate_skip() { parse_zeroize_test(stringify!( struct Z { a: String, #[zeroize(skip)] #[zeroize(skip)] b: Vec, c: [u8; 3], } )); } #[test] #[should_panic(expected = "duplicate #[zeroize] skip flags")] fn zeroize_duplicate_skip_list() { parse_zeroize_test(stringify!( struct Z { a: String, #[zeroize(skip, skip)] b: Vec, c: [u8; 3], } )); } #[test] #[should_panic(expected = "duplicate #[zeroize] skip flags")] fn zeroize_duplicate_skip_enum() { parse_zeroize_test(stringify!( enum Z { #[zeroize(skip)] Variant { a: String, #[zeroize(skip)] b: Vec, c: [u8; 3], }, } )); } #[test] #[should_panic(expected = "duplicate #[zeroize] bound flags")] fn zeroize_duplicate_bound() { parse_zeroize_test(stringify!( #[zeroize(bound = "T: MyTrait")] #[zeroize(bound = "")] struct Z(T); )); } #[test] #[should_panic(expected = "duplicate #[zeroize] bound flags")] fn zeroize_duplicate_bound_list() { parse_zeroize_test(stringify!( #[zeroize(bound = "T: MyTrait", bound = "")] struct Z(T); )); } #[test] #[should_panic( expected = "The #[zeroize(bound)] attribute is not allowed on struct fields. Use it on the containing struct instead." )] fn zeroize_bound_struct() { parse_zeroize_test(stringify!( struct Z { #[zeroize(bound = "T: MyTrait")] a: T, } )); } #[test] #[should_panic( expected = "The #[zeroize(bound)] attribute is not allowed on enum variants. Use it on the containing enum instead." )] fn zeroize_bound_enum() { parse_zeroize_test(stringify!( enum Z { #[zeroize(bound = "T: MyTrait")] A(T), } )); } #[test] #[should_panic( expected = "The #[zeroize(bound)] attribute is not allowed on enum fields. Use it on the containing enum instead." )] fn zeroize_bound_enum_variant_field() { parse_zeroize_test(stringify!( enum Z { A { #[zeroize(bound = "T: MyTrait")] a: T, }, } )); } #[test] #[should_panic( expected = "The #[zeroize(bound)] attribute expects a name-value syntax with a string literal value.E.g. #[zeroize(bound = \"T: MyTrait\")]." )] fn zeroize_bound_no_value() { parse_zeroize_test(stringify!( #[zeroize(bound)] struct Z(T); )); } #[test] #[should_panic(expected = "error parsing bounds: LitStr { token: \"T\" } (expected `:`)")] fn zeroize_bound_no_where_predicate() { parse_zeroize_test(stringify!( #[zeroize(bound = "T")] struct Z(T); )); } }