Skip to content

feat(crypto): Add EncryptionInfo to Decrypted to-device variant #5074

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
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions bindings/matrix-sdk-crypto-ffi/src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,11 @@ impl OlmMachine {
encryption_info.verification_state.to_shield_state_lax().into()
},
},
AlgorithmInfo::OlmV1Curve25519AesSha2 { .. } => {
// cannot happen because `decrypt_room_event` would have fail to decrypt olm for
// a room (EventError::UnsupportedAlgorithm)
panic!("Unsupported olm algorithm in room")
}
})
}

Expand Down
58 changes: 34 additions & 24 deletions crates/matrix-sdk-common/src/deserialized_responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,12 @@ pub enum AlgorithmInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
session_id: Option<String>,
},

/// The info if the event was encrypted using m.olm.v1.curve25519-aes-sha2
OlmV1Curve25519AesSha2 {
// The sender device key, base64 encoded
curve25519_public_key_base64: String,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the stringly typing? Curve25519Publickey is a Copy type so it's cheaper to copy it around, provides stronger typing and has a to_base64() method if you do need a string.

I feel like we've been here already once.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It tried to keep it consistent with the other variant.
I suppose I have then to use serde(deserialize_with = "deserialize_curve_key", .. "serialize_curve_key"?
I'll do it too for MegolmV1AesSha2 to stay consistant

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I am not sure about this change.
To do it, I need to add vodozemac as a dependency of matrix-sdk-common (it is not yet), would I need also to add some feature = "e2e-encryption" cfg?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had another look, and if I just refactor both Olm and Megolm variant to use Curve25519Publickey instead of strings, I'll need to

  • make the common crate to depend on vodozemac
  • Then for ser/deser compatibility (particularly for Megolm variant as part of TimelineEventKind) we need to move deserialize_curve_key and serialize_curve_key from crypto crate down to common crate (that will also bring back a dependency to zeroize).

This is touching several tests files. Looks like a candidate for a separate PR

},
}

/// Struct containing information on how an event was decrypted.
Expand All @@ -312,8 +318,11 @@ pub struct EncryptionInfo {
impl EncryptionInfo {
/// Helper to get the megolm session id used to encrypt.
pub fn session_id(&self) -> Option<&str> {
let AlgorithmInfo::MegolmV1AesSha2 { session_id, .. } = &self.algorithm_info;
session_id.as_deref()
if let AlgorithmInfo::MegolmV1AesSha2 { session_id, .. } = &self.algorithm_info {
session_id.as_deref()
} else {
None
}
}
}

Expand All @@ -334,26 +343,22 @@ impl<'de> Deserialize<'de> for EncryptionInfo {
pub old_session_id: Option<String>,
}

let Helper {
sender,
sender_device,
algorithm_info:
AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, sender_claimed_keys, session_id },
verification_state,
old_session_id,
} = Helper::deserialize(deserializer)?;

Ok(EncryptionInfo {
sender,
sender_device,
algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
// Migration, merge the old_session_id in algorithm_info
session_id: session_id.or(old_session_id),
curve25519_key,
sender_claimed_keys,
},
verification_state,
})
let Helper { sender, sender_device, algorithm_info, verification_state, old_session_id } =
Helper::deserialize(deserializer)?;

let algorithm_info = match algorithm_info {
AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, sender_claimed_keys, session_id } => {
AlgorithmInfo::MegolmV1AesSha2 {
// Migration, merge the old_session_id in algorithm_info
session_id: session_id.or(old_session_id),
curve25519_key,
sender_claimed_keys,
}
}
other => other,
};

Ok(EncryptionInfo { sender, sender_device, algorithm_info, verification_state })
}
}

