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.
1415use std::iter;
1617use ruma::OwnedUserId;
18use tracing::{info, instrument, warn};
1920use crate::{crypto::types::events::room_key_bundle::RoomKeyBundleContent, Error, Result, Room};
2122/// 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<()> {
28let client = &room.client;
2930// 0. We can only share room history if our user has set up cross signing
31let own_identity = match client.user_id() {
32Some(own_user) => client.encryption().get_user_identity(own_user).await?,
33None => None,
34 };
35if own_identity.is_none() {
36warn!("Not sharing message history as cross-signing is not set up");
37return Ok(());
38 }
3940info!("Sharing message history");
4142// 1. Construct the key bundle
43let bundle = {
44let olm_machine = client.olm_machine().await;
45let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
46 olm_machine.store().build_room_key_bundle(room.room_id()).await?
47};
4849if bundle.is_empty() {
50info!("No keys to share");
51return Ok(());
52 }
5354// 2. Upload to the server as an encrypted file
55let json = serde_json::to_vec(&bundle)?;
56let upload =
57 client.upload_encrypted_file(&mime::APPLICATION_JSON, &mut (json.as_slice())).await?;
5859info!(
60 media_url = ?upload.url,
61 shared_keys = bundle.room_keys.len(),
62 withheld_keys = bundle.withheld.len(),
63"Uploaded encrypted key blob"
64);
6566// 3. Establish Olm sessions with all of the recipient's devices.
67client.claim_one_time_keys(iter::once(user_id.as_ref())).await?;
6869// 4. Send to-device messages to the recipient to share the keys.
70let content = RoomKeyBundleContent { room_id: room.room_id().to_owned(), file: upload };
71let requests = {
72let olm_machine = client.olm_machine().await;
73let 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};
8283for request in requests {
84let response = client.send_to_device(&request).await?;
85 client.mark_request_as_sent(&request.txn_id, &response).await?;
86 }
87Ok(())
88}