Skip to content

Fix bincode serde compatibility - #2021

Closed
tylerhawkes wants to merge 5 commits into
openmls:mainfrom
xmtp:fix-bincode-serde-compat
Closed

tylerhawkes wants to merge 5 commits into
openmls:mainfrom
xmtp:fix-bincode-serde-compat

Conversation

@tylerhawkes

Copy link
Copy Markdown
Contributor

Summary

Restore openmls-0.7.x serde wire-format compatibility for non-self-describing formats (bincode, postcard, …). Builds on #1990, which fixed the same class of bug for serde_json only.

serde's contract is with the underlying format, not with serde_json. Several changes since 0.7.1 — new enum variants inserted mid-declaration, new #[serde(default)] tail fields, a usize-shaped sentinel — produce stable JSON output but corrupt or refuse to load data persisted by 0.7.x bincode/postcard clients.

What broke since 0.7.1

Type Change bincode impact
ProposalType / Proposal AppAck removed; Grease, AppEphemeral, AppDataUpdate inserted persisted Custom(_) decodes as SelfRemove; SelfRemove decodes as Grease
Extension / ExtensionType Grease, AppDataDictionary inserted before Unknown persisted Unknown(_) decodes as one of the new variants
CredentialType Grease inserted before Other persisted Other(_) decodes as Grease(_)
MessageSecrets added_at: Option<SystemTime> added with #[serde(default)] bincode hits EOF; MessageSecretsStore fails to load
MemberStagedCommitState application_export_tree: Option<…> added with #[serde(default)] (feature-gated) same EOF when feature is enabled
PastEpochDeletionPolicy::KeepAll sentinel was usize::MAX as u64 wasm32 (u32::MAX) and 64-bit (u64::MAX) wrote different bytes; cross-host KeepAll failed to deserialize on wasm32

Commits

  1. fix: stabilize serde variant indices for persisted enums — restore 0.7.x declaration order; new variants moved to the end. The removed AppAck variant is replaced with a hidden _AppAck unit placeholder so subsequent indices don't shift. openmls never originated AppAck (no public API constructs one), and ProposalQueue::filter_proposals panics on any inbound Proposal::AppAck, so no openmls deployment plausibly has persisted state containing this variant. If any does survive (e.g. from a fork), the unit placeholder will misalign subsequent QueuedProposal fields and the deserialize will fail loudly in the common case.
  2. fix: tolerantly deserialize trailing optional fields on persisted structs — hand-written Deserialize for MessageSecrets and MemberStagedCommitState that probes the trailing field via SeqAccess::next_element and treats EOF / Ok(None)
    as "field absent → None". Both structs are positioned as the final field of their containing record, so the EOF-tolerant fallback can't misinterpret unrelated bytes.
  3. fix: encode persisted usize values as portable u64 — fix the KeepAll sentinel (u64::MAX, checked before narrowing). Defensively annotate the remaining persisted usize fields with a usize_as_u64 adapter; this is a wire no-op against
    today's serde usize impl but pins the convention.
  4. refactor: lock persisted enum variant indices via custom serde impls — replace the derived Serialize/Deserialize on the five enums with hand-written impls that pin each variant's variant_index as a numeric literal. Wire bytes
    byte-identical to the previous positional encoding. This commit is independent — feel free to drop it if the size isn't worth the safety; the rest of the fix stands.
  5. test: lock serde variant indices for persisted enums — minimal #[cfg(test)] serde::Serializer whose Ok is (u32, &'static str) and whose serialize_*_variant methods capture and return the call. Five unit tests pin every variant of
    each enum.

What this does not break

  • JSON / CBOR / msgpack — every existing variant name is preserved. The _AppAck placeholder serializes as "AppAck".
  • TLS wire format — From<u16> mappings on the type-ID enums and the hand-written codecs in messages/codec.rs / extensions/codec.rs are untouched.
  • Public API — every variant name, public method, and trait impl preserved. _AppAck is #[doc(hidden)].
  • Cross-architecture key derivation — not affected; the usize fields touched are bookkeeping (cache caps, ring-buffer cursor, padding length, PPRF tree width). HKDF inputs are sized by ciphersuite constants and TLS-length-prefixed bytes.
  • Derived Ord on the type-ID enums — restored to 0.7.x order for existing variants; new variants sort higher.