Expand Down Expand Up @@ -1463,8 +1468,13 @@ mod tests {
let deserialized = serde_json::from_value::<EncryptionInfo>(old_format).unwrap();
let expected_session_id = Some("mysessionid76".to_owned());

let AlgorithmInfo::MegolmV1AesSha2 { session_id, .. } = deserialized.algorithm_info.clone();
assert_eq!(session_id, expected_session_id);
if let AlgorithmInfo::MegolmV1AesSha2 { session_id, .. } =
deserialized.algorithm_info.clone()
{
assert_eq!(session_id, expected_session_id);
} else {
panic!("Expected MegolmV1AesSha2");
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's assert_let!() and assert_matches!() for this kind of code snippet.


assert_json_snapshot!(deserialized);
}
Expand Down
5 changes: 5 additions & 0 deletions crates/matrix-sdk-crypto/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ All notable changes to this project will be documented in this file.

- [**breaking**] Move `session_id` from `EncryptionInfo` to `AlgorithmInfo` as it is megolm specific.
Use `EncryptionInfo::session_id()` helper for quick access.
([4981](https://github.com/matrix-org/matrix-rust-sdk/pull/4981))

- [**breaking**] The `ProcessedToDeviceEvent::Decrypted` variant now also have an `EncryptionInfo` field.
Format changed from `Decrypted(Raw<AnyToDeviceEvent>)` to `Decrypted { raw: Raw<AnyToDeviceEvent>, encryption_info: EncryptionInfo) }`
([5074](https://github.com/matrix-org/matrix-rust-sdk/pull/5074))

- Send stable identifier `sender_device_keys` for MSC4147 (Including device
keys with Olm-encrypted events).
Expand Down
5 changes: 4 additions & 1 deletion crates/matrix-sdk-crypto/src/machine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1453,7 +1453,10 @@ impl OlmMachine {
}
}

Some(ProcessedToDeviceEvent::Decrypted(raw_event))
Some(ProcessedToDeviceEvent::Decrypted {
raw: raw_event,
encryption_info: decrypted.result.encryption_info,
})
}

e => {
Expand Down
54 changes: 51 additions & 3 deletions crates/matrix-sdk-crypto/src/machine/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,25 @@ use ruma::{
encryption::OneTimeKey,
events::dummy::ToDeviceDummyEventContent,
serde::Raw,
to_device::DeviceIdOrAllDevices,
user_id, DeviceId, OwnedOneTimeKeyId, TransactionId, UserId,
};
use serde_json::json;
use serde_json::{json, Value};
use tokio::sync::Mutex;

use crate::{
machine::tests,
olm::PrivateCrossSigningIdentity,
store::{Changes, CryptoStoreWrapper, MemoryStore},
types::{events::ToDeviceEvent, requests::AnyOutgoingRequest, DeviceKeys},
types::{
events::ToDeviceEvent,
requests::{AnyOutgoingRequest, ToDeviceRequest},
DeviceKeys, ProcessedToDeviceEvent,
},
utilities::json_convert,
verification::VerificationMachine,
Account, CrossSigningBootstrapRequests, Device, DeviceData, OlmMachine, OtherUserIdentityData,
Account, CrossSigningBootstrapRequests, Device, DeviceData, EncryptionSyncChanges, OlmMachine,
OtherUserIdentityData,
};

/// These keys need to be periodically uploaded to the server.
Expand Down Expand Up @@ -174,6 +182,46 @@ pub async fn get_machine_pair_with_session(
build_session_for_pair(alice, bob, one_time_keys).await
}

pub async fn send_and_receive_encrypted_to_device_test_helper(
sender: &OlmMachine,
recipient: &OlmMachine,
event_type: &str,
content: Value,
) -> ProcessedToDeviceEvent {
let device =
sender.get_device(recipient.user_id(), recipient.device_id(), None).await.unwrap().unwrap();

let raw_encrypted = device
.encrypt_event_raw(event_type, &content)
.await
.expect("Should have encrypted the content");

let request = ToDeviceRequest::new(
recipient.user_id(),
DeviceIdOrAllDevices::DeviceId(recipient.device_id().to_owned()),
"m.room.encrypted",
raw_encrypted.cast(),
);
let event = ToDeviceEvent::new(
sender.user_id().to_owned(),
tests::to_device_requests_to_content(vec![request.clone().into()]),
);

let event = json_convert(&event).unwrap();

let sync_changes = EncryptionSyncChanges {
to_device_events: vec![event],
changed_devices: &Default::default(),
one_time_keys_counts: &Default::default(),
unused_fallback_keys: None,
next_batch_token: None,
};

let (decrypted, _) = recipient.receive_sync_changes(sync_changes).await.unwrap();
assert_eq!(1, decrypted.len());
decrypted[0].clone()
}

/// Create a session for the two supplied Olm machines to communicate.
pub async fn build_session_for_pair(
alice: OlmMachine,
Expand Down
Loading
Loading