Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tls_codec: feature for conditional deserialization derivation #1214

Merged
merged 18 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 11 additions & 5 deletions tls_codec/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,18 @@ criterion = "0.5"
regex = "1.8"

[features]
default = [ "std" ]
arbitrary = [ "std", "dep:arbitrary" ]
derive = [ "tls_codec_derive" ]
serde = [ "std", "dep:serde" ]
default = ["std"]
arbitrary = ["std", "dep:arbitrary"]
derive = ["tls_codec_derive"]
serde = ["std", "dep:serde"]
mls = [] # In MLS variable length vectors are limited compared to QUIC.
std = [ "tls_codec_derive?/std" ]
std = ["tls_codec_derive?/std"]
verifiable_structs = [
"std",
"derive",
"tls_codec_derive/verifiable_structs",
"tls_codec_derive/std",
]

[[bench]]
name = "tls_vec"
Expand Down
3 changes: 2 additions & 1 deletion tls_codec/derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ tls_codec = { path = "../" }
trybuild = "1"

[features]
default = [ "std" ]
default = ["std"]
verifiable_structs = ["std"]
std = []
54 changes: 53 additions & 1 deletion tls_codec/derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,37 @@
//! c: u8,
//! }
//! ```
//!
//!
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
//!
//!

#[cfg_attr(
feature = "verifiable_structs",
doc = r##"
## Verifiable structs

```compile_fail
use tls_codec_derive::{TlsSerialize, TlsDeserialize, TlsSize};

#[derive(TlsDeserialize, TlsSerialize, TlsSize)]
struct VerifiableStruct<const VERIFIED: bool> {
pub a: u16,
}

impl VerifiableStruct<true> {
#[cfg(feature = "verifiable_structs")]
fn deserialize(mut bytes: &[u8]) -> Result<Self, Error> {
Self::tls_deserialize(&mut bytes)
}
}

```
"##
)]
extern crate proc_macro;
extern crate proc_macro2;

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use quote::{quote, ToTokens};
use syn::{
self, parse_macro_input, punctuated::Punctuated, token::Comma, Attribute, Data, DeriveInput,
Expr, ExprLit, ExprPath, Field, Generics, Ident, Lit, Member, Meta, Result, Token, Type,
Expand Down Expand Up @@ -512,6 +536,16 @@ pub fn deserialize_macro_derive(input: TokenStream) -> TokenStream {
impl_deserialize(parsed_ast).into()
}

#[proc_macro_derive(TlsDeserializeUnverified, attributes(tls_codec))]
pub fn deserialize_unverified_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let parsed_ast = match parse_ast(ast) {
Ok(ast) => ast,
Err(err_ts) => return err_ts.into_compile_error().into(),
};
impl_deserialize(parsed_ast).into()
}

#[proc_macro_derive(TlsDeserializeBytes, attributes(tls_codec))]
pub fn deserialize_bytes_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
Expand Down Expand Up @@ -914,6 +948,24 @@ fn impl_deserialize(parsed_ast: TlsStruct) -> TokenStream2 {
.map(|p| p.for_trait("Deserialize"))
.collect::<Vec<_>>();
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
// If the struct is a VERIFIABLE pattern struct, only derive Deserialize for the unverified version
let (ty_generics, impl_generics) = if cfg!(feature = "verifiable_structs")
&& ty_generics.clone().to_token_stream().to_string() == "< VERIFIED >"
{
(
quote! {
<false>
},
TokenStream2::new(),
)
} else {
(
quote! {
#ty_generics
},
impl_generics.to_token_stream(),
)
};
quote! {
impl #impl_generics tls_codec::Deserialize for #ident #ty_generics #where_clause {
#[cfg(feature = "std")]
Expand Down
27 changes: 27 additions & 0 deletions tls_codec/derive/tests/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,3 +532,30 @@ fn type_with_unknowns() {
let deserialized = TypeWithUnknowns::tls_deserialize_exact(incoming);
assert!(matches!(deserialized, Err(Error::UnknownValue(3))));
}

#[derive(TlsDeserialize, TlsSerialize, TlsSize)]
struct VerifiableStruct<const VERIFIED: bool> {
pub a: u16,
}

impl VerifiableStruct<true> {
fn deserialize(mut bytes: &[u8]) -> Result<Self, Error> {
Self::tls_deserialize(&mut bytes)
}
}

#[test]
fn verifiable_struct() {
let verifiable_struct = VerifiableStruct::<true> { a: 1 };
let serialized = verifiable_struct.tls_serialize_detached().unwrap();
let deserialized = VerifiableStruct::<false>::tls_deserialize(&mut serialized.as_slice());
assert!(deserialized.is_ok());

// Remove this to test that the verifiable struct is not deserializable when
// the const generic is set to true.
#[cfg(not(feature = "verifiable_structs"))]
{
let deserialized = VerifiableStruct::<true>::tls_deserialize(&mut serialized.as_slice());
assert!(deserialized.is_ok());
}
}
Loading