Commit 46f50f5aa4

46f50f5aa430cdd6b3bd80e554c2fe6cb42a499c

parent: 9880f35b9a

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-29 16:10 UTC
committer: <strk@kbt.io>

feat: inspect and trust Matrix devices

Layout: unified · split

src/commands/matrix.rs +11 −2
@@ -16,7 +16,7 @@ use super::{
16 verification::VerificationCommand, 16 verification::VerificationCommand,
17}; 17};
18use crate::{ 18use crate::{
19 commands::{DevicesCommand, KeysCommand, MediaCommand}, 19 commands::{DevicesCommand, KeysCommand, MediaCommand, VerifyCommand},
20 config::ConfigHandle, 20 config::ConfigHandle,
21 MatrixServer, Servers, PLUGIN_NAME, 21 MatrixServer, Servers, PLUGIN_NAME,
22}; 22};
@@ -40,6 +40,8 @@ impl MatrixCommand {
40 .add_argument("devices delete|list|set-name") 40 .add_argument("devices delete|list|set-name")
41 .add_argument("keys import|export <file> <passphrase>") 41 .add_argument("keys import|export <file> <passphrase>")
42 .add_argument("media download <mxc-uri> [file]") 42 .add_argument("media download <mxc-uri> [file]")
43 .add_argument("verify <contact> <device-id>")
44 .add_argument("verification info [contact]")
43 .add_argument("disconnect <server-name>") 45 .add_argument("disconnect <server-name>")
44 .add_argument("reconnect <server-name>") 46 .add_argument("reconnect <server-name>")
45 .add_argument("sso-complete <server-name> <login-token>") 47 .add_argument("sso-complete <server-name> <login-token>")
@@ -58,18 +60,21 @@ sso-complete: Finish SSO login with a copied loginToken.
58 devices: {} 60 devices: {}
59 keys: {} 61 keys: {}
60 media: {} 62 media: {}
63 verify: {}
61verification: {} 64verification: {}
62 help: Show detailed command help.\n 65 help: Show detailed command help.\n
63Use /matrix [command] help to find out more.\n", 66Use /matrix [command] help to find out more.\n",
64 DevicesCommand::DESCRIPTION, 67 DevicesCommand::DESCRIPTION,
65 KeysCommand::DESCRIPTION, 68 KeysCommand::DESCRIPTION,
66 MediaCommand::DESCRIPTION, 69 MediaCommand::DESCRIPTION,
70 VerifyCommand::DESCRIPTION,
67 VerificationCommand::DESCRIPTION, 71 VerificationCommand::DESCRIPTION,
68 )) 72 ))
69 .add_completion("server add|delete|list|listfull") 73 .add_completion("server add|delete|list|listfull")
70 .add_completion("devices list|delete|set-name %(matrix-users)") 74 .add_completion("devices list|delete|set-name %(matrix-users)")
71 .add_completion(format!("keys {}", KeysCommand::COMPLETION)) 75 .add_completion(format!("keys {}", KeysCommand::COMPLETION))
72 .add_completion(format!("media {}", MediaCommand::COMPLETION)) 76 .add_completion(format!("media {}", MediaCommand::COMPLETION))
77 .add_completion("verify %(matrix-users)")
73 .add_completion(format!( 78 .add_completion(format!(
74 "verification {}", 79 "verification {}",
75 VerificationCommand::COMPLETION 80 VerificationCommand::COMPLETION
@@ -79,7 +84,7 @@ Use /matrix [command] help to find out more.\n",
79 .add_completion("reconnect %(matrix_servers)") 84 .add_completion("reconnect %(matrix_servers)")
80 .add_completion("sso-complete %(matrix_servers)") 85 .add_completion("sso-complete %(matrix_servers)")
81 .add_completion( 86 .add_completion(
82 "help server|connect|disconnect|reconnect|join|sso-complete|read|version|keys|devices|media|verification", 87 "help server|connect|disconnect|reconnect|join|sso-complete|read|version|keys|devices|media|verify|verification",
83 ); 88 );
84 89
85 Command::new( 90 Command::new(
@@ -286,6 +291,9 @@ Use /matrix [command] help to find out more.\n",
286 ("media", Some(subargs)) => { 291 ("media", Some(subargs)) => {
287 MediaCommand::run(buffer, &self.servers, subargs) 292 MediaCommand::run(buffer, &self.servers, subargs)
288 } 293 }
294 ("verify", Some(subargs)) => {
295 VerifyCommand::run(buffer, &self.servers, subargs)
296 }
289 ("verification", Some(subargs)) => { 297 ("verification", Some(subargs)) => {
290 VerificationCommand::run(buffer, &self.servers, subargs) 298 VerificationCommand::run(buffer, &self.servers, subargs)
291 } 299 }
@@ -381,6 +389,7 @@ impl CommandCallback for MatrixCommand {
381 .settings(VerificationCommand::SETTINGS) 389 .settings(VerificationCommand::SETTINGS)
382 .subcommands(VerificationCommand::subcommands()), 390 .subcommands(VerificationCommand::subcommands()),
383 ) 391 )
392 .subcommand(VerifyCommand::parser())
384 .subcommand( 393 .subcommand(
385 SubCommand::with_name("connect") 394 SubCommand::with_name("connect")
386 .about("Connect to Matrix servers.") 395 .about("Connect to Matrix servers.")
src/commands/mod.rs +2
@@ -28,6 +28,7 @@ mod reply;
28mod topic; 28mod topic;
29mod upload; 29mod upload;
30mod verification; 30mod verification;
31mod verify;
31 32
32use buffer_clear::BufferClearCommand; 33use buffer_clear::BufferClearCommand;
33use buffer_switch::BufferSwitchCommand; 34use buffer_switch::BufferSwitchCommand;
@@ -51,6 +52,7 @@ use redact::RedactCommand;
51use reply::ReplyCommand; 52use reply::ReplyCommand;
52use topic::TopicCommand; 53use topic::TopicCommand;
53use upload::UploadCommand; 54use upload::UploadCommand;
55use verify::VerifyCommand;
54 56
55pub struct Commands { 57pub struct Commands {
56 _matrix: Command, 58 _matrix: Command,
src/commands/verification.rs +66 −2
@@ -28,7 +28,7 @@ impl VerificationCommand {
28 "Control interactive verification flows"; 28 "Control interactive verification flows";
29 29
30 pub const COMPLETION: &'static str = 30 pub const COMPLETION: &'static str =
31 "start %(matrix-users)|accept|confirm|cancel"; 31 "start %(matrix-users)|info %(matrix-users)|accept|confirm|cancel";
32 pub const SETTINGS: &'static [ArgParseSettings] = &[ 32 pub const SETTINGS: &'static [ArgParseSettings] = &[
33 ArgParseSettings::DisableHelpFlags, 33 ArgParseSettings::DisableHelpFlags,
34 ArgParseSettings::DisableVersion, 34 ArgParseSettings::DisableVersion,
@@ -40,16 +40,18 @@ impl VerificationCommand {
40 let settings = CommandSettings::new("verification") 40 let settings = CommandSettings::new("verification")
41 .description(Self::DESCRIPTION) 41 .description(Self::DESCRIPTION)
42 .add_argument("verification start <contact>") 42 .add_argument("verification start <contact>")
43 .add_argument("verification info [contact]")
43 .add_argument("verification accept|confirm|cancel") 44 .add_argument("verification accept|confirm|cancel")
44 .arguments_description( 45 .arguments_description(
45 " start: start an interactive verification with a contact 46 " start: start an interactive verification with a contact
47 info: show verification state for one or all known contacts
46 accept: accept the verification request 48 accept: accept the verification request
47 confirm: confirm that the emojis match on both sides or \ 49 confirm: confirm that the emojis match on both sides or \
48 confirm that the other side has scanned our QR code 50 confirm that the other side has scanned our QR code
49 cancel: cancel the verification flow or request", 51 cancel: cancel the verification flow or request",
50 ) 52 )
51 .add_completion(Self::COMPLETION) 53 .add_completion(Self::COMPLETION)
52 .add_completion("help accept|confirm|cancel"); 54 .add_completion("help start|info|accept|confirm|cancel");
53 55
54 Command::new( 56 Command::new(
55 settings, 57 settings,
@@ -93,6 +95,17 @@ impl VerificationCommand {
93 } 95 }
94 } 96 }
95 97
98 fn info(servers: &Servers, buffer: &Buffer, user_id: Option<OwnedUserId>) {
99 if let Some(server) = servers.find_server(buffer) {
100 Weechat::spawn(async move {
101 server.verification_info(user_id).await;
102 })
103 .detach();
104 } else {
105 Weechat::print("Must be executed on Matrix buffer")
106 }
107 }
108
96 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) { 109 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
97 match args.subcommand() { 110 match args.subcommand() {
98 ("start", Some(args)) => { 111 ("start", Some(args)) => {
@@ -103,6 +116,13 @@ impl VerificationCommand {
103 .expect("Contact wasn't a valid Matrix user ID"); 116 .expect("Contact wasn't a valid Matrix user ID");
104 Self::start(servers, buffer, user_id); 117 Self::start(servers, buffer, user_id);
105 } 118 }
119 ("info", Some(args)) => {
120 let user_id = args.value_of("contact").map(|contact| {
121 UserId::parse(contact)
122 .expect("Contact wasn't a valid Matrix user ID")
123 });
124 Self::info(servers, buffer, user_id);
125 }
106 ("accept", _) => { 126 ("accept", _) => {
107 Self::verification(servers, buffer, CommandType::Accept) 127 Self::verification(servers, buffer, CommandType::Accept)
108 } 128 }
@@ -128,6 +148,16 @@ impl VerificationCommand {
128 }) 148 })
129 }, 149 },
130 )), 150 )),
151 SubCommand::with_name("info")
152 .about("Show verification state for one or all known contacts")
153 .arg(Arg::with_name("contact").required(false).validator(
154 |contact| {
155 UserId::parse(contact).map(|_| ()).map_err(|_| {
156 "The contact isn't a valid Matrix user ID"
157 .to_owned()
158 })
159 },
160 )),
131 SubCommand::with_name("accept") 161 SubCommand::with_name("accept")
132 .about("Accept a verification request"), 162 .about("Accept a verification request"),
133 SubCommand::with_name("confirm").about( 163 SubCommand::with_name("confirm").about(
@@ -170,6 +200,40 @@ mod tests {
170 .get_matches_from_safe(vec!["verification", "start", "alice"]) 200 .get_matches_from_safe(vec!["verification", "start", "alice"])
171 .is_err()); 201 .is_err());
172 } 202 }
203
204 #[test]
205 fn parses_verification_info_with_optional_contact() {
206 let all = parser()
207 .get_matches_from_safe(vec!["verification", "info"])
208 .expect("valid verification info command");
209 assert_eq!(
210 all.subcommand_matches("info")
211 .expect("info args")
212 .value_of("contact"),
213 None
214 );
215
216 let one = parser()
217 .get_matches_from_safe(vec![
218 "verification",
219 "info",
220 "@alice:example.org",
221 ])
222 .expect("valid verification info contact");
223 assert_eq!(
224 one.subcommand_matches("info")
225 .expect("info args")
226 .value_of("contact"),
227 Some("@alice:example.org")
228 );
229 }
230
231 #[test]
232 fn rejects_invalid_verification_info_contact() {
233 assert!(parser()
234 .get_matches_from_safe(vec!["verification", "info", "alice"])
235 .is_err());
236 }
173} 237}
174 238
175impl CommandCallback for VerificationCommand { 239impl CommandCallback for VerificationCommand {
src/commands/verify.rs added +75
@@ -0,0 +1,75 @@
1use clap::{App as Argparse, Arg, ArgMatches};
2use matrix_sdk::ruma::{OwnedDeviceId, UserId};
3use weechat::{buffer::Buffer, Weechat};
4
5use crate::Servers;
6
7pub struct VerifyCommand;
8
9impl VerifyCommand {
10 pub const DESCRIPTION: &'static str =
11 "Mark an exact Matrix device as locally verified";
12
13 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
14 let user_id = UserId::parse(
15 args.value_of("contact")
16 .expect("Contact wasn't provided despite being required"),
17 )
18 .expect("Contact wasn't a valid Matrix user ID");
19 let device_id: OwnedDeviceId = args
20 .value_of("device-id")
21 .expect("Device ID wasn't provided despite being required")
22 .into();
23
24 if let Some(server) = servers.find_server(buffer) {
25 Weechat::spawn(async move {
26 server.mark_device_verified(user_id, device_id).await;
27 })
28 .detach();
29 } else {
30 Weechat::print("Must be executed on Matrix buffer")
31 }
32 }
33
34 pub fn parser() -> Argparse<'static, 'static> {
35 Argparse::new("verify")
36 .about(Self::DESCRIPTION)
37 .arg(Arg::with_name("contact").required(true).validator(
38 |contact| {
39 UserId::parse(contact).map(|_| ()).map_err(|_| {
40 "The contact isn't a valid Matrix user ID".to_owned()
41 })
42 },
43 ))
44 .arg(Arg::with_name("device-id").required(true))
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51
52 #[test]
53 fn parses_exact_contact_and_device() {
54 let matches = VerifyCommand::parser()
55 .get_matches_from_safe(vec![
56 "verify",
57 "@alice:example.org",
58 "ALICEDEVICE",
59 ])
60 .expect("valid verify command");
61
62 assert_eq!(matches.value_of("contact"), Some("@alice:example.org"));
63 assert_eq!(matches.value_of("device-id"), Some("ALICEDEVICE"));
64 }
65
66 #[test]
67 fn rejects_missing_or_invalid_target() {
68 assert!(VerifyCommand::parser()
69 .get_matches_from_safe(vec!["verify", "alice", "ALICEDEVICE"])
70 .is_err());
71 assert!(VerifyCommand::parser()
72 .get_matches_from_safe(vec!["verify", "@alice:example.org"])
73 .is_err());
74 }
75}
src/server.rs +172 −1
@@ -70,7 +70,7 @@ use url::Url;
70use matrix_sdk::{ 70use matrix_sdk::{
71 self, 71 self,
72 deserialized_responses::AmbiguityChange, 72 deserialized_responses::AmbiguityChange,
73 encryption::RoomKeyImportResult, 73 encryption::{LocalTrust, RoomKeyImportResult},
74 media::{MediaFormat, MediaRequestParameters}, 74 media::{MediaFormat, MediaRequestParameters},
75 room::Room, 75 room::Room,
76 ruma::{ 76 ruma::{
@@ -1918,6 +1918,177 @@ impl InnerServer {
1918 } 1918 }
1919 } 1919 }
1920 1920
1921 pub async fn mark_device_verified(
1922 &self,
1923 user_id: OwnedUserId,
1924 device_id: OwnedDeviceId,
1925 ) {
1926 let Some(connection) = self.connection() else {
1927 self.print_error("You must be connected to execute this command");
1928 return;
1929 };
1930
1931 let client = connection.client().clone();
1932 let requested_user_id = user_id.clone();
1933 let requested_device_id = device_id.clone();
1934 let result = connection
1935 .spawn(async move {
1936 client
1937 .encryption()
1938 .request_user_identity(&requested_user_id)
1939 .await
1940 .map_err(|error| error.to_string())?;
1941
1942 let Some(device) = client
1943 .encryption()
1944 .get_device(&requested_user_id, &requested_device_id)
1945 .await
1946 .map_err(|error| error.to_string())?
1947 else {
1948 return Ok::<_, String>(false);
1949 };
1950
1951 device
1952 .set_local_trust(LocalTrust::Verified)
1953 .await
1954 .map_err(|error| error.to_string())?;
1955 Ok::<_, String>(true)
1956 })
1957 .await;
1958
1959 match result {
1960 Ok(true) => self.print_network(&format!(
1961 "Marked device {} of {} as locally verified on this client",
1962 device_id, user_id
1963 )),
1964 Ok(false) => self.print_error(&format!(
1965 "Device {} of {} was not found",
1966 device_id, user_id
1967 )),
1968 Err(error) => self.print_error(&format!(
1969 "Error marking device {} of {} as locally verified: {}",
1970 device_id, user_id, error
1971 )),
1972 }
1973 }
1974
1975 pub async fn verification_info(&self, user_id: Option<OwnedUserId>) {
1976 let Some(connection) = self.connection() else {
1977 self.print_error("You must be connected to execute this command");
1978 return;
1979 };
1980
1981 let client = connection.client().clone();
1982 let result = connection
1983 .spawn(async move {
1984 let encryption = client.encryption();
1985 let refresh_identity = user_id.is_some();
1986 let mut users = if let Some(user_id) = user_id {
1987 vec![user_id]
1988 } else {
1989 encryption
1990 .tracked_users()
1991 .await
1992 .map_err(|error| error.to_string())?
1993 .into_iter()
1994 .collect::<Vec<_>>()
1995 };
1996 users.sort();
1997
1998 let mut report = Vec::new();
1999
2000 for user_id in users {
2001 let identity = if refresh_identity {
2002 encryption
2003 .request_user_identity(&user_id)
2004 .await
2005 .map_err(|error| error.to_string())?
2006 } else {
2007 encryption
2008 .get_user_identity(&user_id)
2009 .await
2010 .map_err(|error| error.to_string())?
2011 };
2012 let identity_state = match identity.as_ref() {
2013 Some(identity)
2014 if identity.has_verification_violation() =>
2015 {
2016 "verification violation"
2017 }
2018 Some(identity) if identity.is_verified() => "verified",
2019 Some(identity)
2020 if identity.was_previously_verified() =>
2021 {
2022 "previously verified"
2023 }
2024 Some(_) => "not verified",
2025 None => "no cross-signing identity",
2026 };
2027
2028 report.push(format!("{}: {}", user_id, identity_state));
2029
2030 let devices = encryption
2031 .get_user_devices(&user_id)
2032 .await
2033 .map_err(|error| error.to_string())?;
2034 let mut device_lines = devices
2035 .devices()
2036 .map(|device| {
2037 let state = if device
2038 .is_verified_with_cross_signing()
2039 {
2040 "verified by cross-signing"
2041 } else {
2042 match device.local_trust_state() {
2043 LocalTrust::Verified => {
2044 "locally trusted only"
2045 }
2046 LocalTrust::BlackListed => "blacklisted",
2047 LocalTrust::Ignored => "ignored",
2048 LocalTrust::Unset
2049 if device.is_verified() =>
2050 {
2051 "verified"
2052 }
2053 LocalTrust::Unset => "not verified",
2054 }
2055 };
2056 let name = device
2057 .display_name()
2058 .map(|name| format!(" ({name})"))
2059 .unwrap_or_default();
2060
2061 format!(
2062 " {}{}: {}",
2063 device.device_id(),
2064 name,
2065 state
2066 )
2067 })
2068 .collect::<Vec<_>>();
2069 device_lines.sort();
2070 report.extend(device_lines);
2071 }
2072
2073 Ok::<_, String>(report)
2074 })
2075 .await;
2076
2077 match result {
2078 Ok(report) if report.is_empty() => self.print_error(
2079 "No tracked Matrix contacts have verification information",
2080 ),
2081 Ok(report) => {
2082 self.print_network("Matrix verification state:");
2083 self.print(&report.join("\n"));
2084 }
2085 Err(error) => self.print_error(&format!(
2086 "Error fetching Matrix verification state: {}",
2087 error
2088 )),
2089 }
2090 }
2091
1921 pub fn autoconnect(&self) -> bool { 2092 pub fn autoconnect(&self) -> bool {
1922 self.settings.borrow().autoconnect 2093 self.settings.borrow().autoconnect
1923 } 2094 }