src/verifications.rs

226 lines · 8154 bytes

  1use matrix_sdk::Client;
  2use matrix_sdk::encryption::verification::{
  3    Verification,
  4    VerificationRequest,
  5    VerificationRequestState,
  6};
  7use matrix_sdk::ruma::events::key::verification::VerificationMethod;
  8use matrix_sdk::ruma::{OwnedDeviceId, OwnedUserId, UserId};
  9use modalkit::errors::UIError;
 10use modalkit::prelude::{EditInfo, InfoMessage};
 11
 12use crate::base::{AsyncProgramStore, IambError, IambResult, ProgramStore, VerifyAction};
 13
 14const SUPPORTED_METHODS: [VerificationMethod; 3] = [
 15    // Emoji verification
 16    VerificationMethod::SasV1,
 17    // QR Code verification
 18    VerificationMethod::ReciprocateV1,
 19    VerificationMethod::QrCodeShowV1,
 20];
 21
 22async fn maybe_autostart(request: &VerificationRequest) -> Result<(), matrix_sdk::Error> {
 23    if let Some(theirs) = request.their_supported_methods() {
 24        if theirs.contains(&VerificationMethod::QrCodeScanV1) &&
 25            theirs.contains(&VerificationMethod::ReciprocateV1)
 26        {
 27            // Generate a QR code to show. This doesn't actually mean we select
 28            // this flow.
 29            request.generate_qr_code().await?;
 30        } else if theirs.contains(&VerificationMethod::SasV1) {
 31            // We only have one method in common and don't need to query the
 32            // user.
 33            request.start_sas().await?;
 34        }
 35    }
 36
 37    Ok(())
 38}
 39
 40pub async fn handle_request(
 41    flow_id: String,
 42    other_user_id: OwnedUserId,
 43    other_device_id: OwnedDeviceId,
 44    client: Client,
 45    store: AsyncProgramStore,
 46) {
 47    let own_user_id = client.user_id().unwrap();
 48    let own_device_id = client.device_id().unwrap();
 49    if other_user_id == own_user_id && other_device_id == own_device_id {
 50        tracing::debug!("ignoring the verification request we sent");
 51        return;
 52    }
 53
 54    let Some(request) = client
 55        .encryption()
 56        .get_verification_request(&other_user_id, &flow_id)
 57        .await
 58    else {
 59        tracing::warn!("couldn't find verification request in crypto store");
 60        return;
 61    };
 62
 63    tracing::debug!("received a verification request");
 64
 65    store.lock().await.application.verifications.insert(flow_id, request);
 66}
 67
 68pub async fn handle_ready(
 69    flow_id: String,
 70    other_user_id: OwnedUserId,
 71    client: Client,
 72    store: AsyncProgramStore,
 73) {
 74    let Some(request) = client
 75        .encryption()
 76        .get_verification_request(&other_user_id, &flow_id)
 77        .await
 78    else {
 79        tracing::warn!("couldn't find verification request in crypto store");
 80        return;
 81    };
 82
 83    if let Err(err) = maybe_autostart(&request).await {
 84        tracing::warn!("unable to start verification process: {err}");
 85    }
 86
 87    // Insert the request in case we missed it. Not sure if this is needed.
 88    // Might happen with room verification requests if the client is restarted.
 89    store.lock().await.application.verifications.insert(flow_id, request);
 90}
 91
 92pub async fn handle_start(flow_id: String, other_user_id: OwnedUserId, client: Client) {
 93    match client.encryption().get_verification(&other_user_id, &flow_id).await {
 94        Some(Verification::SasV1(sas)) => {
 95            tracing::debug!("accepting SAS verification flow");
 96            if let Err(err) = sas.accept().await {
 97                tracing::warn!("unable to accept SAS verification flow: {err}");
 98            }
 99        },
100        Some(_) => {
101            tracing::info!("ignoring verification start with unsupported method");
102        },
103        None => {
104            tracing::warn!("couldn't find verification request in crypto store");
105        },
106    }
107}
108
109pub async fn iamb_verify(
110    act: VerifyAction,
111    flow_id: String,
112    store: &ProgramStore,
113) -> IambResult<EditInfo> {
114    let Some(request) = store.application.verifications.get(&flow_id) else {
115        return Err(IambError::InvalidVerificationId(flow_id).into());
116    };
117
118    match act {
119        VerifyAction::Accept => {
120            if request.their_supported_methods().is_none_or(|theirs| {
121                !(theirs.contains(&VerificationMethod::SasV1) ||
122                    theirs.contains(&VerificationMethod::QrCodeScanV1) &&
123                        theirs.contains(&VerificationMethod::ReciprocateV1))
124            }) {
125                let msg = "We don't have any verification methods in common.";
126                let err = UIError::Failure(msg.into());
127                return Err(err);
128            }
129
130            request
131                .accept_with_methods(SUPPORTED_METHODS.into())
132                .await
133                .map_err(IambError::from)?;
134
135            maybe_autostart(request).await.map_err(IambError::from)?;
136
137            Ok(Some(InfoMessage::from("Accepted verification request")))
138        },
139        VerifyAction::Emoji => {
140            if request
141                .their_supported_methods()
142                .is_none_or(|theirs| !theirs.contains(&VerificationMethod::SasV1))
143            {
144                let msg = "The other party doesn't support emoji verification.";
145                let err = UIError::Failure(msg.into());
146                return Err(err);
147            }
148
149            if request.start_sas().await.map_err(IambError::from)?.is_some() {
150                Ok(Some(InfoMessage::from("Verification started")))
151            } else {
152                let msg = "Can't start interactive verification at this point.";
153                let err = UIError::Failure(msg.into());
154                Err(err)
155            }
156        },
157        VerifyAction::Cancel => {
158            request.cancel().await.map_err(IambError::from)?;
159            Ok(Some(InfoMessage::from("Cancelled verification")))
160        },
161        VerifyAction::Confirm => {
162            match request.state() {
163                VerificationRequestState::Transitioned {
164                    verification: Verification::SasV1(sas),
165                } if sas.can_be_presented() => {
166                    sas.confirm().await.map_err(IambError::from)?;
167                },
168                VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) }
169                    if qr.has_been_scanned() =>
170                {
171                    qr.confirm().await.map_err(IambError::from)?;
172                },
173                _ => {
174                    let msg = "Can only confirm in-progress verifications!";
175                    let err = UIError::Failure(msg.into());
176                    return Err(err);
177                },
178            }
179
180            Ok(Some(InfoMessage::from("Confirmed verification")))
181        },
182        VerifyAction::Mismatch => {
183            match request.state() {
184                VerificationRequestState::Transitioned {
185                    verification: Verification::SasV1(sas),
186                } if sas.can_be_presented() => {
187                    sas.mismatch().await.map_err(IambError::from)?;
188                },
189                VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) }
190                    if qr.has_been_scanned() =>
191                {
192                    qr.cancel().await.map_err(IambError::from)?;
193                },
194                _ => {
195                    let msg = "Can only reject in-progress verifications!";
196                    let err = UIError::Failure(msg.into());
197                    return Err(err);
198                },
199            }
200
201            Ok(Some(InfoMessage::from("Rejected verification")))
202        },
203    }
204}
205
206pub async fn iamb_verify_request(
207    user_id: &UserId,
208    store: &mut ProgramStore,
209) -> IambResult<EditInfo> {
210    let enc = store.application.worker.client.encryption();
211
212    let Some(identity) = enc.get_user_identity(user_id).await.map_err(IambError::from)? else {
213        let msg = format!("Could not find identity information for {user_id}");
214        let err = UIError::Failure(msg);
215        return Err(err);
216    };
217
218    let request = identity.request_verification_with_methods(SUPPORTED_METHODS.into());
219    let request = request.await.map_err(IambError::from)?;
220
221    let flow_id = request.flow_id().to_owned();
222    store.application.verifications.insert(flow_id, request);
223
224    let info = format!("Sent verification request to {user_id}");
225    Ok(Some(InfoMessage::from(info)))
226}