Repository navigation
Description
Services that keep keys, credentials and personal data in generated messages need to control the copies of that data that generated code makes: where binary and JSON decoding put it, how it is exported to JSON, including through views, and which wire fields are accepted, from buf generate as well as build.rs. This issue proposes hooks and policy options that let an application's own field types take that control (items 1–4, ready as PRs). It also asks for direction on a much larger profile, kept in our fork for now, that generates cleanup for whole messages (item 5).
Why this matters
Protobuf messages are how keys, credentials, tokens and personal data move between services. Rust's ownership still determines when such data is freed; ordinary deallocation simply does not erase it. Freed memory can end up in core dumps, crash reports, swap and hibernation files, or be handed to other code in the same process. An application that wants secret fields wiped therefore needs every copy to be owned by something that wipes it.
buffa's custom representations (bytes_type_custom_in, string_type_custom_in, repeated_type_custom_in) already let a crate-local type own and wipe a field's value when it is dropped or replaced, and [debug_redact = true] covers Debug. Some copies are still made where such a type cannot reach them:
- buffa's own copies while decoding and encoding a
bytesorstringfield: the ordinaryBytesbuffer used when a field spans input chunks, and base64 and string scratch space during JSON parsing and printing; - copies of values that are not custom representations: numbers, enums, timestamps and
google.protobuf.Valuetrees that are overwritten, removed by a oneof switch, left behind when a repeated field grows, or already decoded when a later part of the input fails.
These copies are made inside generated and runtime code, so the application cannot close the gaps itself. Today the alternative is post-processing generated sources, which is fragile across buffa releases and difficult to audit.
Items 1–4 address the first group. With them, a crate can name its sensitive field types in buf.gen.yaml or build.rs and:
- let a type that overrides the new binary decode hook copy a field straight into its own storage instead of through an intermediate
Bytes; - decide per type how the field is exported to JSON, for example accepting a private key on import but refusing to print it, including through views, and keep base64 scratch under the type's own ownership;
- reject unknown wire fields at the decode boundary, whether or not it stores them;
- configure all of this from
buf generateas well asbuild.rs.
Nothing in items 1–4 wipes memory by itself. They are hooks and routing that a wiping representation type, supplied by the application, can use. They do not cover values that are not custom representations, the parsers' and serializers' own internal buffers, or transport buffers.
The second group needs cleanup generated for whole messages, with wipe-owning collections and well-known types. That is item 5. We have implemented it in our fork, but it is far larger, so we are asking for direction rather than opening PRs.
Items 1–4 are opt-in. Code that does not use the new options keeps its behavior and its dependencies, with one deliberate exception, described in item 4: a zero unknown-field allowance now rejects unknown fields instead of only disabling their storage.
This matters to anyone building wallets, identity and credential services, key management, authentication, payments or health systems in Rust, and to auditors who need to show where secret material can persist.
Proposed changes
Items 1–4 add the hooks and options that a custom representation needs for the copies buffa itself makes, and are ready as PRs. Item 5 covers whole messages; it is larger, and we would like your view on where it belongs before proposing it.
-
Plugin options for custom representations.
protoc-gen-buffahas no equivalent ofbytes_type_custom_in,string_type_custom_inorrepeated_type_custom_in, so plugin users cannot select a custom type without post-processing generated sources. Proposed: repeatable options with the builder's names and<proto_path>=<rust_type>values, normalized like the other path-scoped options, with the Rust type validated by codegen as it is forbuffa-build. This sits alongside protoc-gen-buffa: add bytes_type and bytes_type_in options #821 (bytes_type_in=<path>=vec|bytes) and protoc-gen-buffa: expose map container options #767 (map options) rather than overlapping them; it also bears on Design question: prost-compatible suffix selectors for path-scoped build options #492's question of which builder options the plugin should mirror. protoc-gen-buffa: add bytes_type and bytes_type_in options #821 leaves custom types out because the plugin cannot check the dependency. That is also true ofextern_path, and codegen still reports a path that does not parse. -
Representation-controlled binary decoding.
ProtoBytes::from_wire/ProtoString::from_wirereceive aWirePayload, which for a field spanning input chunks is first copied into an ordinaryBytes. A wiping representation cannot protect that copy. Proposed: overridabledecode_length_delimitedmethods on both traits. buffa reads and validates the length prefix and passes an opaqueFieldPayloadthat implementsBuf, bounded to exactly the field; an override cannot widen the window or reach the surrounding input, and anything it leaves unread is skipped. The defaults keep today'sfrom_wirebehavior. -
JSON policy for custom types, including views. Today a custom bytes field's JSON always goes through buffa's base64 helper, custom string fields use either a with-module or the type's own
serdedepending on the field shape, and generated views serialize the borrowed bytes directly. A type therefore cannot keep base64 scratch storage under its own ownership, and an owned type that refuses export can still be exported through itsView/OwnedView. Proposed: opt-inProtoBytesJson/ProtoStringJsontraits with type-level functions taking&[u8]/&str, selected per type withjson_policy_type. Every JSON use of a listed type, in owned messages, views, lazy views and owned views, goes through the trait. Unlisted types are unchanged, so this is not a breaking change. Configuration mistakes, such as a listed type that no representation rule selects or a near-miss spelling, are codegen errors rather than a silent fall back to default JSON. There is a cleaner way to do this: require every custombytesandstringtype to implement the trait, with default methods that keep today's encoding, and route all of them through it with no configuration. That removes the type list and the second JSON path, but it is a breaking change for every JSON-enabled custom type. This proposal keeps the policy opt-in so that no existing code changes. -
Rejecting unknown wire fields independently of retaining them. With unknown-field preservation off, unknown fields are skipped and never counted, so a decoder cannot reject them. Proposed:
DecodeOptions::reject_unknown_fields(), equivalent towith_unknown_field_limit(0), where a zero allowance rejects every unknown wire field, stored or discarded: owned decoding, views, lazy views, the table codec, map entries, unknown groups and unknown closed-enum values. A positive allowance keeps its meaning as a storage budget. This changes what a zero limit means for messages generated without preservation, which previously decoded successfully; a separate option would avoid that if you prefer. Statically generated messages hold extensions and custom options as unknown fields, so those are rejected too, and a lazy view checks a deferred child when it is read. -
Message-level cleanup (design discussion). Items 1–4 give
bytesandstringrepresentations the hooks to control their own copies; they do not generate any cleanup. Numbers, enums, timestamps,google.protobuf.Valuetrees and repeated scalars are still stored as ordinary values, and their copies are left behind on replacement, on oneof switches, on repeated-field growth and after a failed decode. We have implemented an opt-in profile for this in our fork:- a
zeroizecargo feature andzeroize_in/generate_zeroizecodegen options; - generated recursive cleanup on drop,
clear()and replacement, including partial decodes; - wipe-owning list, map and view storage, with JSON and text decoding streaming straight into it;
- erase hooks for map entries discarded before insertion;
- generated JSON deserialization and eager and lazy view-to-owned conversion that build the message by field assignment, so cleanup messages implement
Drop(ordinary messages also gainDrop-compatible JSON); - borrowed inspection in place of reflection snapshots;
- depth-bounded
arbitrary; - a per-message
deny_view_jsonexport restriction; - a separate family of wipe-owning well-known types behind a
buffa-types/sensitivefeature; - a borrowed-only view mode (
borrowed_views_only_in), with an owner that keeps eager views in wiping storage.
At our 0.1.0 release it was about 5,700 lines of hand-written code plus about 6,700 lines of generated well-known types, far beyond the contribution guideline, so we are not opening it as PRs. We would like to know whether you would want any of it in buffa, as a separate crate built on public hooks, or not at all. Some parts are useful on their own:
Drop-compatible JSON for ordinary messages, the map erase hooks anddeny_view_json. - a
Smaller changes found along the way are independent of the items above:
protoc-gen-buffaerror responses omit the supported edition range, sobufreports a protocol error instead of the plugin's message.- An editions enum that declares itself
CLOSEDgets no vtableReflectElementimpl, so itsrepeatedandmapfields fail to compile with reflection enabled. - JSON decoding errors include the rejected value: unknown enum names and numbers, map keys, numbers written as strings, base64 decoder errors, malformed
TimestampandDurationstrings, andAnydecoder errors. An application that logs a rejected message can disclose that input. - A
skip_debugrule removes an owned message's generatedDebug, but its views still print every field, including preserved unknown fields that[debug_redact = true]cannot annotate. - A failed
DecodeOptions::mergeleaves old and partially merged fields in the destination. An opt-inclear_on_merge_errorclears it instead.
Out of scope
Canonical-encoding checks, transport buffers, the internal buffers of JSON and text parsers and serializers (for example serde_json's string scratch), and application resource limits stay with the application. Generated Clone stays as it is: each cloned guarded field must own and wipe its copy. Unknown JSON fields are already covered by deny_unknown_json_fields.
Questions
- Are plugin options naming custom Rust types acceptable, given the reasoning in protoc-gen-buffa: add bytes_type and bytes_type_in options #821?
- Item 3 is opt-in so that existing code is unaffected. Would you prefer the cleaner, breaking version, where the trait is required for every custom type, in a future breaking release instead?
- For item 4, is it acceptable for a zero unknown-field allowance to reject discarded fields, or would you prefer a separate option?
- For item 5, would you want message-level cleanup in buffa, as a separate crate, or not at all? If in buffa, which parts first?
Pull requests
| Item | PR | What it does |
|---|---|---|
| 1 | #824 | protoc-gen-buffa options bytes_type_custom_in, string_type_custom_in and repeated_type_custom_in, so buf generate can select custom representations. |
| 2 | #825 | ProtoBytes / ProtoString::decode_length_delimited, receiving a bounded, opaque FieldPayload, so a representation can decode a field into its own storage without an intermediate Bytes. |
| 3 | #828 | ProtoBytesJson / ProtoStringJson traits and the serde helpers they need. Runtime only; nothing selects a policy yet. |
| 3 | #829 (draft) | json_policy_type in buffa-build, the plugin and codegen, routing every JSON use of a listed type through its policy in owned messages, views, lazy views and owned views, with fail-closed configuration checks. Builds on #823, #824, #825 and #828 and includes their commits until they merge. |
| 4 | #826 | DecodeOptions::reject_unknown_fields(); a zero unknown-field allowance rejects stored and discarded unknown fields across owned, view, lazy-view and table decoding. Filed as a behavior change. |
| fix | #823 | Plugin error responses advertise the supported edition range, so buf shows the plugin's error. |
| fix | #827 | Vtable reflection emits ReflectElement for an editions enum that declares itself CLOSED. |
| fix | #830 | Enum JSON errors omit the rejected name or number, in generated enums, message fields, extensions and reflection. |
| fix | #832 (draft) | Other ProtoJSON decoding errors omit the rejected value: map keys, numeric strings and range checks, base64, Timestamp, Duration and Any. Builds on #830 and includes its commit until it merges. |
| fix | #831 | Views, view oneofs and owned views of a message selected by skip_debug print only the type name and a redaction marker. |
| option | #833 | DecodeOptions::clear_on_merge_error() clears the destination when merge or merge_from_slice fails. |
Item 5 has no PR; it is a question for discussion above. Each PR includes tests, a changelog fragment and the checks from CONTRIBUTING.md.
Contributed by ReallyMe Technologies Limited.
Activity