src/verifications.rs

271 lines · 9982 bytes

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