Skip to main content

xmtp_mls_device_sync/
lib.rs

1//! Device sync: the sync worker and its sync group, preference sync, and
2//! archive export and import. Built on the core, engine and identity crates;
3//! names no facade, streams or notifications type.
4#![warn(clippy::unwrap_used)]
5
6use prost::Message;
7use std::sync::Arc;
8use thiserror::Error;
9use tokio::sync::broadcast::error::RecvError;
10use tracing::instrument;
11use worker::SyncMetric;
12use xmtp_archive::ArchiveError;
13use xmtp_common::ErrorCode;
14use xmtp_common::RetryableError;
15use xmtp_configuration::{
16    INSTALLATION_RETRY_MIN_PROTOCOL_VERSION, SYNC_UPDATE_INSTALLATIONS_INTERVAL_NS,
17};
18use xmtp_cryptography::secret::{Zeroize, Zeroizing};
19use xmtp_db::TransactionalKeyStore;
20use xmtp_db::{
21    NotFound, StorageError,
22    group_message::{DeliveryStatus, StoredGroupMessage},
23    sync_outbox::{OwedPage, clear_owed, owed_page},
24};
25use xmtp_db::{XmtpDb, group::ConversationType, prelude::*};
26use xmtp_id::{InboxIdRef, associations::DeserializationError};
27use xmtp_mls_core::state_tx::StateTx;
28use xmtp_mls_core::sync_tasks::schedule_add_missing_installations;
29use xmtp_mls_core::{
30    mls_store::MlsStoreError,
31    worker::{NeedsDbReconnect, metrics::WorkerMetrics},
32};
33use xmtp_mls_engine::groups::is_own_sync_group;
34use xmtp_mls_engine::groups::{
35    GroupError, MlsGroup, PreconfiguredPolicies, context::XmtpSharedContext, send_message_opts,
36    summary::SyncSummary,
37};
38use xmtp_mls_group_state::app_data::protocol_floor::committed_floor_at_least;
39use xmtp_mls_group_state::group::GroupMetadataOptions;
40use xmtp_mls_group_state::libxmtp_version::LibXMTPVersion;
41use xmtp_mls_identity::identity_updates::{IdentityUpdateError, IdentityUpdates};
42use xmtp_proto::ShortHex;
43use xmtp_proto::types::{GroupId, InstallationId};
44use xmtp_proto::xmtp::{
45    device_sync::content::{
46        DeviceSyncContent as DeviceSyncContentProto, HmacKeyUpdate,
47        PreferenceUpdate as PreferenceUpdateMessage, PreferenceUpdates,
48        device_sync_content::Content as ContentProto,
49        preference_update::Update as PreferenceUpdateProto,
50    },
51    mls::message_contents::{ContentTypeId, EncodedContent},
52};
53
54pub mod archive;
55pub mod preference_sync;
56#[cfg(any(test, feature = "test-utils"))]
57#[doc(hidden)]
58pub mod test_support;
59pub mod worker;
60
61pub use xmtp_archive::archive_options::{ArchiveOptions, BackupElementSelection};
62
63/// Encode sync content as the `EncodedContent` bytes of a sync message.
64///
65/// Sync content can hold an HMAC root key. Every buffer that holds it here is
66/// wiped: the key fields of `content` after encoding, the inner encoding, and
67/// the returned bytes when the caller drops them.
68fn sync_message_bytes(content: ContentProto) -> Zeroizing<Vec<u8>> {
69    let mut content = DeviceSyncContentProto {
70        content: Some(content),
71    };
72    // `encode_to_vec` sizes its buffer up front, so it never frees a partial copy.
73    let inner = content.encode_to_vec();
74    if let Some(content) = &mut content.content {
75        wipe_hmac_keys(content);
76    }
77    let mut encoded = EncodedContent {
78        r#type: Some(ContentTypeId {
79            authority_id: "xmtp.org".to_string(),
80            type_id: "application/x-protobuf".to_string(),
81            version_major: 1,
82            version_minor: 0,
83        }),
84        parameters: Default::default(),
85        fallback: None,
86        compression: None,
87        content: inner,
88    };
89    let bytes = Zeroizing::new(encoded.encode_to_vec());
90    encoded.content.zeroize();
91    bytes
92}
93
94/// Wipe the HMAC root key of every preference update in `content`.
95fn wipe_hmac_keys(content: &mut ContentProto) {
96    if let ContentProto::PreferenceUpdates(updates) = content {
97        for update in &mut updates.updates {
98            if let Some(PreferenceUpdateProto::Hmac(hmac)) = &mut update.update {
99                hmac.key.zeroize();
100            }
101        }
102    }
103}
104
105/// Move a stored sync message's plaintext into a buffer wiped on drop. It
106/// can hold an HMAC root key, so it moves as the row loads, before any
107/// path out can drop it.
108fn take_plaintext(msg: &mut StoredGroupMessage) -> Zeroizing<Vec<u8>> {
109    Zeroizing::new(std::mem::take(&mut msg.decrypted_message_bytes))
110}
111
112/// [`take_plaintext`] for every loaded row.
113fn with_plaintext(rows: Vec<StoredGroupMessage>) -> Vec<(StoredGroupMessage, Zeroizing<Vec<u8>>)> {
114    rows.into_iter()
115        .map(|mut msg| {
116            let plaintext = take_plaintext(&mut msg);
117            (msg, plaintext)
118        })
119        .collect()
120}
121
122/// Sync content decoded from a received message. Its HMAC root keys are wiped
123/// on drop, on every path out of processing.
124pub struct ReceivedContent(
125    /// The decoded content. Suites outside the crate read it under
126    /// `test-utils`.
127    #[cfg(any(test, feature = "test-utils"))]
128    pub ContentProto,
129    #[cfg(not(any(test, feature = "test-utils")))] pub(crate) ContentProto,
130);
131
132impl Drop for ReceivedContent {
133    fn drop(&mut self) {
134        wipe_hmac_keys(&mut self.0);
135    }
136}
137
138/// The id of the group [`DeviceSyncClient::primary_sync_group`] selects,
139/// read in the caller's write.
140// implements: SYNC-002, SYNC-010
141pub(crate) fn selected_sync_group_in<T: TransactionalKeyStore>(
142    tx: &mut StateTx<'_, T>,
143    own_inbox_id: &str,
144) -> Result<Option<GroupId>, GroupError> {
145    let groups = tx.storage().db().all_sync_groups()?;
146    for stored in groups {
147        let own = tx.with_group(stored.id, |group, _| {
148            Ok::<_, GroupError>(is_own_sync_group(
149                own_inbox_id,
150                &stored.added_by_inbox_id,
151                group.members(),
152            ))
153        })?;
154        if own {
155            return Ok(Some(stored.id));
156        }
157    }
158    Ok(None)
159}
160
161#[derive(Debug, Error, ErrorCode)]
162pub enum DeviceSyncError {
163    /// I/O error.
164    ///
165    /// File system or network I/O failed. May be retryable.
166    #[error("IO error: {0}")]
167    IO(#[from] std::io::Error),
168    /// Serialization error.
169    ///
170    /// JSON serialization/deserialization failed. Retryable.
171    #[error("Serialization/Deserialization Error {0}")]
172    Serde(#[from] serde_json::Error),
173    #[error(transparent)]
174    #[error_code(inherit)]
175    ProtoConversion(#[from] xmtp_proto::ConversionError),
176    /// AES-GCM encryption error.
177    ///
178    /// Encryption/decryption of sync payload failed. Retryable.
179    #[error("AES-GCM encryption error")]
180    AesGcm(#[from] aes_gcm::Error),
181    #[error("storage error: {0}")]
182    #[error_code(inherit)]
183    Storage(#[from] StorageError),
184    /// Type conversion error.
185    ///
186    /// Internal type conversion failed. Retryable.
187    #[error("type conversion error")]
188    Conversion,
189    /// UTF-8 error.
190    ///
191    /// String is not valid UTF-8. Retryable.
192    #[error("utf-8 error: {0}")]
193    UTF8(#[from] std::str::Utf8Error),
194    #[error("identity update error: {0}")]
195    #[error_code(inherit)]
196    IdentityUpdate(#[from] IdentityUpdateError),
197    #[error("group error: {0}")]
198    #[error_code(inherit)]
199    Group(#[from] GroupError),
200    /// Invalid payload.
201    ///
202    /// Sync message payload is malformed. Retryable.
203    #[error("invalid history message payload")]
204    InvalidPayload,
205    /// Unspecified sync kind.
206    ///
207    /// Device sync kind not specified. Not retryable.
208    #[error("unspecified device sync kind")]
209    UnspecifiedDeviceSyncKind,
210    /// Archive error.
211    ///
212    /// Sync archive operation failed. Retryable.
213    #[error(transparent)]
214    Archive(#[from] ArchiveError),
215    /// Decode error.
216    ///
217    /// Protobuf decoding failed. Retryable.
218    #[error(transparent)]
219    Decode(#[from] prost::DecodeError),
220    #[error(transparent)]
221    #[error_code(inherit)]
222    Deserialization(#[from] DeserializationError),
223    /// Missing sync group.
224    ///
225    /// Sync group not found. Not retryable.
226    #[error("Missing sync group")]
227    MissingSyncGroup,
228    #[error(transparent)]
229    #[error_code(inherit)]
230    Db(#[from] xmtp_db::ConnectionError),
231    /// Sync summary.
232    ///
233    /// Sync completed with errors. May be retryable.
234    #[error("{}", _0.to_string())]
235    Sync(#[source] Box<SyncSummary>),
236    /// MLS store error.
237    ///
238    /// OpenMLS key store operation failed. Retryable.
239    #[error(transparent)]
240    MlsStore(#[from] MlsStoreError),
241    /// Receive error.
242    ///
243    /// Channel receive failed. Retryable.
244    #[error(transparent)]
245    Recv(#[from] RecvError),
246    /// Missing field.
247    ///
248    /// Required field not present. Retryable.
249    #[error("Missing Field: {0:?} {1}")]
250    MissingField(MissingField, String),
251    // The own identity state could not be read; a sync publish waits for it.
252    #[error("own identity state unavailable: {0}")]
253    #[error_code(inherit)]
254    OwnStateUnavailable(#[source] IdentityUpdateError),
255    /// Outbox page unpublished.
256    ///
257    /// A queued sync message is not published yet; its values stay owed and
258    /// the outbox retries. Retryable.
259    #[error("a queued sync message is not published yet")]
260    OutboxPageUnpublished,
261}
262
263#[derive(Debug)]
264pub enum MissingField {
265    Conversation(ConversationField),
266}
267#[derive(Debug)]
268pub enum ConversationField {
269    DmId,
270}
271
272impl From<SyncSummary> for DeviceSyncError {
273    fn from(value: SyncSummary) -> Self {
274        DeviceSyncError::Sync(Box::new(value))
275    }
276}
277
278impl NeedsDbReconnect for DeviceSyncError {
279    fn restart_delay(&self) -> Option<xmtp_common::time::Duration> {
280        RetryableError::rate_limit_delay(self)
281    }
282
283    #[deny(clippy::wildcard_enum_match_arm)]
284    fn needs_db_reconnect(&self) -> bool {
285        match self {
286            Self::IdentityUpdate(e) => e.needs_db_reconnect(),
287            Self::Storage(s) => s.db_needs_connection(),
288            // A dropped pool can hide in these wrapped errors; forward so the
289            // worker stops instead of hot-looping.
290            Self::Db(c) => c.db_needs_connection(),
291            Self::Group(e) => e.needs_db_reconnect(),
292            Self::MlsStore(e) => e.needs_db_reconnect(),
293            Self::OwnStateUnavailable(e) => e.needs_db_reconnect(),
294            Self::Sync(summary) => summary.needs_db_reconnect(),
295            Self::Archive(ArchiveError::Storage(s)) => s.db_needs_connection(),
296            Self::Archive(_)
297            | Self::IO(..)
298            | Self::Serde(..)
299            | Self::ProtoConversion(..)
300            | Self::AesGcm(..)
301            | Self::Conversion
302            | Self::UTF8(..)
303            | Self::InvalidPayload
304            | Self::UnspecifiedDeviceSyncKind
305            | Self::Decode(..)
306            | Self::Deserialization(..)
307            | Self::MissingSyncGroup
308            | Self::Recv(..)
309            | Self::MissingField(..)
310            | Self::OutboxPageUnpublished => false,
311        }
312    }
313}
314
315impl RetryableError for DeviceSyncError {
316    fn is_retryable(&self) -> bool {
317        !matches!(
318            self,
319            Self::MissingSyncGroup | Self::UnspecifiedDeviceSyncKind
320        )
321    }
322
323    fn rate_limit_delay(&self) -> Option<xmtp_common::time::Duration> {
324        match self {
325            Self::IdentityUpdate(e) => e.rate_limit_delay(),
326            Self::Group(e) => e.rate_limit_delay(),
327            Self::Sync(e) => e.rate_limit_delay(),
328            Self::MlsStore(e) => e.rate_limit_delay(),
329            Self::OwnStateUnavailable(e) => e.rate_limit_delay(),
330            _ => None,
331        }
332    }
333}
334
335impl From<NotFound> for DeviceSyncError {
336    fn from(value: NotFound) -> Self {
337        DeviceSyncError::Storage(StorageError::NotFound(value))
338    }
339}
340
341#[derive(Clone)]
342pub struct DeviceSyncClient<Context> {
343    pub(crate) context: Context,
344    pub(crate) metrics: Arc<WorkerMetrics<SyncMetric>>,
345}
346
347impl<Context: XmtpSharedContext> DeviceSyncClient<Context> {
348    pub fn new(context: Context, metrics: Arc<WorkerMetrics<SyncMetric>>) -> Self {
349        Self { context, metrics }
350    }
351}
352
353impl<Context> DeviceSyncClient<Context>
354where
355    Context: XmtpSharedContext,
356{
357    pub fn inbox_id(&self) -> InboxIdRef<'_> {
358        self.context.identity().inbox_id()
359    }
360
361    pub fn installation_id(&self) -> InstallationId {
362        self.context.installation_id()
363    }
364
365    pub fn db(&self) -> <Context::Db as XmtpDb>::DbQuery {
366        self.context.db()
367    }
368
369    /// Blocks until the sync worker notifies that it is initialized and running.
370    pub async fn wait_for_sync_worker_init(&self) -> Result<(), xmtp_common::time::Expired> {
371        self.metrics.wait_for_init().await
372    }
373
374    /// Publish every owed value to the selected sync group, a page at
375    /// a time. A page's marks clear only after the message carrying it is
376    /// published.
377    // implements: SYNC-004, SYNC-034, SYNC-029, SYNC-033
378    #[tracing::instrument(level = "debug", skip_all, fields(operation = "publish_outbox"))]
379    pub async fn publish_outbox(&self) -> Result<(), DeviceSyncError> {
380        // A quarter of the deployment's envelope, so MLS and envelope framing fit.
381        let max_bytes = (self.context.api().limits().max_envelope_bytes / 4).min(PAGE_BYTES);
382        self.get_sync_group().await?;
383        // One add per pass; the stored retry repeats it after the interval.
384        let mut add_tried = false;
385        loop {
386            // Values first, target second. A sync Welcome that commits after
387            // this read marks every key again, so the clear below skips them.
388            // One that committed before it is already the selected group.
389            let page = owed_page(&self.db(), PAGE_UPDATES, max_bytes)?;
390            if page.is_empty() {
391                return Ok(());
392            }
393            let group = self
394                .primary_sync_group()?
395                .ok_or(DeviceSyncError::MissingSyncGroup)?;
396            // implements: SYNC-034
397            let gap = self.own_membership_gap(&group).await?;
398            if gap.missing && !add_tried {
399                add_tried = true;
400                // A failed add holds no page back, unless a revoked leaf may
401                // stay or the add must wait out a rate limit.
402                // implements: RATE-041
403                if let Err(e) = group.add_missing_installations().await {
404                    if gap.revoked || e.needs_db_reconnect() || e.rate_limit_delay().is_some() {
405                        return Err(e.into());
406                    }
407                    tracing::warn!(error = %e, "adding own installations failed");
408                }
409            } else if gap.revoked {
410                group.remove_revoked_installations().await?;
411            }
412            if gap.missing || gap.revoked {
413                let gap = self.own_membership_gap(&group).await?;
414                if gap.revoked {
415                    return Err(GroupError::InvalidGroupMembership.into());
416                }
417                // The leaves present still get this page; the task retries
418                // the add once the retry interval has passed.
419                if gap.retriable {
420                    let interval = SYNC_UPDATE_INSTALLATIONS_INTERVAL_NS as u64;
421                    let delay = xmtp_common::time::Duration::from_nanos(interval);
422                    self.schedule_add_missing_installations_task(group.group_id, Some(delay))?;
423                }
424            }
425            // One intent at a time: a page an earlier pass queued is
426            // published, or fails for good, before this one is queued.
427            group.sync_until_last_intent_resolved().await?;
428            tracing::info!(
429                group_id = group.group_id.short_hex(),
430                "publishing owed preferences"
431            );
432            let id = group.prepare_message(
433                &sync_message_bytes(page_content(&page)),
434                send_message_opts::SendMessageOpts {
435                    should_push: false,
436                    idempotency_key: None,
437                },
438            )?;
439            group.sync_until_last_intent_resolved().await?;
440            // Only a published page clears its marks. Otherwise they stay
441            // owed, the pass backs off, and a later pass sends them again.
442            let status = self.db().get_group_message(&id)?.map(|mut sent| {
443                drop(take_plaintext(&mut sent));
444                sent.delivery_status
445            });
446            #[cfg(any(test, feature = "test-hooks"))]
447            let status = UNCONFIRMED_NEXT_PAGE
448                .lock()
449                .take_if(|installation| *installation == self.installation_id().as_slice())
450                .map_or(status, |_| None);
451            if status != Some(DeliveryStatus::Published) {
452                return Err(DeviceSyncError::OutboxPageUnpublished);
453            }
454            clear_owed(&self.db(), &page)?;
455            for _ in &page.consent {
456                self.metrics.increment_metric(SyncMetric::ConsentSent);
457            }
458            if page.root_key.is_some() {
459                self.metrics.increment_metric(SyncMetric::HmacSent);
460            }
461        }
462    }
463
464    /// One outbox pass, then one receive pass, as the worker runs them.
465    #[cfg(any(test, feature = "test-utils"))]
466    pub async fn sync_passes_for_test(&self) -> Result<(), DeviceSyncError> {
467        self.publish_outbox().await?;
468        self.process_sync_group_messages().await
469    }
470
471    /// How `group`'s leaves differ from the newest own association state held
472    /// locally: an associated installation without a leaf, or a leaf other
473    /// than this installation's that the state does not associate.
474    async fn own_membership_gap(
475        &self,
476        group: &MlsGroup<Context>,
477    ) -> Result<MembershipGap, DeviceSyncError> {
478        // implements: SYNC-034. An unreadable own state, such as a smart-wallet
479        // signature that needs the verifier, means not yet (as the receive path does).
480        let own = match IdentityUpdates::new(&self.context)
481            .get_association_state(&self.db(), self.inbox_id(), None)
482            .await
483        {
484            Ok(state) => state.installation_ids(),
485            Err(e) if e.needs_db_reconnect() => return Err(e.into()),
486            Err(e) => return Err(DeviceSyncError::OwnStateUnavailable(e)),
487        };
488        let me = self.installation_id();
489        Ok(group.with_group_snapshot(|mls_group| {
490            let missing = own.iter().any(|installation| {
491                !mls_group
492                    .members()
493                    .any(|member| member.signature_key == *installation)
494            });
495            let gate = LibXMTPVersion::parse(INSTALLATION_RETRY_MIN_PROTOCOL_VERSION).ok();
496            Ok(MembershipGap {
497                missing,
498                revoked: mls_group.members().any(|member| {
499                    member.signature_key != me.as_slice() && !own.contains(&member.signature_key)
500                }),
501                retriable: missing
502                    && gate.is_some_and(|gate| {
503                        committed_floor_at_least(mls_group.extensions(), &gate)
504                    }),
505            })
506        })?)
507    }
508
509    /// Add the own installations that sync group `group` lacks. `true` while
510    /// it is the selected group and one it can retry still has no leaf.
511    pub async fn retry_own_installations(
512        &self,
513        group: &MlsGroup<Context>,
514    ) -> Result<bool, DeviceSyncError> {
515        group.add_missing_installations().await?;
516        if self
517            .primary_sync_group()?
518            .is_none_or(|selected| selected.group_id != group.group_id)
519        {
520            return Ok(false);
521        }
522        Ok(self.own_membership_gap(group).await?.retriable)
523    }
524
525    /// The newest sync group that only the own inbox is in.
526    /// Older builds stored sync groups from other inboxes; this skips them.
527    // implements: SYNC-002, SYNC-010
528    pub fn primary_sync_group(&self) -> Result<Option<MlsGroup<Context>>, GroupError> {
529        let own_inbox_id = self.context.inbox_id();
530        for stored in self.context.db().all_sync_groups()? {
531            let group = MlsGroup::load_by_id(&self.context, &stored.id)?;
532            let own = group.with_group_snapshot(|mls_group| {
533                Ok(is_own_sync_group(
534                    own_inbox_id,
535                    &stored.added_by_inbox_id,
536                    mls_group.members(),
537                ))
538            })?;
539            if own {
540                return Ok(Some(group));
541            }
542            tracing::debug!(
543                group_id = %stored.id,
544                "skipping a sync group that names another inbox"
545            );
546        }
547        Ok(None)
548    }
549
550    // implements: SYNC-001
551    #[instrument(level = "trace", skip_all)]
552    pub async fn get_sync_group(&self) -> Result<MlsGroup<Context>, GroupError> {
553        let sync_group = match self.primary_sync_group()? {
554            Some(sync_group) => sync_group,
555            None => {
556                let sync_group = MlsGroup::create_and_insert(
557                    self.context.clone(),
558                    ConversationType::Sync,
559                    PreconfiguredPolicies::default().to_policy_set(),
560                    GroupMetadataOptions::default(),
561                    None,
562                )?;
563                tracing::info!(
564                    "Creating sync group: {}",
565                    xmtp_common::fmt::debug_hex(sync_group.group_id)
566                );
567                if let Err(inline_err) = sync_group.add_missing_installations().await {
568                    // A rate-limited add is not resent before its delay.
569                    // implements: RATE-041
570                    self.schedule_add_missing_installations_task(
571                        sync_group.group_id,
572                        inline_err.rate_limit_delay(),
573                    )?;
574                    return Err(inline_err);
575                }
576                // The task checks for missing leaves even after an Ok inline add.
577                sync_group.sync_with_conn().await?;
578
579                self.metrics.increment_metric(SyncMetric::SyncGroupCreated);
580
581                sync_group
582            }
583        };
584
585        Ok(sync_group)
586    }
587
588    /// Arm the sync group's reconcile task for `group_id`, due once `delay`
589    /// has passed. It is kept until it finishes, whatever its failures.
590    pub fn schedule_add_missing_installations_task(
591        &self,
592        group_id: GroupId,
593        delay: Option<xmtp_common::time::Duration>,
594    ) -> Result<(), StorageError> {
595        schedule_add_missing_installations(
596            &self.context.db(),
597            self.context.events(),
598            group_id,
599            delay,
600            true,
601        )
602    }
603
604    /// Schedule the adds to the user's conversations for a new installation.
605    #[cfg(any(test, feature = "test-utils"))]
606    pub fn schedule_add_installations_to_groups(&self) -> Result<usize, DeviceSyncError> {
607        Ok(xmtp_mls_core::sync_tasks::schedule_newcomer_adds(
608            &self.context.db(),
609            self.context.events(),
610        )?)
611    }
612}
613
614/// How a sync group's leaves differ from the own inbox's installations.
615struct MembershipGap {
616    missing: bool,
617    revoked: bool,
618    /// Missing, and the group's floor admits own-installation retries.
619    retriable: bool,
620}
621
622/// Test-only fault: the next outbox page of this installation reads back as
623/// not published, as when its confirmation fails after the backend took it.
624#[cfg(any(test, feature = "test-hooks"))]
625#[doc(hidden)]
626pub static UNCONFIRMED_NEXT_PAGE: parking_lot::Mutex<Option<Vec<u8>>> =
627    parking_lot::Mutex::new(None);
628
629/// Records per sync message the outbox sends.
630const PAGE_UPDATES: usize = 1_000;
631/// Bytes of encoded updates per sync message.
632const PAGE_BYTES: usize = 256 * 1024;
633
634/// The sync content of an outbox page. It holds a plain copy of the root key;
635/// `sync_message_bytes` wipes it.
636fn page_content(page: &OwedPage) -> ContentProto {
637    let root_key = page.root_key.iter().map(|root| {
638        PreferenceUpdateProto::Hmac(HmacKeyUpdate {
639            key: root.key.as_slice().to_vec(),
640            cycled_at_ns: root.cycled_at_ns,
641        })
642    });
643    let consent = page
644        .consent
645        .iter()
646        .map(|record| PreferenceUpdateProto::Consent(record.clone().into()));
647    ContentProto::PreferenceUpdates(PreferenceUpdates {
648        updates: root_key
649            .chain(consent)
650            .map(|update| PreferenceUpdateMessage {
651                update: Some(update),
652            })
653            .collect(),
654    })
655}
656
657/// The payload of a sync message's outer `EncodedContent`, the only field the
658/// worker reads. It can hold an HMAC root key, so it is wiped on drop, also
659/// when prost drops a value whose decode fails part way.
660#[derive(Clone, PartialEq, prost::Message)]
661struct SyncPayload {
662    #[prost(bytes = "vec", tag = "4")]
663    content: Vec<u8>,
664}
665
666impl Drop for SyncPayload {
667    fn drop(&mut self) {
668        self.content.zeroize();
669    }
670}
671
672/// Decode a received sync message: the outer `EncodedContent`, then the
673/// supported device-sync content inside it.
674pub(crate) fn decode_sync_message(plaintext: &[u8]) -> Option<ReceivedContent> {
675    let payload = SyncPayload::decode(decode_buffer(plaintext)).ok()?;
676    decode_supported_content(&payload.content)
677}
678
679/// A copy of `bytes` for prost to decode. prost decodes a bytes field of a
680/// `&[u8]` through a temporary copy that it frees unwiped; from `Bytes` it
681/// takes a slice instead. This copy is wiped on drop.
682fn decode_buffer(bytes: &[u8]) -> bytes::Bytes {
683    bytes::Bytes::from_owner(Zeroizing::new(bytes.to_vec()))
684}
685
686/// Decode only device-sync content that this client supports.
687///
688/// Old archive transfer fields decode as an unset oneof after their field
689/// numbers became reserved. Ignore them so older installations do not make
690/// the sync worker fail or retry the message.
691///
692/// `bytes` can hold an HMAC root key: the caller wipes them, and the content
693/// wipes its keys on drop.
694fn decode_supported_content(bytes: &[u8]) -> Option<ReceivedContent> {
695    DeviceSyncContentProto::decode(decode_buffer(bytes))
696        .ok()?
697        .content
698        .map(ReceivedContent)
699}
700
701#[cfg_attr(not(target_arch = "wasm32"), ctor::ctor(unsafe))]
702#[cfg(all(test, not(target_arch = "wasm32")))]
703fn test_setup() {
704    xmtp_common::logger();
705    let _ = fdlimit::raise_fd_limit();
706}