-
Notifications
You must be signed in to change notification settings - Fork 314
feat(sdk): Add a tasks that listens for historic room keys if they arrive out of order #5322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
poljar
wants to merge
4
commits into
main
Choose a base branch
from
poljar/shared-history/out-of-order
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+247
−19
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
754d946
feat(sdk): Add a tasks that listens for historic room keys if they ar…
poljar c63dc8f
test(sdk): Test the conditions under which we accept a historic room …
poljar bc5afce
test(sdk): Test that we accept historic room key bundles if they arri…
poljar 6368654
fixup! feat(sdk): Add a tasks that listens for historic room keys if …
poljar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,23 +14,24 @@ | |
|
||
use std::{collections::BTreeMap, sync::Arc, time::Duration}; | ||
|
||
use futures_core::Stream; | ||
use futures_util::{pin_mut, StreamExt}; | ||
use matrix_sdk_base::{crypto::store::types::RoomKeyBundleInfo, RoomState}; | ||
use matrix_sdk_common::failures_cache::FailuresCache; | ||
use ruma::{ | ||
events::room::encrypted::{EncryptedEventScheme, OriginalSyncRoomEncryptedEvent}, | ||
serde::Raw, | ||
OwnedEventId, OwnedRoomId, | ||
}; | ||
use tokio::sync::{ | ||
mpsc::{self, UnboundedReceiver}, | ||
Mutex, | ||
}; | ||
use tracing::{debug, trace, warn}; | ||
use tokio::sync::{mpsc, Mutex}; | ||
use tracing::{debug, info, instrument, trace, warn}; | ||
|
||
use crate::{ | ||
client::WeakClient, | ||
encryption::backups::UploadState, | ||
executor::{spawn, JoinHandle}, | ||
Client, | ||
room::shared_room_history, | ||
Client, Room, | ||
}; | ||
|
||
/// A cache of room keys we already downloaded. | ||
|
@@ -41,6 +42,7 @@ pub(crate) struct ClientTasks { | |
pub(crate) upload_room_keys: Option<BackupUploadingTask>, | ||
pub(crate) download_room_keys: Option<BackupDownloadTask>, | ||
pub(crate) update_recovery_state_after_backup: Option<JoinHandle<()>>, | ||
pub(crate) receive_historic_room_key_bundles: Option<BundleReceiverTask>, | ||
pub(crate) setup_e2ee: Option<JoinHandle<()>>, | ||
} | ||
|
||
|
@@ -72,7 +74,7 @@ impl BackupUploadingTask { | |
let _ = self.sender.send(()); | ||
} | ||
|
||
pub(crate) async fn listen(client: WeakClient, mut receiver: UnboundedReceiver<()>) { | ||
pub(crate) async fn listen(client: WeakClient, mut receiver: mpsc::UnboundedReceiver<()>) { | ||
while receiver.recv().await.is_some() { | ||
if let Some(client) = client.get() { | ||
let upload_progress = &client.inner.e2ee.backup_state.upload_progress; | ||
|
@@ -176,7 +178,10 @@ impl BackupDownloadTask { | |
/// # Arguments | ||
/// | ||
/// * `receiver` - The source of incoming [`RoomKeyDownloadRequest`]s. | ||
async fn listen(client: WeakClient, mut receiver: UnboundedReceiver<RoomKeyDownloadRequest>) { | ||
async fn listen( | ||
client: WeakClient, | ||
mut receiver: mpsc::UnboundedReceiver<RoomKeyDownloadRequest>, | ||
) { | ||
let state = Arc::new(Mutex::new(BackupDownloadTaskListenerState::new(client))); | ||
|
||
while let Some(room_key_download_request) = receiver.recv().await { | ||
|
@@ -385,15 +390,77 @@ impl BackupDownloadTaskListenerState { | |
} | ||
} | ||
|
||
pub(crate) struct BundleReceiverTask { | ||
_handle: JoinHandle<()>, | ||
} | ||
|
||
impl BundleReceiverTask { | ||
pub async fn new(client: &Client) -> Self { | ||
let stream = client.encryption().historic_room_key_stream().await.expect("E2EE tasks should only be initialized once we have logged in and have access to an OlmMachine"); | ||
let weak_client = WeakClient::from_client(client); | ||
let handle = spawn(Self::listen_task(weak_client, stream)); | ||
|
||
Self { _handle: handle } | ||
} | ||
|
||
async fn listen_task(client: WeakClient, stream: impl Stream<Item = RoomKeyBundleInfo>) { | ||
pin_mut!(stream); | ||
|
||
// TODO: Listening to this stream is not enough for iOS due to the NSE killing | ||
// our OlmMachine and thus also this stream. We need to add an event handler | ||
// that will listen for the bundle event. To be able to add an event handler, | ||
// we'll have to implement the bundle event in Ruma. | ||
while let Some(bundle_info) = stream.next().await { | ||
let Some(client) = client.get() else { | ||
// The client was dropped while we were waiting on the stream. Let's end the | ||
// loop, since this means that the application has shut down. | ||
break; | ||
}; | ||
|
||
let Some(room) = client.get_room(&bundle_info.room_id) else { | ||
warn!(room_id = %bundle_info.room_id, "Received a historic room key bundle for an unknown room"); | ||
continue; | ||
}; | ||
|
||
Self::handle_bundle(&room, &bundle_info).await; | ||
} | ||
} | ||
|
||
#[instrument(skip(room), fields(room_id = %room.room_id()))] | ||
async fn handle_bundle(room: &Room, bundle_info: &RoomKeyBundleInfo) { | ||
if Self::should_accept_bundle(room, bundle_info) { | ||
info!("Accepting an out of order key bundle."); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not really "out of order", right? More "late-arriving". |
||
|
||
if let Err(e) = | ||
shared_room_history::maybe_accept_key_bundle(room, &bundle_info.sender).await | ||
{ | ||
warn!("Couldn't accept a late room key bundle {e:?}"); | ||
andybalaam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} else { | ||
info!("Refusing to accept a historic room key bundle."); | ||
andybalaam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
fn should_accept_bundle(room: &Room, _bundle_info: &RoomKeyBundleInfo) -> bool { | ||
// TODO: Check that the person that invited us to this room is the same as the | ||
// sender, of the bundle. Otherwise don't ignore the bundle. | ||
// TODO: Check that we joined the room "recently". (How do you do this if you | ||
// accept the invite on another client? I guess we remember when the transition | ||
// from Invited to Joined happened, but can't the server force us into a joined | ||
// state if we do this? | ||
room.state() == RoomState::Joined | ||
} | ||
} | ||
|
||
#[cfg(all(test, not(target_family = "wasm")))] | ||
mod test { | ||
use matrix_sdk_test::async_test; | ||
use ruma::{event_id, room_id}; | ||
use matrix_sdk_test::{async_test, InvitedRoomBuilder, JoinedRoomBuilder}; | ||
use ruma::{event_id, room_id, user_id}; | ||
use serde_json::json; | ||
use wiremock::MockServer; | ||
|
||
use super::*; | ||
use crate::test_utils::logged_in_client; | ||
use crate::test_utils::{logged_in_client, mocks::MatrixMockServer}; | ||
|
||
// Test that, if backups are not enabled, we don't incorrectly mark a room key | ||
// as downloaded. | ||
|
@@ -451,4 +518,44 @@ mod test { | |
) | ||
} | ||
} | ||
|
||
/// Test that ensures that we only accept a bundle if a certain set of | ||
/// conditions is met. | ||
#[async_test] | ||
async fn test_should_accept_bundle() { | ||
let server = MatrixMockServer::new().await; | ||
let client = server.client_builder().logged_in_with_oauth().build().await; | ||
|
||
let user_id = user_id!("@alice:localhost"); | ||
let joined_room_id = room_id!("!joined:localhost"); | ||
let invited_rom_id = room_id!("!invited:localhost"); | ||
|
||
server | ||
.mock_sync() | ||
.ok_and_run(&client, |builder| { | ||
builder | ||
.add_joined_room(JoinedRoomBuilder::new(joined_room_id)) | ||
.add_invited_room(InvitedRoomBuilder::new(invited_rom_id)); | ||
}) | ||
.await; | ||
|
||
let room = | ||
client.get_room(joined_room_id).expect("We should have access to our joined room now"); | ||
|
||
let bundle_info = | ||
RoomKeyBundleInfo { sender: user_id.to_owned(), room_id: joined_room_id.to_owned() }; | ||
|
||
assert!(BundleReceiverTask::should_accept_bundle(&room, &bundle_info)); | ||
|
||
let invited_room = | ||
client.get_room(invited_rom_id).expect("We should have access to our invited room now"); | ||
|
||
assert!( | ||
!BundleReceiverTask::should_accept_bundle(&invited_room, &bundle_info), | ||
"We should not accept a bundle if we didn't join the room." | ||
); | ||
|
||
// TODO: Add more cases here once we figure out the correct acceptance | ||
// rules. | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.