1#![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
63fn sync_message_bytes(content: ContentProto) -> Zeroizing<Vec<u8>> {
69 let mut content = DeviceSyncContentProto {
70 content: Some(content),
71 };
72 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
94fn 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
105fn take_plaintext(msg: &mut StoredGroupMessage) -> Zeroizing<Vec<u8>> {
109 Zeroizing::new(std::mem::take(&mut msg.decrypted_message_bytes))
110}
111
112fn 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
122pub struct ReceivedContent(
125 #[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
138pub(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 #[error("IO error: {0}")]
167 IO(#[from] std::io::Error),
168 #[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 #[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 #[error("type conversion error")]
188 Conversion,
189 #[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 #[error("invalid history message payload")]
204 InvalidPayload,
205 #[error("unspecified device sync kind")]
209 UnspecifiedDeviceSyncKind,
210 #[error(transparent)]
214 Archive(#[from] ArchiveError),
215 #[error(transparent)]
219 Decode(#[from] prost::DecodeError),
220 #[error(transparent)]
221 #[error_code(inherit)]
222 Deserialization(#[from] DeserializationError),
223 #[error("Missing sync group")]
227 MissingSyncGroup,
228 #[error(transparent)]
229 #[error_code(inherit)]
230 Db(#[from] xmtp_db::ConnectionError),
231 #[error("{}", _0.to_string())]
235 Sync(#[source] Box<SyncSummary>),
236 #[error(transparent)]
240 MlsStore(#[from] MlsStoreError),
241 #[error(transparent)]
245 Recv(#[from] RecvError),
246 #[error("Missing Field: {0:?} {1}")]
250 MissingField(MissingField, String),
251 #[error("own identity state unavailable: {0}")]
253 #[error_code(inherit)]
254 OwnStateUnavailable(#[source] IdentityUpdateError),
255 #[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 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 pub async fn wait_for_sync_worker_init(&self) -> Result<(), xmtp_common::time::Expired> {
371 self.metrics.wait_for_init().await
372 }
373
374 #[tracing::instrument(level = "debug", skip_all, fields(operation = "publish_outbox"))]
379 pub async fn publish_outbox(&self) -> Result<(), DeviceSyncError> {
380 let max_bytes = (self.context.api().limits().max_envelope_bytes / 4).min(PAGE_BYTES);
382 self.get_sync_group().await?;
383 let mut add_tried = false;
385 loop {
386 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 let gap = self.own_membership_gap(&group).await?;
398 if gap.missing && !add_tried {
399 add_tried = true;
400 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 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 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 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 #[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 async fn own_membership_gap(
475 &self,
476 group: &MlsGroup<Context>,
477 ) -> Result<MembershipGap, DeviceSyncError> {
478 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 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 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 #[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 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 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 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 #[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
614struct MembershipGap {
616 missing: bool,
617 revoked: bool,
618 retriable: bool,
620}
621
622#[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
629const PAGE_UPDATES: usize = 1_000;
631const PAGE_BYTES: usize = 256 * 1024;
633
634fn 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#[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
672pub(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
679fn decode_buffer(bytes: &[u8]) -> bytes::Bytes {
683 bytes::Bytes::from_owner(Zeroizing::new(bytes.to_vec()))
684}
685
686fn 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}