reallyme-buffa-codegen 0.1.3

ReallyMe fork: Shared code generation logic for buffa (descriptor → Rust source)
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
// Modified by ReallyMe Technologies Limited.
//! Recursive owned-message cleanup, enabled explicitly by the consumer.

use crate::context::{CodeGenContext, MessageScope};
use crate::generated::descriptor::{field_descriptor_proto::Type, DescriptorProto};
use crate::{BytesRepr, CodeGenError, StringRepr, ZeroizeConfigurationErrorReason as Reason};
use proc_macro2::{Ident, TokenStream};
use quote::quote;

pub(crate) fn message_impl(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    name: &Ident,
    resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        proto_fqn,
        features,
        ..
    } = scope;
    if !ctx.zeroizes_message(proto_fqn) {
        // An ordinary container would relocate or snapshot a guarded
        // descendant without wiping the stale copy, so it must be selected.
        if ctx.contains_guarded_message(proto_fqn) {
            let reason = if ctx.config.generate_reflection {
                Reason::ReflectionParent
            } else {
                Reason::ContainingMessage
            };
            return Err(invalid(proto_fqn, reason));
        }
        return Ok(quote! {});
    }
    if ctx.preserve_unknown_fields(proto_fqn) {
        return Err(invalid(proto_fqn, Reason::UnknownFieldStorage));
    }
    let mut fields = Vec::new();
    let mut guards = Vec::new();
    for field in &msg.field {
        let field_name = field
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("field.name"))?;
        let ty = crate::impl_message::effective_type(ctx, field, features);
        let string_repr = crate::impl_message::field_string_repr(ctx, proto_fqn, field_name);
        let bytes_repr = crate::impl_message::field_bytes_repr(ctx, proto_fqn, field_name);
        if field.label.unwrap_or_default()
            == crate::generated::descriptor::field_descriptor_proto::Label::LABEL_REPEATED
            && !wipe_owning_collection(ctx, msg, field, proto_fqn, field_name)
        {
            return Err(invalid(proto_fqn, Reason::CollectionRepresentation));
        }
        let mut slot_types = vec![ty];
        if let Some(entry) = crate::message::find_map_entry(msg, field) {
            if crate::message::map_entry_key_type(ctx, entry, features) == Some(Type::TYPE_BYTES) {
                return Err(invalid(proto_fqn, Reason::RawMapKey));
            }
            slot_types = entry
                .field
                .iter()
                .map(|slot| crate::impl_message::effective_type_in_map_entry(ctx, slot, features))
                .collect();
        }
        for slot in slot_types {
            let path = match slot {
                Type::TYPE_STRING => match &string_repr {
                    StringRepr::Custom(path) => Some(path),
                    _ => return Err(invalid(proto_fqn, Reason::BufferRepresentation)),
                },
                Type::TYPE_BYTES => match &bytes_repr {
                    BytesRepr::Custom(path) => Some(path),
                    _ => return Err(invalid(proto_fqn, Reason::BufferRepresentation)),
                },
                _ => None,
            };
            if let Some(path) = path {
                if ctx.config.generate_json && !ctx.is_json_policy_type(path) {
                    return Err(invalid(proto_fqn, Reason::JsonPolicy));
                }
                let ty = crate::parse_custom_type_path(path)?;
                guards.push(quote! {__requires_wipe_owner::<#ty>();});
            }
        }
        // Imported messages must own their cleanup too. A Zeroize-only
        // implementation would not protect a child that fails before it can
        // be inserted into this parent.
        let message_slot = crate::message::find_map_entry(msg, field)
            .and_then(|entry| entry.field.iter().find(|slot| slot.number == Some(2)))
            .unwrap_or(field);
        let message_type = crate::impl_message::effective_type(ctx, message_slot, features);
        if matches!(message_type, Type::TYPE_MESSAGE | Type::TYPE_GROUP) {
            let ty = crate::message::scalar_or_message_type_nested(
                ctx,
                message_slot,
                scope.current_package,
                scope.nesting,
                features,
                resolver,
            )?;
            guards.push(quote! { __requires_wipe_owner::<#ty>(); });
        }
        if field.label.unwrap_or_default()
            == crate::generated::descriptor::field_descriptor_proto::Label::LABEL_REPEATED
        {
            let info = crate::message::classify_field(scope, msg, field, resolver)?;
            // This assertion is outside the message impl, where `Self` is
            // unavailable for recursive repeated fields.
            let ty = info.concrete_type();
            guards.push(quote! { __requires_wipe_owner::<#ty>(); });
        }
        if !crate::impl_message::is_real_oneof_member(field) {
            fields.push(ctx.field_ident(field_name, field.number.unwrap_or(0)));
        }
    }
    for (index, oneof) in msg.oneof_decl.iter().enumerate() {
        if msg.field.iter().any(|field| {
            crate::impl_message::is_real_oneof_member(field)
                && field.oneof_index.and_then(|i| usize::try_from(i).ok()) == Some(index)
        }) {
            fields.push(
                ctx.oneof_ident(
                    oneof
                        .name
                        .as_deref()
                        .ok_or(CodeGenError::MissingField("oneof.name"))?,
                ),
            );
        }
    }
    let guard_check = if guards.is_empty() {
        quote! {}
    } else {
        quote! {
            const _:fn()=||{
                fn __requires_wipe_owner<T: ::buffa::sensitive::Zeroize+::buffa::sensitive::ZeroizeOnDrop>(){}
                #(#guards)*
            };
        }
    };
    let allow = crate::message::deprecated_field_allow(ctx, msg, proto_fqn);
    Ok(quote! {
        #allow
        #guard_check
        #allow
        impl ::buffa::sensitive::Zeroize for #name {
            fn zeroize(&mut self) { #(::buffa::sensitive::Zeroize::zeroize(&mut self.#fields);)* }
        }
        impl ::buffa::sensitive::ZeroizeOnDrop for #name {}
        impl ::core::ops::Drop for #name {
            fn drop(&mut self) { ::buffa::sensitive::Zeroize::zeroize(self); }
        }
    })
}

pub(crate) fn oneof_impl(
    ctx: &CodeGenContext<'_>,
    proto_fqn: &str,
    name: &Ident,
    variants: impl Iterator<Item = (Ident, bool)>,
) -> TokenStream {
    if !ctx.zeroizes_message(proto_fqn) {
        return quote! {};
    }
    let arms: Vec<_> = variants.map(|(variant, boxed)| {
        if boxed { quote! { Self::#variant(value) => ::buffa::sensitive::Zeroize::zeroize(&mut **value), } }
        else { quote! { Self::#variant(value) => ::buffa::sensitive::Zeroize::zeroize(value), } }
    }).collect();
    quote! {
        impl ::buffa::sensitive::Zeroize for #name {
            fn zeroize(&mut self) { match self { #(#arms)* } }
        }
        impl ::buffa::sensitive::ZeroizeOnDrop for #name {}
        impl ::core::ops::Drop for #name { fn drop(&mut self) { ::buffa::sensitive::Zeroize::zeroize(self); } }
    }
}

/// Wipe view-owned scalar slots and collections without touching borrowed input.
pub(crate) fn view_impl(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    name: &Ident,
    lazy: bool,
) -> Result<TokenStream, CodeGenError> {
    let ctx = scope.ctx;
    if !ctx.zeroizes_message(scope.proto_fqn) {
        return Ok(quote! {});
    }
    let mut fields = Vec::new();
    let mut child_checks = Vec::new();
    for field in &msg.field {
        let entry = crate::message::find_map_entry(msg, field);
        let child = entry
            .and_then(|entry| entry.field.iter().find(|slot| slot.number == Some(2)))
            .unwrap_or(field);
        if matches!(
            crate::impl_message::effective_type(ctx, child, scope.features),
            Type::TYPE_MESSAGE | Type::TYPE_GROUP
        ) {
            let deferred = lazy
                && entry.is_none()
                && !crate::impl_message::is_real_oneof_member(field)
                && crate::lazy_view::is_lazy_field(scope, field);
            let ty = if deferred {
                crate::view::resolve_lazy_view_ty_tokens(scope, child, &quote! {'a})?
            } else {
                crate::view::resolve_view_ty_tokens(scope, child, &quote! {'a})?
            };
            child_checks.push(quote! {__requires_view_wipe_owner::<#ty>();});
        }

        if crate::impl_message::is_real_oneof_member(field) {
            continue;
        }
        let repeated = field.label.unwrap_or_default()
            == crate::generated::descriptor::field_descriptor_proto::Label::LABEL_REPEATED;
        if !repeated
            && matches!(
                crate::impl_message::effective_type(ctx, field, scope.features),
                Type::TYPE_STRING | Type::TYPE_BYTES
            )
        {
            continue;
        }
        fields.push(
            ctx.field_ident(
                field
                    .name
                    .as_deref()
                    .ok_or(CodeGenError::MissingField("field.name"))?,
                field.number.unwrap_or(0),
            ),
        );
    }
    for (index, oneof) in msg.oneof_decl.iter().enumerate() {
        if msg.field.iter().any(|field| {
            crate::impl_message::is_real_oneof_member(field)
                && field.oneof_index.and_then(|i| usize::try_from(i).ok()) == Some(index)
        }) {
            fields.push(
                ctx.oneof_ident(
                    oneof
                        .name
                        .as_deref()
                        .ok_or(CodeGenError::MissingField("oneof.name"))?,
                ),
            );
        }
    }
    let checks = if child_checks.is_empty() {
        quote! {}
    } else {
        quote! {
            fn __requires_view_wipe_owner<T: ::buffa::sensitive::Zeroize+::buffa::sensitive::ZeroizeOnDrop>(){}
            #(#child_checks)*
        }
    };
    let allow = crate::message::deprecated_field_allow(ctx, msg, scope.proto_fqn);
    Ok(quote! {
        #allow
        impl<'a> ::buffa::sensitive::Zeroize for #name<'a> {
            fn zeroize(&mut self) { #checks #(::buffa::sensitive::Zeroize::zeroize(&mut self.#fields);)* }
        }
        impl<'a> ::buffa::sensitive::ZeroizeOnDrop for #name<'a> {}
        impl<'a> ::core::ops::Drop for #name<'a> {
            fn drop(&mut self) { ::buffa::sensitive::Zeroize::zeroize(self); }
        }
    })
}

pub(crate) fn view_oneof_impl(
    scope: MessageScope<'_>,
    fields: &[&crate::generated::descriptor::FieldDescriptorProto],
    name: &Ident,
    generics: &TokenStream,
) -> Result<TokenStream, CodeGenError> {
    if !scope.ctx.zeroizes_message(scope.proto_fqn) {
        return Ok(quote! {});
    }
    let arms = fields.iter().map(|field| {
        let name = field.name.as_deref().ok_or(CodeGenError::MissingField("field.name"))?;
        let variant = crate::oneof::oneof_variant_ident(name);
        Ok(match crate::impl_message::effective_type(scope.ctx, field, scope.features) {
            Type::TYPE_STRING | Type::TYPE_BYTES => quote! { Self::#variant(_) => {}, },
            Type::TYPE_MESSAGE | Type::TYPE_GROUP => quote! {
                Self::#variant(value) => ::buffa::sensitive::Zeroize::zeroize(&mut **value),
            },
            _ => quote! { Self::#variant(value) => ::buffa::sensitive::Zeroize::zeroize(value), },
        })
    }).collect::<Result<Vec<TokenStream>, CodeGenError>>()?;
    Ok(quote! {
        impl #generics ::buffa::sensitive::Zeroize for #name #generics {
            fn zeroize(&mut self) { match self { #(#arms)* } }
        }
        impl #generics ::buffa::sensitive::ZeroizeOnDrop for #name #generics {}
        impl #generics ::core::ops::Drop for #name #generics {
            fn drop(&mut self) { ::buffa::sensitive::Zeroize::zeroize(self); }
        }
    })
}

/// Whether a repeated or map field's collection can own cleanup of its
/// elements. A `Vec` implements the cleanup traits for wipe-owning elements,
/// yet moves them on growth and releases the old allocation unwiped, so an
/// explicit rule selecting one is rejected. `HashMap` and `BTreeMap` would
/// fail the trait bounds at compile time; rejecting them here names the
/// problem earlier. Other custom collections are checked by their trait
/// bounds only, so a crate-local alias or newtype over `Vec` is not detected.
fn wipe_owning_collection(
    ctx: &CodeGenContext<'_>,
    msg: &DescriptorProto,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    proto_fqn: &str,
    field_name: &str,
) -> bool {
    if crate::message::find_map_entry(msg, field).is_some() {
        return matches!(
            crate::impl_message::field_map_repr(ctx, proto_fqn, field_name),
            crate::MapRepr::Custom(_)
        );
    }
    match crate::impl_message::field_repeated_repr(ctx, proto_fqn, field_name) {
        crate::RepeatedRepr::Custom(template) => !names_std_vec(&template),
        _ => false,
    }
}

/// Whether a custom collection template names the standard `Vec` itself.
fn names_std_vec(template: &str) -> bool {
    // Validation and emission must agree on equivalent type syntax. Otherwise
    // parentheses or raw identifiers can disguise a standard Vec, whose
    // cleanup traits do not protect allocations released during growth.
    let Ok(syn::Type::Path(path)) =
        crate::context::normalized_rust_type(&template.replace('*', "()"))
    else {
        return false;
    };
    // Associated types are opaque without the consumer's type checker, just
    // like aliases; their storage contract remains the defining crate's duty.
    if path.qself.is_some() {
        return false;
    }
    let names: Vec<String> = path
        .path
        .segments
        .iter()
        .map(|segment| segment.ident.to_string())
        .collect();
    let names: Vec<&str> = names.iter().map(String::as_str).collect();
    matches!(
        names.as_slice(),
        ["Vec"]
            | ["vec", "Vec"]
            | ["std" | "alloc", "vec", "Vec"]
            | ["buffa", "alloc", "vec", "Vec"]
            | [
                "std",
                "prelude",
                "v1" | "rust_2015" | "rust_2018" | "rust_2021" | "rust_2024",
                "Vec"
            ]
    )
}

fn invalid(message: &str, reason: Reason) -> CodeGenError {
    CodeGenError::InvalidZeroizeConfiguration {
        message: message.into(),
        reason,
    }
}

/// Build a dropping owner before evaluating any fallible field initializer.
/// Otherwise Rust drops initialized fields on error, but plain scalar fields
/// in a partially initialized aggregate never reach the message's destructor.
pub(crate) fn owned_from_view(
    ctx: &CodeGenContext<'_>,
    proto_fqn: &str,
    owned: &TokenStream,
    fields: &[(Ident, TokenStream)],
) -> TokenStream {
    if !ctx.zeroizes_message(proto_fqn) {
        let initializers = fields.iter().map(|(name, value)| quote! { #name: #value, });
        return quote! {
            ::core::result::Result::Ok(#owned {
                #(#initializers)*
                ..::core::default::Default::default()
            })
        };
    }
    let assignments = fields
        .iter()
        .map(|(name, value)| quote! { __owned.#name = #value; });
    let mutable = if fields.is_empty() {
        quote! {}
    } else {
        quote! {mut}
    };
    quote! {
        let #mutable __owned = <#owned as ::core::default::Default>::default();
        #(#assignments)*
        ::core::result::Result::Ok(__owned)
    }
}