matrix_sdk/room/
shared_room_history.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::iter;
16
17use ruma::OwnedUserId;
18use tracing::{info, instrument, warn};
19
20use crate::{crypto::types::events::room_key_bundle::RoomKeyBundleContent, Error, Result, Room};
21
22/// Share any shareable E2EE history in the given room with the given recipient,
23/// as per [MSC4268].
24///
25/// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
26#[instrument(skip(room), fields(room_id = ?room.room_id()))]
27pub async fn share_room_history(room: &Room, user_id: OwnedUserId) -> Result<()> {
28    let client = &room.client;
29
30    // 0. We can only share room history if our user has set up cross signing
31    let own_identity = match client.user_id() {
32        Some(own_user) => client.encryption().get_user_identity(own_user).await?,
33        None => None,
34    };
35    if own_identity.is_none() {
36        warn!("Not sharing message history as cross-signing is not set up");
37        return Ok(());
38    }
39
40    info!("Sharing message history");
41
42    // 1. Construct the key bundle
43    let bundle = {
44        let olm_machine = client.olm_machine().await;
45        let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
46        olm_machine.store().build_room_key_bundle(room.room_id()).await?
47    };
48
49    if bundle.is_empty() {
50        info!("No keys to share");
51        return Ok(());
52    }
53
54    // 2. Upload to the server as an encrypted file
55    let json = serde_json::to_vec(&bundle)?;
56    let upload =
57        client.upload_encrypted_file(&mime::APPLICATION_JSON, &mut (json.as_slice())).await?;
58
59    info!(
60        media_url = ?upload.url,
61        shared_keys = bundle.room_keys.len(),
62        withheld_keys = bundle.withheld.len(),
63        "Uploaded encrypted key blob"
64    );
65
66    // 3. Establish Olm sessions with all of the recipient's devices.
67    client.claim_one_time_keys(iter::once(user_id.as_ref())).await?;
68
69    // 4. Send to-device messages to the recipient to share the keys.
70    let content = RoomKeyBundleContent { room_id: room.room_id().to_owned(), file: upload };
71    let requests = {
72        let olm_machine = client.olm_machine().await;
73        let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
74        olm_machine
75            .share_room_key_bundle_data(
76                &user_id,
77                &client.base_client().room_key_recipient_strategy,
78                content,
79            )
80            .await?
81    };
82
83    for request in requests {
84        let response = client.send_to_device(&request).await?;
85        client.mark_request_as_sent(&request.txn_id, &response).await?;
86    }
87    Ok(())
88}