Caveats worth flagging

  • Exhaustive matches. External code that exhaustively matches on Proposal or ProposalType will need a _AppAck arm. The variant is #[doc(hidden)] but not #[non_exhaustive]. If you'd prefer marking these enums #[non_exhaustive] as a one-time API change instead, happy to do that — would let us drop the placeholder entirely and just delete the variant.
  • Inbound AppAck from non-openmls peers. If a peer ever sends a Proposal with proposal_type = 0x000b, the unit _AppAck placeholder consumes the variant tag and leaves the wrapped payload in the stream, causing the surrounding QueuedProposal deserialization to fail. This was already broken before (the receive path panics in filter_proposals), so this is a strict improvement, but worth flagging as an explicit non-fix.

`ProposalType`, `Proposal`, `Extension`, `ExtensionType`, and `CredentialType`
all gained or lost variants since openmls-0.7.1 in positions that shifted the
serde variant index. Self-describing formats (JSON, CBOR) deserialize enum
variants by name and are unaffected, but non-self-describing formats like
bincode and postcard decode the variant tag as a positional `u32`. A
persisted `Proposal::Custom`, `Proposal::SelfRemove`, `Extension::Unknown`,
`ExtensionType::Unknown`, or `CredentialType::Other` written by openmls-0.7.x
deserializes as some other variant on the current main branch, silently
corrupting state.

Restore the original variant order and append all new variants
(`Grease`, `AppEphemeral`, `AppDataUpdate`, `AppDataDictionary`,
`ImmutableMetadata` where applicable, plus `Grease` for `CredentialType`)
at the end of each enum. For the removed `AppAck` variant on `Proposal`
and `ProposalType`, introduce a hidden `_AppAck` placeholder at index 7
(with `#[serde(rename = "AppAck")]` to preserve the JSON variant name) so
subsequent variant indices stay stable. `AppAck` was never produced by the
library so no real persisted data round-trips through this variant.

Match arms in `messages/codec.rs`, `messages/proposals_in.rs`, and
`group/mls_group/proposal_store.rs` updated accordingly.
…ucts

`MessageSecrets.added_at` and `MemberStagedCommitState.application_export_tree`
were added as trailing fields with `#[serde(default)]` after openmls-0.7.x.
`#[serde(default)]` is honored by self-describing formats but not by
positional formats like bincode, where the deserializer requires the field's
bytes to be present. A group persisted by openmls-0.7.x fails to deserialize
its `MessageSecretsStore` or its pending `MemberStagedCommitState` on
current main because bincode hits EOF when trying to read the new tail
field.

Replace the derived `Serialize`/`Deserialize` impls with hand-written
visitors that read the trailing field via `SeqAccess::next_element` and
treat any failure (EOF from bincode, `Ok(None)` from formats that signal
end of sequence) as "field absent, default to None". Persisted data that
already contains the field round-trips its value unchanged; 0.7.x data
that predates the field loads with the field as None. `visit_map` retains
the standard `serde(default)` semantics for self-describing formats.

Both fields are positioned as the last field of their struct, and each
struct is the last field of its containing record (`MessageSecrets` is the
final field of `MessageSecretsStore`; `MemberStagedCommitState` is the
single payload of `StagedCommitState::GroupMember`), so the EOF-tolerant
fallback is safe — there are no following bytes to misinterpret.
`usize` is 32 bits on `wasm32` and 64 bits on most host targets. Serde's
default `usize` impl already routes through `serialize_u64` / `deserialize_u64`
so common formats (JSON, bincode, postcard) produce identical wire bytes on
both platforms — but PR openmls#1990's hand-written serializer for
`PastEpochDeletionPolicy::KeepAll` wrote `usize::MAX as u64`, which differs
by platform:

  * wasm32: `usize::MAX as u64 == u32::MAX == 4_294_967_295`
  * 64-bit: `usize::MAX as u64 == u64::MAX == 18_446_744_073_709_551_615`

The deserializer compounded the problem by calling `usize::try_from(v)`
before checking the sentinel, so a `KeepAll` policy written by a 64-bit
host failed to deserialize at all on `wasm32` (since `u64::MAX` does not
fit in a 32-bit `usize`). New code emits `u64::MAX` unconditionally and
checks the sentinel *before* narrowing to `usize`, so cross-architecture
group state with `KeepAll` now round-trips cleanly.

Legacy `wasm32`-written `KeepAll` (encoded as `u32::MAX`) loads as
`MaxEpochs(u32::MAX)` — functionally equivalent to "keep all" given the
practical ceiling on past-epoch counts — so existing wasm32 data is not
broken by this change.

Defensively annotate every remaining persisted `usize` field with a new
`usize_as_u64` serde adapter so any future format change cannot
re-introduce platform-native encoding by accident:

  * `MlsGroupJoinConfig.padding_size`
  * `MlsGroupJoinConfig.number_of_resumption_psks`
  * `MessageSecretsStore.max_epochs`
  * `ResumptionPskStore.max_number_of_secrets`
  * `ResumptionPskStore.cursor`
  * `Pprf.width`

