crypto: Turn the content_to_request function into a constructor

Closes: #260
master
Damir Jelić 2021-06-10 13:24:13 +02:00
parent 00c3921d2a
commit b14d754aed
7 changed files with 51 additions and 57 deletions

View File

@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
#![allow(missing_docs)]
use std::{collections::BTreeMap, sync::Arc, time::Duration}; use std::{collections::BTreeMap, sync::Arc, time::Duration};
use matrix_sdk_common::uuid::Uuid; use matrix_sdk_common::uuid::Uuid;
@ -32,7 +30,7 @@ use ruma::{
message::send_message_event::Response as RoomMessageResponse, message::send_message_event::Response as RoomMessageResponse,
to_device::{send_event_to_device::Response as ToDeviceResponse, DeviceIdOrAllDevices}, to_device::{send_event_to_device::Response as ToDeviceResponse, DeviceIdOrAllDevices},
}, },
events::{AnyMessageEventContent, EventType}, events::{AnyMessageEventContent, AnyToDeviceEventContent, EventContent, EventType},
DeviceIdBox, RoomId, UserId, DeviceIdBox, RoomId, UserId,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -60,6 +58,35 @@ pub struct ToDeviceRequest {
} }
impl ToDeviceRequest { impl ToDeviceRequest {
/// Create a new owned to-device request
///
/// # Arguments
///
/// * `recipient` - The ID of the user that should receive this to-device
/// event.
///
/// * `recipient_device` - The device that should receive this to-device
/// event, or all devices.
///
/// * `content` - The content of the to-device event.
pub(crate) fn new(
recipient: &UserId,
recipient_device: impl Into<DeviceIdOrAllDevices>,
content: AnyToDeviceEventContent,
) -> Self {
let mut messages = BTreeMap::new();
let mut user_messages = BTreeMap::new();
user_messages.insert(
recipient_device.into(),
serde_json::value::to_raw_value(&content).expect("Can't serialize to-device content"),
);
messages.insert(recipient.clone(), user_messages);
let event_type = EventType::from(content.event_type());
ToDeviceRequest { txn_id: Uuid::new_v4(), event_type, messages }
}
/// Gets the transaction ID as a string. /// Gets the transaction ID as a string.
pub fn txn_id_string(&self) -> String { pub fn txn_id_string(&self) -> String {
self.txn_id.to_string() self.txn_id.to_string()
@ -133,6 +160,8 @@ pub enum OutgoingRequests {
/// Signature upload request, this request is used after a successful device /// Signature upload request, this request is used after a successful device
/// or user verification is done. /// or user verification is done.
SignatureUpload(SignatureUploadRequest), SignatureUpload(SignatureUploadRequest),
/// A room message request, usually for sending in-room interactive
/// verification events.
RoomMessage(RoomMessageRequest), RoomMessage(RoomMessageRequest),
} }
@ -205,9 +234,9 @@ pub enum IncomingResponse<'a> {
/// The cross signing keys upload response, marking our private cross /// The cross signing keys upload response, marking our private cross
/// signing identity as shared. /// signing identity as shared.
SigningKeysUpload(&'a SigningKeysUploadResponse), SigningKeysUpload(&'a SigningKeysUploadResponse),
/// The cross signing keys upload response, marking our private cross /// The cross signing signature upload response.
/// signing identity as shared.
SignatureUpload(&'a SignatureUploadResponse), SignatureUpload(&'a SignatureUploadResponse),
/// A room message response, usually for interactive verifications.
RoomMessage(&'a RoomMessageResponse), RoomMessage(&'a RoomMessageResponse),
} }
@ -270,6 +299,7 @@ impl OutgoingRequest {
} }
} }
/// Customized owned request type for sending out room messages.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RoomMessageRequest { pub struct RoomMessageRequest {
/// The room to send the event to. /// The room to send the event to.
@ -286,13 +316,17 @@ pub struct RoomMessageRequest {
pub content: AnyMessageEventContent, pub content: AnyMessageEventContent,
} }
/// An enum over the different outgoing verification based requests.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum OutgoingVerificationRequest { pub enum OutgoingVerificationRequest {
/// The to-device verification request variant.
ToDevice(ToDeviceRequest), ToDevice(ToDeviceRequest),
/// The in-room verification request variant.
InRoom(RoomMessageRequest), InRoom(RoomMessageRequest),
} }
impl OutgoingVerificationRequest { impl OutgoingVerificationRequest {
/// Get the unique id of this request.
pub fn request_id(&self) -> Uuid { pub fn request_id(&self) -> Uuid {
match self { match self {
OutgoingVerificationRequest::ToDevice(t) => t.txn_id, OutgoingVerificationRequest::ToDevice(t) => t.txn_id,

View File

@ -18,8 +18,8 @@ use dashmap::DashMap;
use matrix_sdk_common::uuid::Uuid; use matrix_sdk_common::uuid::Uuid;
use ruma::{DeviceId, UserId}; use ruma::{DeviceId, UserId};
use super::{event_enums::OutgoingContent, sas::content_to_request, Sas, Verification}; use super::{event_enums::OutgoingContent, Sas, Verification};
use crate::{OutgoingRequest, QrVerification, RoomMessageRequest}; use crate::{OutgoingRequest, QrVerification, RoomMessageRequest, ToDeviceRequest};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct VerificationCache { pub struct VerificationCache {
@ -125,7 +125,7 @@ impl VerificationCache {
) { ) {
match content { match content {
OutgoingContent::ToDevice(c) => { OutgoingContent::ToDevice(c) => {
let request = content_to_request(recipient, recipient_device.to_owned(), c); let request = ToDeviceRequest::new(recipient, recipient_device.to_owned(), c);
let request_id = request.txn_id; let request_id = request.txn_id;
let request = OutgoingRequest { request_id, request: Arc::new(request.into()) }; let request = OutgoingRequest { request_id, request: Arc::new(request.into()) };

View File

@ -23,7 +23,7 @@ use super::{
cache::VerificationCache, cache::VerificationCache,
event_enums::{AnyEvent, AnyVerificationContent, OutgoingContent}, event_enums::{AnyEvent, AnyVerificationContent, OutgoingContent},
requests::VerificationRequest, requests::VerificationRequest,
sas::{content_to_request, Sas}, sas::Sas,
FlowId, Verification, VerificationResult, FlowId, Verification, VerificationResult,
}; };
use crate::{ use crate::{
@ -31,6 +31,7 @@ use crate::{
requests::OutgoingRequest, requests::OutgoingRequest,
store::{CryptoStore, CryptoStoreError}, store::{CryptoStore, CryptoStoreError},
OutgoingVerificationRequest, ReadOnlyAccount, ReadOnlyDevice, RoomMessageRequest, OutgoingVerificationRequest, ReadOnlyAccount, ReadOnlyDevice, RoomMessageRequest,
ToDeviceRequest,
}; };
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -79,7 +80,7 @@ impl VerificationMachine {
} }
OutgoingContent::ToDevice(c) => { OutgoingContent::ToDevice(c) => {
let request = let request =
content_to_request(device.user_id(), device.device_id().to_owned(), c); ToDeviceRequest::new(device.user_id(), device.device_id().to_owned(), c);
self.verifications.insert_sas(sas.clone()); self.verifications.insert_sas(sas.clone());

View File

@ -39,14 +39,13 @@ use thiserror::Error;
use super::{ use super::{
event_enums::{DoneContent, OutgoingContent, OwnedStartContent, StartContent}, event_enums::{DoneContent, OutgoingContent, OwnedStartContent, StartContent},
sas::content_to_request,
Cancelled, Done, FlowId, IdentitiesBeingVerified, VerificationResult, Cancelled, Done, FlowId, IdentitiesBeingVerified, VerificationResult,
}; };
use crate::{ use crate::{
olm::{PrivateCrossSigningIdentity, ReadOnlyAccount}, olm::{PrivateCrossSigningIdentity, ReadOnlyAccount},
store::CryptoStore, store::CryptoStore,
CryptoStoreError, OutgoingVerificationRequest, ReadOnlyDevice, RoomMessageRequest, CryptoStoreError, OutgoingVerificationRequest, ReadOnlyDevice, RoomMessageRequest,
UserIdentities, ToDeviceRequest, UserIdentities,
}; };
const SECRET_SIZE: usize = 16; const SECRET_SIZE: usize = 16;
@ -201,7 +200,7 @@ impl QrVerification {
OutgoingContent::Room(room_id, content) => { OutgoingContent::Room(room_id, content) => {
RoomMessageRequest { room_id, txn_id: Uuid::new_v4(), content }.into() RoomMessageRequest { room_id, txn_id: Uuid::new_v4(), content }.into()
} }
OutgoingContent::ToDevice(c) => content_to_request( OutgoingContent::ToDevice(c) => ToDeviceRequest::new(
self.identities.other_user_id(), self.identities.other_user_id(),
self.identities.other_device_id().to_owned(), self.identities.other_device_id().to_owned(),
c, c,

View File

@ -41,7 +41,6 @@ use super::{
CancelContent, DoneContent, OutgoingContent, ReadyContent, RequestContent, StartContent, CancelContent, DoneContent, OutgoingContent, ReadyContent, RequestContent, StartContent,
}, },
qrcode::{QrVerification, ScanError}, qrcode::{QrVerification, ScanError},
sas::content_to_request,
Cancelled, FlowId, IdentitiesBeingVerified, Cancelled, FlowId, IdentitiesBeingVerified,
}; };
use crate::{ use crate::{
@ -268,7 +267,7 @@ impl VerificationRequest {
inner.accept().map(|c| match c { inner.accept().map(|c| match c {
OutgoingContent::ToDevice(content) => { OutgoingContent::ToDevice(content) => {
self.content_to_request(inner.other_device_id(), content).into() ToDeviceRequest::new(&self.other_user(), inner.other_device_id(), content).into()
} }
OutgoingContent::Room(room_id, content) => { OutgoingContent::Room(room_id, content) => {
RoomMessageRequest { room_id, txn_id: Uuid::new_v4(), content }.into() RoomMessageRequest { room_id, txn_id: Uuid::new_v4(), content }.into()
@ -337,14 +336,6 @@ impl VerificationRequest {
_ => None, _ => None,
} }
} }
fn content_to_request(
&self,
other_device_id: DeviceIdOrAllDevices,
content: AnyToDeviceEventContent,
) -> ToDeviceRequest {
content_to_request(&self.other_user_id, other_device_id, content)
}
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]

View File

@ -14,17 +14,15 @@
use std::{collections::BTreeMap, convert::TryInto}; use std::{collections::BTreeMap, convert::TryInto};
use matrix_sdk_common::uuid::Uuid;
use olm_rs::sas::OlmSas; use olm_rs::sas::OlmSas;
use ruma::{ use ruma::{
api::client::r0::to_device::DeviceIdOrAllDevices,
events::{ events::{
key::verification::{ key::verification::{
cancel::CancelCode, cancel::CancelCode,
mac::{MacEventContent, MacToDeviceEventContent}, mac::{MacEventContent, MacToDeviceEventContent},
Relation, Relation,
}, },
AnyMessageEventContent, AnyToDeviceEventContent, EventType, AnyMessageEventContent, AnyToDeviceEventContent,
}, },
DeviceKeyAlgorithm, DeviceKeyId, UserId, DeviceKeyAlgorithm, DeviceKeyId, UserId,
}; };
@ -36,7 +34,7 @@ use crate::{
identities::{ReadOnlyDevice, UserIdentities}, identities::{ReadOnlyDevice, UserIdentities},
utilities::encode, utilities::encode,
verification::event_enums::{MacContent, StartContent}, verification::event_enums::{MacContent, StartContent},
ReadOnlyAccount, ToDeviceRequest, ReadOnlyAccount,
}; };
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -527,34 +525,6 @@ fn bytes_to_decimal(bytes: Vec<u8>) -> (u16, u16, u16) {
(first + 1000, second + 1000, third + 1000) (first + 1000, second + 1000, third + 1000)
} }
pub fn content_to_request(
recipient: &UserId,
recipient_device: impl Into<DeviceIdOrAllDevices>,
content: AnyToDeviceEventContent,
) -> ToDeviceRequest {
let mut messages = BTreeMap::new();
let mut user_messages = BTreeMap::new();
user_messages.insert(
recipient_device.into(),
serde_json::value::to_raw_value(&content).expect("Can't serialize to-device content"),
);
messages.insert(recipient.clone(), user_messages);
let event_type = match content {
AnyToDeviceEventContent::KeyVerificationAccept(_) => EventType::KeyVerificationAccept,
AnyToDeviceEventContent::KeyVerificationStart(_) => EventType::KeyVerificationStart,
AnyToDeviceEventContent::KeyVerificationKey(_) => EventType::KeyVerificationKey,
AnyToDeviceEventContent::KeyVerificationMac(_) => EventType::KeyVerificationMac,
AnyToDeviceEventContent::KeyVerificationCancel(_) => EventType::KeyVerificationCancel,
AnyToDeviceEventContent::KeyVerificationReady(_) => EventType::KeyVerificationReady,
AnyToDeviceEventContent::KeyVerificationDone(_) => EventType::KeyVerificationDone,
_ => unreachable!(),
};
ToDeviceRequest { txn_id: Uuid::new_v4(), event_type, messages }
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use proptest::prelude::*; use proptest::prelude::*;

View File

@ -20,7 +20,6 @@ use std::sync::{Arc, Mutex};
#[cfg(test)] #[cfg(test)]
use std::time::Instant; use std::time::Instant;
pub use helpers::content_to_request;
use inner_sas::InnerSas; use inner_sas::InnerSas;
use matrix_sdk_common::uuid::Uuid; use matrix_sdk_common::uuid::Uuid;
use ruma::{ use ruma::{
@ -442,7 +441,7 @@ impl Sas {
} }
pub(crate) fn content_to_request(&self, content: AnyToDeviceEventContent) -> ToDeviceRequest { pub(crate) fn content_to_request(&self, content: AnyToDeviceEventContent) -> ToDeviceRequest {
content_to_request(self.other_user_id(), self.other_device_id().to_owned(), content) ToDeviceRequest::new(self.other_user_id(), self.other_device_id().to_owned(), content)
} }
} }