deltachat/
sync.rs

1//! # Synchronize items between devices.
2
3use anyhow::Result;
4use mail_builder::mime::MimePart;
5use serde::{Deserialize, Serialize};
6
7use crate::chat::{self, ChatId};
8use crate::config::Config;
9use crate::constants::Blocked;
10use crate::contact::ContactId;
11use crate::context::Context;
12use crate::log::LogExt;
13use crate::log::{info, warn};
14use crate::message::{Message, MsgId, Viewtype};
15use crate::mimeparser::SystemMessage;
16use crate::param::Param;
17use crate::sync::SyncData::{AddQrToken, AlterChat, DeleteQrToken};
18use crate::token::Namespace;
19use crate::tools::time;
20use crate::{message, stock_str, token};
21use std::collections::HashSet;
22
23/// Whether to send device sync messages. Aimed for usage in the internal API.
24#[derive(Debug, PartialEq)]
25pub(crate) enum Sync {
26    Nosync,
27    Sync,
28}
29
30impl From<Sync> for bool {
31    fn from(sync: Sync) -> bool {
32        match sync {
33            Sync::Nosync => false,
34            Sync::Sync => true,
35        }
36    }
37}
38
39impl From<bool> for Sync {
40    fn from(sync: bool) -> Sync {
41        match sync {
42            false => Sync::Nosync,
43            true => Sync::Sync,
44        }
45    }
46}
47
48#[derive(Debug, Serialize, Deserialize)]
49pub(crate) struct QrTokenData {
50    pub(crate) invitenumber: String,
51    pub(crate) auth: String,
52    pub(crate) grpid: Option<String>,
53}
54
55#[derive(Debug, Serialize, Deserialize)]
56pub(crate) enum SyncData {
57    AddQrToken(QrTokenData),
58    DeleteQrToken(QrTokenData),
59    AlterChat {
60        id: chat::SyncId,
61        action: chat::SyncAction,
62    },
63    Config {
64        key: Config,
65        val: String,
66    },
67    SaveMessage {
68        src: String,  // RFC724 id (i.e. "Message-Id" header)
69        dest: String, // RFC724 id (i.e. "Message-Id" header)
70    },
71    DeleteMessages {
72        msgs: Vec<String>, // RFC724 id (i.e. "Message-Id" header)
73    },
74}
75
76#[derive(Debug, Serialize, Deserialize)]
77#[serde(untagged)]
78pub(crate) enum SyncDataOrUnknown {
79    SyncData(SyncData),
80    Unknown(serde_json::Value),
81}
82
83#[derive(Debug, Serialize, Deserialize)]
84pub(crate) struct SyncItem {
85    timestamp: i64,
86
87    data: SyncDataOrUnknown,
88}
89
90#[derive(Debug, Deserialize)]
91pub(crate) struct SyncItems {
92    items: Vec<SyncItem>,
93}
94
95impl From<SyncData> for SyncDataOrUnknown {
96    fn from(sync_data: SyncData) -> Self {
97        Self::SyncData(sync_data)
98    }
99}
100
101impl Context {
102    /// Adds an item to the list of items that should be synchronized to other devices.
103    ///
104    /// NB: Private and `pub(crate)` functions shouldn't call this unless `Sync::Sync` is explicitly
105    /// passed to them. This way it's always clear whether the code performs synchronisation.
106    pub(crate) async fn add_sync_item(&self, data: SyncData) -> Result<()> {
107        self.add_sync_item_with_timestamp(data, time()).await
108    }
109
110    /// Adds item and timestamp to the list of items that should be synchronized to other devices.
111    /// If device synchronization is disabled, the function does nothing.
112    async fn add_sync_item_with_timestamp(&self, data: SyncData, timestamp: i64) -> Result<()> {
113        if !self.should_send_sync_msgs().await? {
114            return Ok(());
115        }
116
117        let item = SyncItem {
118            timestamp,
119            data: data.into(),
120        };
121        let item = serde_json::to_string(&item)?;
122        self.sql
123            .execute("INSERT INTO multi_device_sync (item) VALUES(?);", (item,))
124            .await?;
125
126        Ok(())
127    }
128
129    /// Adds most recent qr-code tokens for the given group or self-contact to the list of items to
130    /// be synced. If device synchronization is disabled,
131    /// no tokens exist or the chat is unpromoted, the function does nothing.
132    /// The caller should call `SchedulerState::interrupt_inbox()` on its own to trigger sending.
133    pub(crate) async fn sync_qr_code_tokens(&self, grpid: Option<&str>) -> Result<()> {
134        if !self.should_send_sync_msgs().await? {
135            return Ok(());
136        }
137        if let (Some(invitenumber), Some(auth)) = (
138            token::lookup(self, Namespace::InviteNumber, grpid).await?,
139            token::lookup(self, Namespace::Auth, grpid).await?,
140        ) {
141            self.add_sync_item(SyncData::AddQrToken(QrTokenData {
142                invitenumber,
143                auth,
144                grpid: grpid.map(|s| s.to_string()),
145            }))
146            .await?;
147        }
148        Ok(())
149    }
150
151    /// Adds deleted qr-code token to the list of items to be synced
152    /// so that the token also gets deleted on the other devices.
153    /// This interrupts SMTP on its own.
154    pub(crate) async fn sync_qr_code_token_deletion(
155        &self,
156        invitenumber: String,
157        auth: String,
158    ) -> Result<()> {
159        self.add_sync_item(SyncData::DeleteQrToken(QrTokenData {
160            invitenumber,
161            auth,
162            grpid: None,
163        }))
164        .await?;
165        self.scheduler.interrupt_inbox().await;
166        Ok(())
167    }
168
169    /// Sends out a self-sent message with items to be synchronized, if any.
170    ///
171    /// Mustn't be called from multiple tasks in parallel to avoid sending the same sync items twice
172    /// because sync items are removed from the db only after successful sending. We guarantee this
173    /// by calling `send_sync_msg()` only from the inbox loop.
174    pub async fn send_sync_msg(&self) -> Result<Option<MsgId>> {
175        if let Some((json, ids)) = self.build_sync_json().await? {
176            let chat_id =
177                ChatId::create_for_contact_with_blocked(self, ContactId::SELF, Blocked::Yes)
178                    .await?;
179            let mut msg = Message {
180                chat_id,
181                viewtype: Viewtype::Text,
182                text: stock_str::sync_msg_body(self).await,
183                hidden: true,
184                subject: stock_str::sync_msg_subject(self).await,
185                ..Default::default()
186            };
187            msg.param.set_cmd(SystemMessage::MultiDeviceSync);
188            msg.param.set(Param::Arg, json);
189            msg.param.set(Param::Arg2, ids);
190            msg.param.set_int(Param::GuaranteeE2ee, 1);
191            Ok(Some(chat::send_msg(self, chat_id, &mut msg).await?))
192        } else {
193            Ok(None)
194        }
195    }
196
197    /// Copies all sync items to a JSON string and clears the sync-table.
198    /// Returns the JSON string and a comma-separated string of the IDs used.
199    pub(crate) async fn build_sync_json(&self) -> Result<Option<(String, String)>> {
200        let (ids, serialized) = self
201            .sql
202            .query_map(
203                "SELECT id, item FROM multi_device_sync ORDER BY id;",
204                (),
205                |row| Ok((row.get::<_, u32>(0)?, row.get::<_, String>(1)?)),
206                |rows| {
207                    let mut ids = vec![];
208                    let mut serialized = String::default();
209                    for row in rows {
210                        let (id, item) = row?;
211                        ids.push(id);
212                        if !serialized.is_empty() {
213                            serialized.push_str(",\n");
214                        }
215                        serialized.push_str(&item);
216                    }
217                    Ok((ids, serialized))
218                },
219            )
220            .await?;
221
222        if ids.is_empty() {
223            Ok(None)
224        } else {
225            Ok(Some((
226                format!("{{\"items\":[\n{serialized}\n]}}"),
227                ids.iter()
228                    .map(|x| x.to_string())
229                    .collect::<Vec<String>>()
230                    .join(","),
231            )))
232        }
233    }
234
235    pub(crate) fn build_sync_part(&self, json: String) -> MimePart<'static> {
236        MimePart::new("application/json", json).attachment("multi-device-sync.json")
237    }
238
239    /// Takes a JSON string created by `build_sync_json()`
240    /// and construct `SyncItems` from it.
241    pub(crate) fn parse_sync_items(&self, serialized: String) -> Result<SyncItems> {
242        let sync_items: SyncItems = serde_json::from_str(&serialized)?;
243        Ok(sync_items)
244    }
245
246    /// Executes sync items sent by other device.
247    ///
248    /// CAVE: When changing the code to handle other sync items,
249    /// take care that does not result in calls to `add_sync_item()`
250    /// as otherwise we would add in a dead-loop between two devices
251    /// sending message back and forth.
252    ///
253    /// If an error is returned, the caller shall not try over because some sync items could be
254    /// already executed. Sync items are considered independent and executed in the given order but
255    /// regardless of whether executing of the previous items succeeded.
256    pub(crate) async fn execute_sync_items(&self, items: &SyncItems) {
257        info!(self, "executing {} sync item(s)", items.items.len());
258        for item in &items.items {
259            match &item.data {
260                SyncDataOrUnknown::SyncData(data) => match data {
261                    AddQrToken(token) => self.add_qr_token(token).await,
262                    DeleteQrToken(token) => self.delete_qr_token(token).await,
263                    AlterChat { id, action } => self.sync_alter_chat(id, action).await,
264                    SyncData::Config { key, val } => self.sync_config(key, val).await,
265                    SyncData::SaveMessage { src, dest } => self.save_message(src, dest).await,
266                    SyncData::DeleteMessages { msgs } => self.sync_message_deletion(msgs).await,
267                },
268                SyncDataOrUnknown::Unknown(data) => {
269                    warn!(self, "Ignored unknown sync item: {data}.");
270                    Ok(())
271                }
272            }
273            .log_err(self)
274            .ok();
275        }
276
277        // Since there was a sync message, we know that there is a second device.
278        // Set BccSelf to true if it isn't already.
279        if !items.items.is_empty() && !self.get_config_bool(Config::BccSelf).await.unwrap_or(true) {
280            self.set_config_ex(Sync::Nosync, Config::BccSelf, Some("1"))
281                .await
282                .log_err(self)
283                .ok();
284        }
285    }
286
287    async fn add_qr_token(&self, token: &QrTokenData) -> Result<()> {
288        let grpid = token.grpid.as_deref();
289        token::save(self, Namespace::InviteNumber, grpid, &token.invitenumber).await?;
290        token::save(self, Namespace::Auth, grpid, &token.auth).await?;
291        Ok(())
292    }
293
294    async fn delete_qr_token(&self, token: &QrTokenData) -> Result<()> {
295        self.sql
296            .execute(
297                "DELETE FROM tokens
298                 WHERE foreign_key IN
299                 (SELECT foreign_key FROM tokens
300                  WHERE token=? OR token=?)",
301                (&token.invitenumber, &token.auth),
302            )
303            .await?;
304        Ok(())
305    }
306
307    async fn save_message(&self, src_rfc724_mid: &str, dest_rfc724_mid: &String) -> Result<()> {
308        if let Some((src_msg_id, _)) = message::rfc724_mid_exists(self, src_rfc724_mid).await? {
309            chat::save_copy_in_self_talk(self, src_msg_id, dest_rfc724_mid).await?;
310        }
311        Ok(())
312    }
313
314    async fn sync_message_deletion(&self, msgs: &Vec<String>) -> Result<()> {
315        let mut modified_chat_ids = HashSet::new();
316        let mut msg_ids = Vec::new();
317        for rfc724_mid in msgs {
318            if let Some((msg_id, _)) = message::rfc724_mid_exists(self, rfc724_mid).await? {
319                if let Some(msg) = Message::load_from_db_optional(self, msg_id).await? {
320                    message::delete_msg_locally(self, &msg).await?;
321                    msg_ids.push(msg.id);
322                    modified_chat_ids.insert(msg.chat_id);
323                } else {
324                    warn!(self, "Sync message delete: Database entry does not exist.");
325                }
326            } else {
327                warn!(self, "Sync message delete: {rfc724_mid:?} not found.");
328            }
329        }
330        message::delete_msgs_locally_done(self, &msg_ids, modified_chat_ids).await?;
331        Ok(())
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use std::time::Duration;
338
339    use anyhow::bail;
340
341    use super::*;
342    use crate::chat::{Chat, ProtectionStatus, remove_contact_from_chat};
343    use crate::chatlist::Chatlist;
344    use crate::contact::{Contact, Origin};
345    use crate::securejoin::get_securejoin_qr;
346    use crate::test_utils::{self, TestContext, TestContextManager};
347    use crate::tools::SystemTime;
348
349    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
350    async fn test_config_sync_msgs() -> Result<()> {
351        let t = TestContext::new_alice().await;
352        assert_eq!(t.get_config_bool(Config::SyncMsgs).await?, false);
353        assert_eq!(t.get_config_bool(Config::BccSelf).await?, true);
354        assert_eq!(t.should_send_sync_msgs().await?, false);
355
356        t.set_config_bool(Config::SyncMsgs, true).await?;
357        assert_eq!(t.get_config_bool(Config::SyncMsgs).await?, true);
358        assert_eq!(t.get_config_bool(Config::BccSelf).await?, true);
359        assert_eq!(t.should_send_sync_msgs().await?, true);
360
361        t.set_config_bool(Config::BccSelf, false).await?;
362        assert_eq!(t.get_config_bool(Config::SyncMsgs).await?, true);
363        assert_eq!(t.get_config_bool(Config::BccSelf).await?, false);
364        assert_eq!(t.should_send_sync_msgs().await?, false);
365
366        t.set_config_bool(Config::SyncMsgs, false).await?;
367        assert_eq!(t.get_config_bool(Config::SyncMsgs).await?, false);
368        assert_eq!(t.get_config_bool(Config::BccSelf).await?, false);
369        assert_eq!(t.should_send_sync_msgs().await?, false);
370        Ok(())
371    }
372
373    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
374    async fn test_build_sync_json() -> Result<()> {
375        let t = TestContext::new_alice().await;
376        t.set_config_bool(Config::SyncMsgs, true).await?;
377
378        assert!(t.build_sync_json().await?.is_none());
379
380        // Having one test on `SyncData::AlterChat` is sufficient here as
381        // `chat::SyncAction::SetMuted` introduces enums inside items and `SystemTime`. Let's avoid
382        // in-depth testing of the serialiser here which is an external crate.
383        t.add_sync_item_with_timestamp(
384            SyncData::AlterChat {
385                id: chat::SyncId::ContactAddr("bob@example.net".to_string()),
386                action: chat::SyncAction::SetMuted(chat::MuteDuration::Until(
387                    SystemTime::UNIX_EPOCH + Duration::from_millis(42999),
388                )),
389            },
390            1631781315,
391        )
392        .await?;
393
394        t.add_sync_item_with_timestamp(
395            SyncData::AddQrToken(QrTokenData {
396                invitenumber: "testinvite".to_string(),
397                auth: "testauth".to_string(),
398                grpid: Some("group123".to_string()),
399            }),
400            1631781316,
401        )
402        .await?;
403        t.add_sync_item_with_timestamp(
404            SyncData::DeleteQrToken(QrTokenData {
405                invitenumber: "123!?\":.;{}".to_string(),
406                auth: "456".to_string(),
407                grpid: None,
408            }),
409            1631781317,
410        )
411        .await?;
412
413        let (serialized, ids) = t.build_sync_json().await?.unwrap();
414        assert_eq!(
415            serialized,
416            r#"{"items":[
417{"timestamp":1631781315,"data":{"AlterChat":{"id":{"ContactAddr":"bob@example.net"},"action":{"SetMuted":{"Until":{"secs_since_epoch":42,"nanos_since_epoch":999000000}}}}}},
418{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"testinvite","auth":"testauth","grpid":"group123"}}},
419{"timestamp":1631781317,"data":{"DeleteQrToken":{"invitenumber":"123!?\":.;{}","auth":"456","grpid":null}}}
420]}"#
421        );
422
423        assert!(t.build_sync_json().await?.is_some());
424        t.sql
425            .execute(
426                &format!("DELETE FROM multi_device_sync WHERE id IN ({ids})"),
427                (),
428            )
429            .await?;
430        assert!(t.build_sync_json().await?.is_none());
431
432        let sync_items = t.parse_sync_items(serialized)?;
433        assert_eq!(sync_items.items.len(), 3);
434
435        Ok(())
436    }
437
438    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
439    async fn test_build_sync_json_sync_msgs_off() -> Result<()> {
440        let t = TestContext::new_alice().await;
441        t.set_config_bool(Config::SyncMsgs, false).await?;
442        t.add_sync_item(SyncData::AddQrToken(QrTokenData {
443            invitenumber: "testinvite".to_string(),
444            auth: "testauth".to_string(),
445            grpid: Some("group123".to_string()),
446        }))
447        .await?;
448        assert!(t.build_sync_json().await?.is_none());
449        Ok(())
450    }
451
452    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
453    async fn test_parse_sync_items() -> Result<()> {
454        let t = TestContext::new_alice().await;
455
456        assert!(t.parse_sync_items(r#"{bad json}"#.to_string()).is_err());
457
458        assert!(t.parse_sync_items(r#"{"badname":[]}"#.to_string()).is_err());
459
460        for bad_item_example in [
461            r#"{"items":[{"timestamp":1631781316,"data":{"BadItem":{"invitenumber":"in","auth":"a","grpid":null}}}]}"#,
462            r#"{"items":[{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":123}}}]}"#, // `123` is invalid for `String`
463            r#"{"items":[{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":true}}}]}"#, // `true` is invalid for `String`
464            r#"{"items":[{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":[]}}}]}"#, // `[]` is invalid for `String`
465            r#"{"items":[{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":{}}}}]}"#, // `{}` is invalid for `String`
466            r#"{"items":[{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","grpid":null}}}]}"#, // missing field
467            r#"{"items":[{"timestamp":1631781316,"data":{"AlterChat":{"id":{"ContactAddr":"bob@example.net"},"action":"Burn"}}}]}"#, // Unknown enum value
468        ] {
469            let sync_items = t.parse_sync_items(bad_item_example.to_string()).unwrap();
470            assert_eq!(sync_items.items.len(), 1);
471            assert!(matches!(sync_items.items[0].timestamp, 1631781316));
472            assert!(matches!(
473                sync_items.items[0].data,
474                SyncDataOrUnknown::Unknown(_)
475            ));
476        }
477
478        // Test enums inside items and SystemTime
479        let sync_items = t.parse_sync_items(
480            r#"{"items":[{"timestamp":1631781318,"data":{"AlterChat":{"id":{"ContactAddr":"bob@example.net"},"action":{"SetMuted":{"Until":{"secs_since_epoch":42,"nanos_since_epoch":999000000}}}}}}]}"#.to_string(),
481        )?;
482        assert_eq!(sync_items.items.len(), 1);
483        let SyncDataOrUnknown::SyncData(AlterChat { id, action }) =
484            &sync_items.items.first().unwrap().data
485        else {
486            bail!("bad item");
487        };
488        assert_eq!(
489            *id,
490            chat::SyncId::ContactAddr("bob@example.net".to_string())
491        );
492        assert_eq!(
493            *action,
494            chat::SyncAction::SetMuted(chat::MuteDuration::Until(
495                SystemTime::UNIX_EPOCH + Duration::from_millis(42999)
496            ))
497        );
498
499        // empty item list is okay
500        assert_eq!(
501            t.parse_sync_items(r#"{"items":[]}"#.to_string())?
502                .items
503                .len(),
504            0
505        );
506
507        // to allow forward compatibility, additional fields should not break parsing
508        let sync_items = t
509            .parse_sync_items(
510                r#"{"items":[
511{"timestamp":1631781316,"data":{"DeleteQrToken":{"invitenumber":"in","auth":"yip","grpid":null}}},
512{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":"yip","additional":123,"grpid":null}}}
513]}"#
514                .to_string(),
515            )
516            ?;
517        assert_eq!(sync_items.items.len(), 2);
518
519        let sync_items = t.parse_sync_items(
520            r#"{"items":[
521{"timestamp":1631781318,"data":{"AddQrToken":{"invitenumber":"in","auth":"yip","grpid":null}}}
522],"additional":"field"}"#
523                .to_string(),
524        )?;
525
526        assert_eq!(sync_items.items.len(), 1);
527        if let SyncDataOrUnknown::SyncData(AddQrToken(token)) =
528            &sync_items.items.first().unwrap().data
529        {
530            assert_eq!(token.invitenumber, "in");
531            assert_eq!(token.auth, "yip");
532            assert_eq!(token.grpid, None);
533        } else {
534            bail!("bad item");
535        }
536
537        // to allow backward compatibility, missing `Option<>` should not break parsing
538        let sync_items = t.parse_sync_items(
539               r#"{"items":[{"timestamp":1631781319,"data":{"AddQrToken":{"invitenumber":"in","auth":"a"}}}]}"#.to_string(),
540           )
541           ?;
542        assert_eq!(sync_items.items.len(), 1);
543
544        Ok(())
545    }
546
547    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
548    async fn test_execute_sync_items() -> Result<()> {
549        let t = TestContext::new_alice().await;
550
551        assert!(!token::exists(&t, Namespace::Auth, "yip-auth").await?);
552
553        let sync_items = t
554            .parse_sync_items(
555                r#"{"items":[
556{"timestamp":1631781315,"data":{"AlterChat":{"id":{"ContactAddr":"bob@example.net"},"action":"Block"}}},
557{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"yip-in","auth":"a"}}},
558{"timestamp":1631781316,"data":{"DeleteQrToken":{"invitenumber":"in","auth":"delete unexistent, shall continue"}}},
559{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":"yip-auth"}}},
560{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":"foo","grpid":"non-existent"}}},
561{"timestamp":1631781316,"data":{"AddQrToken":{"invitenumber":"in","auth":"directly deleted"}}},
562{"timestamp":1631781316,"data":{"DeleteQrToken":{"invitenumber":"in","auth":"directly deleted"}}}
563]}"#
564                .to_string(),
565            )
566            ?;
567        t.execute_sync_items(&sync_items).await;
568
569        assert!(
570            Contact::lookup_id_by_addr(&t, "bob@example.net", Origin::Unknown)
571                .await?
572                .is_none()
573        );
574        assert!(!token::exists(&t, Namespace::InviteNumber, "yip-in").await?);
575        assert!(!token::exists(&t, Namespace::Auth, "yip-auth").await?);
576        assert!(!token::exists(&t, Namespace::Auth, "non-existent").await?);
577        assert!(!token::exists(&t, Namespace::Auth, "directly deleted").await?);
578
579        Ok(())
580    }
581
582    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
583    async fn test_send_sync_msg() -> Result<()> {
584        let alice = TestContext::new_alice().await;
585        alice.set_config_bool(Config::SyncMsgs, true).await?;
586        alice
587            .add_sync_item(SyncData::AddQrToken(QrTokenData {
588                invitenumber: "in".to_string(),
589                auth: "testtoken".to_string(),
590                grpid: None,
591            }))
592            .await?;
593        let msg_id = alice.send_sync_msg().await?.unwrap();
594        let msg = Message::load_from_db(&alice, msg_id).await?;
595        let chat = Chat::load_from_db(&alice, msg.chat_id).await?;
596        assert!(chat.is_self_talk());
597
598        // check that the used self-talk is not visible to the user
599        // but that creation will still work (in this case, the chat is empty)
600        assert_eq!(Chatlist::try_load(&alice, 0, None, None).await?.len(), 0);
601        let chat_id = ChatId::create_for_contact(&alice, ContactId::SELF).await?;
602        let chat = Chat::load_from_db(&alice, chat_id).await?;
603        assert!(chat.is_self_talk());
604        assert_eq!(Chatlist::try_load(&alice, 0, None, None).await?.len(), 1);
605        let msgs = chat::get_chat_msgs(&alice, chat_id).await?;
606        assert_eq!(msgs.len(), 0);
607
608        // let alice's other device receive and execute the sync message,
609        // also here, self-talk should stay hidden
610        let sent_msg = alice.pop_sent_sync_msg().await;
611        let alice2 = TestContext::new_alice().await;
612        alice2.set_config_bool(Config::SyncMsgs, true).await?;
613        alice2.recv_msg_trash(&sent_msg).await;
614        assert!(token::exists(&alice2, token::Namespace::Auth, "testtoken").await?);
615        assert_eq!(Chatlist::try_load(&alice2, 0, None, None).await?.len(), 0);
616
617        // Sync messages are "auto-generated", but they mustn't make the self-contact a bot.
618        let self_contact = alice2.add_or_lookup_contact(&alice2).await;
619        assert!(!self_contact.is_bot());
620
621        // the same sync message sent to bob must not be executed
622        let bob = TestContext::new_bob().await;
623        bob.recv_msg_trash(&sent_msg).await;
624        assert!(!token::exists(&bob, token::Namespace::Auth, "testtoken").await?);
625
626        Ok(())
627    }
628
629    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
630    async fn test_send_sync_msg_enables_bccself() -> Result<()> {
631        for (chatmail, sync_message_sent) in
632            [(false, false), (false, true), (true, false), (true, true)]
633        {
634            let alice1 = TestContext::new_alice().await;
635            let alice2 = TestContext::new_alice().await;
636
637            // SyncMsgs defaults to true on real devices, but in tests it defaults to false,
638            // so we need to enable it
639            alice1.set_config_bool(Config::SyncMsgs, true).await?;
640            alice2.set_config_bool(Config::SyncMsgs, true).await?;
641
642            if chatmail {
643                alice1.set_config_bool(Config::IsChatmail, true).await?;
644                alice2.set_config_bool(Config::IsChatmail, true).await?;
645            } else {
646                alice2.set_config_bool(Config::BccSelf, false).await?;
647            }
648
649            alice1.set_config_bool(Config::BccSelf, true).await?;
650
651            let sent_msg = if sync_message_sent {
652                alice1
653                    .add_sync_item(SyncData::AddQrToken(QrTokenData {
654                        invitenumber: "in".to_string(),
655                        auth: "testtoken".to_string(),
656                        grpid: None,
657                    }))
658                    .await?;
659                alice1.send_sync_msg().await?.unwrap();
660                alice1.pop_sent_sync_msg().await
661            } else {
662                let chat = alice1.get_self_chat().await;
663                alice1.send_text(chat.id, "Hi").await
664            };
665
666            // On chatmail accounts, BccSelf defaults to false.
667            // When receiving a sync message from another device,
668            // there obviously is a multi-device-setup, and BccSelf
669            // should be enabled.
670            assert_eq!(alice2.get_config_bool(Config::BccSelf).await?, false);
671
672            alice2.recv_msg_opt(&sent_msg).await;
673            assert_eq!(
674                alice2.get_config_bool(Config::BccSelf).await?,
675                // BccSelf should be enabled when receiving a sync message,
676                // but not when receiving another outgoing message
677                // because we might have forgotten it and it then it might have been forwarded to us again
678                // (though of course this is very unlikely).
679                sync_message_sent
680            );
681        }
682        Ok(())
683    }
684
685    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
686    async fn test_bot_no_sync_msgs() -> Result<()> {
687        let mut tcm = TestContextManager::new();
688        let alice = &tcm.alice().await;
689        let bob = &tcm.bob().await;
690        alice.set_config_bool(Config::SyncMsgs, true).await?;
691        let chat_id = alice.create_chat(bob).await.id;
692
693        chat::send_text_msg(alice, chat_id, "hi".to_string()).await?;
694        alice
695            .set_config(Config::Displayname, Some("Alice Human"))
696            .await?;
697        alice.send_sync_msg().await?;
698        alice.pop_sent_sync_msg().await;
699        let msg = bob.recv_msg(&alice.pop_sent_msg().await).await;
700        assert_eq!(msg.text, "hi");
701
702        alice.set_config_bool(Config::Bot, true).await?;
703        chat::send_text_msg(alice, chat_id, "hi".to_string()).await?;
704        alice
705            .set_config(Config::Displayname, Some("Alice Bot"))
706            .await?;
707        let msg = bob.recv_msg(&alice.pop_sent_msg().await).await;
708        assert_eq!(msg.text, "hi");
709        Ok(())
710    }
711
712    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
713    async fn test_unpromoted_group_qr_sync() -> Result<()> {
714        let mut tcm = TestContextManager::new();
715        let alice = &tcm.alice().await;
716        alice.set_config_bool(Config::SyncMsgs, true).await?;
717        let alice_chatid =
718            chat::create_group_chat(alice, ProtectionStatus::Protected, "the chat").await?;
719        let qr = get_securejoin_qr(alice, Some(alice_chatid)).await?;
720
721        // alice2 syncs the QR code token.
722        let alice2 = &tcm.alice().await;
723        alice2.set_config_bool(Config::SyncMsgs, true).await?;
724        test_utils::sync(alice, alice2).await;
725
726        let bob = &tcm.bob().await;
727        tcm.exec_securejoin_qr(bob, alice, &qr).await;
728        let msg_id = alice.send_sync_msg().await?;
729        // Core <= v1.143 doesn't sync QR code tokens immediately, so current Core does that when a
730        // group is promoted for compatibility (because the group could be created by older Core).
731        // TODO: assert!(msg_id.is_none());
732        assert!(msg_id.is_some());
733        let sent = alice.pop_sent_sync_msg().await;
734        let msg = alice.parse_msg(&sent).await;
735        let mut sync_items = msg.sync_items.unwrap().items;
736        assert_eq!(sync_items.len(), 1);
737        let data = sync_items.pop().unwrap().data;
738        let SyncDataOrUnknown::SyncData(AddQrToken(_)) = data else {
739            unreachable!();
740        };
741
742        // Remove Bob because alice2 doesn't have their key.
743        let alice_bob_id = alice.add_or_lookup_contact(bob).await.id;
744        remove_contact_from_chat(alice, alice_chatid, alice_bob_id).await?;
745        alice.pop_sent_msg().await;
746        let sent = alice
747            .send_text(alice_chatid, "Promoting group to another device")
748            .await;
749        alice2.recv_msg(&sent).await;
750
751        let fiona = &tcm.fiona().await;
752        tcm.exec_securejoin_qr(fiona, alice2, &qr).await;
753        let msg = fiona.get_last_msg().await;
754        assert_eq!(msg.text, "Member Me added by alice@example.org.");
755        Ok(())
756    }
757}