These fields are bookkeeping (cache caps, ring-buffer cursor, message
padding length, PPRF tree width); none feed key derivation, which is
sized exclusively by ciphersuite constants and TLS-encoded length-prefixed
byte slices.
The five persisted enums fixed by the previous commit (`CredentialType`,
`ExtensionType`, `Extension`, `ProposalType`, `Proposal`) currently rely on
the *declaration order* in source to determine their serde `variant_index`,
because serde's derive macro uses `iter().enumerate()` to assign indices
positionally — Rust's explicit discriminant syntax (`Basic = 1`) is ignored
by the derive.

That convention is fragile: a future PR that adds a variant in the middle of
one of these enums silently shifts every following index and reintroduces
the bincode/postcard wire-format corruption this branch just fixed. The
documentation comment helps, but a one-line review miss is all it takes.

Replace the derived `Serialize`/`Deserialize` impls with hand-written ones
that pin each variant to an explicit `variant_index` via
`serialize_unit_variant` / `serialize_newtype_variant` /
`serialize_tuple_variant`. The wire bytes are byte-identical to the previous
positional encoding — these impls produce the same calls the derive used to
emit, just with the indices spelled out as numeric literals at the call
site. The matching `Deserialize` impls use the standard
`deserialize_enum` + `EnumAccess` + variant-identifier visitor pattern,
accepting both u64 indices (for bincode/postcard) and variant name strings
(for JSON/CBOR).

The `_AppAck` placeholder on `Proposal` and `ProposalType` keeps its
historical `"AppAck"` JSON name via the explicit string passed to
`serialize_unit_variant`, replacing the previous `#[serde(rename = "AppAck")]`
attribute on the variant.

Future maintainers adding a variant to any of these enums must pick a new,
never-reused index and add it to both the `Serialize` match and the
variant-identifier visitor. The compiler's exhaustiveness check enforces
that omissions are caught.
Add unit tests that pin the `(variant_index, variant_name)` pair emitted by
the manual `Serialize` impls for `CredentialType`, `ExtensionType`,
`Extension`, `ProposalType`, and `Proposal`. The variant index is the
bincode/postcard wire encoding of the enum tag; the variant name is the
JSON/CBOR encoding. Either drifting silently corrupts persisted group state
across openmls versions.

The mechanism is a minimal `serde::Serializer` (`utils::variant_index_probe`)
whose `Ok` type is `(u32, &'static str)` and whose only working methods are
`serialize_unit_variant`, `serialize_newtype_variant`, and
`serialize_tuple_variant`. They capture the `variant_index` and `variant`
arguments and return them directly; every other method returns an error so
misuse fails loudly. The probe never recurses into payloads, so the tests
construct each variant with the cheapest payload that satisfies its type.

For the tagged-union enums (`Extension`, `Proposal`), some payload variants
(those holding `Box<...Proposal>` with cryptographic content) are exercised
indirectly through the corresponding `ProposalType`/`ExtensionType` test
rather than directly, to avoid pulling key-package construction into the
test. The variants that historically drifted (the `_AppAck` placeholder,
`SelfRemove`, and `Custom`) are each pinned explicitly.

When adding a new variant to any of these enums:

  * pick a brand-new `variant_index`, never reuse an existing one;
  * append a `check(...)` line to the corresponding test;
  * the compiler's exhaustive-match check on the `Serialize` impl will catch
    omissions in the production code, and the test will catch omissions in
    the wire-format documentation.
@tylerhawkes
tylerhawkes requested a review from a team as a code owner May 11, 2026 23:40
@raphaelrobert

Copy link
Copy Markdown
Member

Thanks for the PR. This looks like something we should have outside the library to facilitate one-time migrations.

@tylerhawkes

Copy link
Copy Markdown
Contributor Author

@raphaelrobert This PR has no impact on json or other self describing (human readable) serializations. This just fixes bincode for us to be backwards compatible back to 0.7.1 (which we have several million clients currently using)

@raphaelrobert

Copy link
Copy Markdown
Member

I'm not questioning your need for it, but this is a pretty substantial departure from the status quo:

  • So far, the standing rule was that potential data format migrations should not live inside the library. We have not had to deal with migration so far because the changes haven't broken self-describing formats. Compatibility for bincode was not something the library ever promised.
  • This PR is 100s of lines of obviously vibe-coded code. It is not on par in terms of structure with the rest of the codebase. This lowers the quality and adds to the maintenance cost.

I don't see why this application-specific backwards compatibility is something that should be part of the library. A one-time migration should not be much harder to implement, and would avoid the two issues mentioned above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants