From 7eb1c072694a8a62f4feea233e9a183699c25bf5 Mon Sep 17 00:00:00 2001 From: nworbnhoj Date: Fri, 29 Dec 2023 10:13:31 +1100 Subject: [PATCH] implement sigchat Manager Config Tie the Staging Environment specifics to the Account Manager Note sigchat is hard coded for the Staging Environment for now --- apps/sigchat/src/account.rs | 39 +++++---- .../src/account/service_environment.rs | 3 +- apps/sigchat/src/api.rs | 1 - apps/sigchat/src/lib.rs | 44 +++++----- apps/sigchat/src/manager.rs | 32 ++++---- apps/sigchat/src/manager/config.rs | 38 +++++++++ apps/sigchat/src/manager/signal_ws.rs | 81 ++++++++++--------- 7 files changed, 145 insertions(+), 93 deletions(-) create mode 100644 apps/sigchat/src/manager/config.rs diff --git a/apps/sigchat/src/account.rs b/apps/sigchat/src/account.rs index 027fdec26..6449f3845 100644 --- a/apps/sigchat/src/account.rs +++ b/apps/sigchat/src/account.rs @@ -26,7 +26,7 @@ pub struct Account { pni_service_id: Option, profile_key: Option, registered: bool, - service_environment: Option, + service_environment: ServiceEnvironment, storage_key: Option, store_last_receive_timestamp: i64, store_manifest_version: i64, @@ -69,7 +69,11 @@ impl Account { /// /// a new Account with default values /// - pub fn new(pddb_dict: &str) -> Result { + pub fn new( + pddb_dict: &str, + host: &Host, + service_environment: &ServiceEnvironment, + ) -> Result { let pddb = pddb::Pddb::new(); pddb.try_mount(); set(&pddb, pddb_dict, ACI_IDENTITY_PRIVATE_KEY, None)?; @@ -77,7 +81,7 @@ impl Account { set(&pddb, pddb_dict, ACI_SERVICE_ID_KEY, None)?; set(&pddb, pddb_dict, DEVICE_ID_KEY, Some("0"))?; set(&pddb, pddb_dict, ENCRYPTED_DEVICE_NAME_KEY, None)?; - set(&pddb, pddb_dict, HOST_KEY, Some(DEFAULT_HOST))?; + set(&pddb, pddb_dict, HOST_KEY, Some(&host.to_string()))?; set( &pddb, pddb_dict, @@ -92,7 +96,12 @@ impl Account { set(&pddb, pddb_dict, PNI_SERVICE_ID_KEY, None)?; set(&pddb, pddb_dict, PROFILE_KEY_KEY, None)?; set(&pddb, pddb_dict, REGISTERED_KEY, Some(&false.to_string()))?; - set(&pddb, pddb_dict, SERVICE_ENVIRONMENT_KEY, None)?; + set( + &pddb, + pddb_dict, + SERVICE_ENVIRONMENT_KEY, + Some(&service_environment.to_string()), + )?; set(&pddb, pddb_dict, STORAGE_KEY_KEY, None)?; set( &pddb, @@ -155,7 +164,7 @@ impl Account { Ok(pni_service_id), Ok(profile_key), Ok(Some(registered)), - Ok(service_environment), + Ok(Some(service_environment)), Ok(storage_key), Ok(Some(store_last_receive_timestamp)), Ok(Some(store_manifest_version)), @@ -178,8 +187,7 @@ impl Account { pni_service_id: pni_service_id, profile_key: profile_key, registered: registered.parse().unwrap(), - service_environment: service_environment - .map(|se| ServiceEnvironment::from_str(&se).unwrap()), + service_environment: ServiceEnvironment::from_str(&service_environment).unwrap(), storage_key: storage_key, store_last_receive_timestamp: store_last_receive_timestamp.parse().unwrap(), store_manifest_version: store_manifest_version.parse().unwrap(), @@ -226,8 +234,6 @@ impl Account { pub fn link( &mut self, device_name: &str, - host: &Host, - service_environment: &ServiceEnvironment, provisioning_msg: ProvisionMessage, ) -> Result { // TODO complete link pre-checks @@ -248,7 +254,6 @@ impl Account { aci.djb_private_key, )), )?; - self.set(HOST_KEY, Some(&host.to_string()))?; self.set(IS_MULTI_DEVICE_KEY, Some(&true.to_string()))?; self.set(NUMBER_KEY, Some(&provisioning_msg.number))?; self.set(PASSWORD_KEY, Some("STUB 32 bytes"))?; @@ -266,10 +271,6 @@ impl Account { ), )?; self.set(REGISTERED_KEY, Some(&false.to_string()))?; - self.set( - SERVICE_ENVIRONMENT_KEY, - Some(&service_environment.to_string()), - )?; self.set(STORAGE_KEY_KEY, None)?; self.set(STORE_LAST_RECEIVE_TIMESTAMP_KEY, Some("0"))?; self.set(STORE_MANIFEST_VERSION_KEY, Some("-1"))?; @@ -288,6 +289,10 @@ impl Account { Ok(false) } + pub fn host(&self) -> &Host { + &self.host + } + #[allow(dead_code)] pub fn number(&self) -> Option<&str> { match &self.number { @@ -296,6 +301,10 @@ impl Account { } } + pub fn service_environment(&self) -> &ServiceEnvironment { + &self.service_environment + } + #[allow(dead_code)] pub fn set_number(&mut self, value: &str) -> Result<(), Error> { match self.set(NUMBER_KEY, Some(value)) { @@ -343,7 +352,7 @@ impl Account { PROFILE_KEY_KEY => Ok(self.profile_key = owned_value), REGISTERED_KEY => Ok(self.registered = owned_value.unwrap().parse().unwrap()), SERVICE_ENVIRONMENT_KEY => Ok(self.service_environment = - Some(ServiceEnvironment::from_str(&value.unwrap()).unwrap())), + ServiceEnvironment::from_str(&value.unwrap()).unwrap()), STORAGE_KEY_KEY => Ok(self.storage_key = owned_value), _ => { log::warn!("invalid key: {key}"); diff --git a/apps/sigchat/src/account/service_environment.rs b/apps/sigchat/src/account/service_environment.rs index 64216d583..a0f17b8d3 100644 --- a/apps/sigchat/src/account/service_environment.rs +++ b/apps/sigchat/src/account/service_environment.rs @@ -1,9 +1,8 @@ -use rkyv::{Archive, Deserialize, Serialize}; use std::fmt; use std::str::FromStr; // The server environment to use: -#[derive(Archive, Serialize, Deserialize, Debug)] +#[derive(Clone, Debug)] pub enum ServiceEnvironment { Live, Staging, diff --git a/apps/sigchat/src/api.rs b/apps/sigchat/src/api.rs index e7f850f0d..c46640c3e 100644 --- a/apps/sigchat/src/api.rs +++ b/apps/sigchat/src/api.rs @@ -1,7 +1,6 @@ #[allow(dead_code)] pub(crate) const SERVER_NAME_SIGCHAT: &str = "_Signal chat_"; pub(crate) const DEFAULT_DEVICE_NAME: &str = "xous"; -pub(crate) const DEFAULT_HOST_NAME: &str = "chat.signal.org"; #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub enum SigchatOp { diff --git a/apps/sigchat/src/lib.rs b/apps/sigchat/src/lib.rs index dce5d00c0..0e516fcdc 100644 --- a/apps/sigchat/src/lib.rs +++ b/apps/sigchat/src/lib.rs @@ -2,14 +2,15 @@ mod account; pub mod api; mod manager; -use crate::account::{Account, ServiceEnvironment}; -use crate::manager::{Manager, TrustMode}; +use crate::account::{Account, ServiceEnvironment, DEFAULT_HOST}; +use crate::manager::{Config, Manager, TrustMode}; pub use api::*; use chat::Chat; use locales::t; use modals::Modals; use std::io::{Error, ErrorKind}; use tls::Tls; +use url::{Host, Url}; /// PDDB Dict for sigchat keys const SIGCHAT_ACCOUNT: &str = "sigchat.account"; @@ -105,6 +106,7 @@ impl<'a> SigChat<'a> { /// fn account_setup(&mut self) -> Result { log::info!("Attempting to setup a Signal Account"); + let service_environment = ServiceEnvironment::Staging; self.modals .add_list_item(t!("sigchat.account.link", locales::LANG)) .expect("failed add list item"); @@ -121,8 +123,9 @@ impl<'a> SigChat<'a> { Ok(index) => match index { 0 => { let host = self.host_modal(); - match self.probe_host(&host) { - true => Ok(self.account_link(&host)?), + let config = Config::new(host, service_environment); + match self.probe_host(config.url()) { + true => Ok(self.account_link(&config)?), false => Err(Error::new( ErrorKind::Other, "failed to trust host certificate", @@ -131,8 +134,9 @@ impl<'a> SigChat<'a> { } 1 => { let host = self.host_modal(); - match self.probe_host(&host) { - true => Ok(self.account_register(&host)?), + let config = Config::new(host, service_environment); + match self.probe_host(config.url()) { + true => Ok(self.account_register(&config)?), false => Err(Error::new( ErrorKind::Other, "failed to trust host certificate", @@ -170,7 +174,7 @@ impl<'a> SigChat<'a> { host = match self .modals .alert_builder(t!("sigchat.account.host.name", locales::LANG)) - .field(Some(DEFAULT_HOST_NAME.to_string()), None) + .field(Some(DEFAULT_HOST.to_string()), None) .build() { Ok(text) => match Host::parse(&text.content()[0].content.to_string()) { @@ -190,7 +194,7 @@ impl<'a> SigChat<'a> { None } }, - _ => Host::parse(DEFAULT_HOST_NAME).ok(), + _ => Host::parse(DEFAULT_HOST).ok(), } } host.unwrap() @@ -204,12 +208,12 @@ impl<'a> SigChat<'a> { /// # Returns /// true if at least 1 Certificate Authority is trusted /// - fn probe_host(&self, host: &str) -> bool { + fn probe_host(&self, url: &Url) -> bool { self.chat .set_status_text(t!("sigchat.status.probing", locales::LANG)); self.chat.set_busy_state(true); let tls = Tls::new(); - if tls.accessible(host, true) { + if tls.accessible(url.host_str().unwrap(), true) { self.chat.set_busy_state(false); true } else { @@ -230,17 +234,17 @@ impl<'a> SigChat<'a> { /// commences - culminating by presenting a qr-code to be scanned by the primary device. /// /// # Arguments - /// * `host` - the Signal server host name or ip-address + /// * `config` - Signal configuration - host server and Live/Staging environment /// /// # Returns /// Account struct stored in pddb /// - pub fn account_link(&mut self, host: &str) -> Result { + pub fn account_link(&mut self, config: &Config) -> Result { log::info!("Attempting to Link to an existing Signal Account"); self.chat .set_status_text(t!("sigchat.status.initializing", locales::LANG)); self.chat.set_busy_state(true); - match Account::new(SIGCHAT_ACCOUNT) { + match Account::new(SIGCHAT_ACCOUNT, config.host(), config.service_environment()) { Ok(account) => { let mut manager = Manager::new(account, TrustMode::OnFirstUse); let name = self.name_modal( @@ -250,11 +254,7 @@ impl<'a> SigChat<'a> { self.chat .set_status_text(t!("sigchat.status.connecting", locales::LANG)); self.chat.set_busy_state(true); - match manager.link( - Some(&name), - Some(&host), - Some(&ServiceEnvironment::Staging.to_string()), - ) { + match manager.link(&name) { Ok(true) => { log::info!("Linked Signal Account"); self.chat.set_busy_state(false); @@ -327,7 +327,11 @@ impl<'a> SigChat<'a> { /// The phone number must include the country calling code, i.e. the number must start with a "+" sign. /// Warning: this will disable the authentication of your phone as a primary device. /// - pub fn account_register(&mut self, _host: &str) -> Result { + /// # Arguments + /// + /// * `config` - Signal configuration - host server and Live/Staging environment + /// + pub fn account_register(&mut self, config: &Config) -> Result { log::info!("Attempting to Register a new Signal Account"); self.modals .show_notification(&"sorry - registration is not implemented yet", None) @@ -335,7 +339,7 @@ impl<'a> SigChat<'a> { match self.number_modal() { Ok(number) => { log::info!("registration phone number = {:?}", number); - match Account::new(SIGCHAT_ACCOUNT) { + match Account::new(SIGCHAT_ACCOUNT, config.host(), config.service_environment()) { Ok(mut account) => match account.set_number(&number.to_string()) { Ok(_number) => { self.manager = Some(Manager::new(account, TrustMode::OnFirstUse)); diff --git a/apps/sigchat/src/manager.rs b/apps/sigchat/src/manager.rs index 8a70721ef..01860e721 100644 --- a/apps/sigchat/src/manager.rs +++ b/apps/sigchat/src/manager.rs @@ -1,10 +1,12 @@ +mod config; mod group_permission; pub mod libsignal; // stub mod link_state; mod signal_ws; mod trust_mode; -use crate::{Account, ServiceEnvironment, DEFAULT_DEVICE_NAME, DEFAULT_HOST_NAME}; +use crate::Account; +pub use config::Config; use group_permission::GroupPermission; use link_state::LinkState; use locales::t; @@ -22,6 +24,7 @@ use tungstenite::Message; #[allow(dead_code)] pub struct Manager { account: Account, + config: Config, trust_mode: TrustMode, websocket: Option, log_verbose: bool, @@ -37,8 +40,13 @@ impl Manager { /// * `account` - Specify your phone number, that will be your identifier. The phone number must include the country calling code, i.e. the number must start with a "+" sign. /// pub fn new(account: Account, trust_mode: TrustMode) -> Manager { + let config = Config::new( + account.host().clone(), + account.service_environment().clone(), + ); Manager { account, + config, trust_mode, websocket: None, log_verbose: false, @@ -141,24 +149,15 @@ impl Manager { /// 7. checking and saving account details /// /// # Arguments - /// * `name` - Optionally specify a name to describe this new device (defaults to "xous"). - /// * `host` - Optionally specify a host to connect to (defaults to "signal.org"). - /// * `service_environment` - Optionally specify a service_environment to connect to (defaults to "Live"). + /// * `name` - name to describe this new device + /// * `config` - Signal configuration - host server and Live/Staging environment + /// * `service_environment` - service_environment to connect to on host /// #[allow(dead_code)] - pub fn link( - &mut self, - name: Option<&str>, - host: Option<&str>, - service_environment: Option<&str>, - ) -> Result { - // insert default values as required - let name = name.unwrap_or(DEFAULT_DEVICE_NAME); - let host = host.unwrap_or(DEFAULT_HOST_NAME); - let live_service_environment = ServiceEnvironment::Live.to_string(); - let service_environment = service_environment.unwrap_or(&live_service_environment); + pub fn link(&mut self, name: &str) -> Result { let link_err = Error::new(ErrorKind::Other, "failed to link device"); - match SignalWS::new_provision(&host) { + let mut host = self.config.url().clone(); + match SignalWS::new_provision(&mut host) { Ok(mut ws) => { log::info!("provisioning websocket established to {host}"); let result = match ws.read(Some(Duration::from_millis(5000))) { @@ -187,7 +186,6 @@ impl Manager { log::info!("Registration message received from host"); match self.account.link( name, - service_environment, libsignal::ProvisionMessage::decode( identity_key_pair, registration, diff --git a/apps/sigchat/src/manager/config.rs b/apps/sigchat/src/manager/config.rs new file mode 100644 index 000000000..572a36cc7 --- /dev/null +++ b/apps/sigchat/src/manager/config.rs @@ -0,0 +1,38 @@ +use crate::ServiceEnvironment; +use url::{Host, Url}; + +pub struct Config { + host: Host, + service_environment: ServiceEnvironment, + url: Url, +} + +impl Config { + pub fn new(host: Host, service_environment: ServiceEnvironment) -> Self { + let host_base = host.to_string(); + match service_environment { + ServiceEnvironment::Live => Self { + host: host, + service_environment: service_environment, + url: Url::parse(&format!("https://chat.{}", host_base)).unwrap(), + }, + ServiceEnvironment::Staging => Self { + host: host, + service_environment: service_environment, + url: Url::parse(&format!("https://chat.staging.{}", host_base)).unwrap(), + }, + } + } + + pub fn host(&self) -> &Host { + &self.host + } + + pub fn service_environment(&self) -> &ServiceEnvironment { + &self.service_environment + } + + pub fn url(&self) -> &Url { + &self.url + } +} diff --git a/apps/sigchat/src/manager/signal_ws.rs b/apps/sigchat/src/manager/signal_ws.rs index beb0da0c7..70a2f17d8 100644 --- a/apps/sigchat/src/manager/signal_ws.rs +++ b/apps/sigchat/src/manager/signal_ws.rs @@ -6,9 +6,10 @@ use std::thread; use std::time::Duration; use tls::Tls; use tungstenite::{Message, WebSocket}; +use url::Url; -const PROVISIONING_PATH: &str = "/v1/websocket/provisioning/"; -const REGISTRATION_PATH: &str = "/v1/registration"; +const PROVISIONING_PATH: [&str; 4] = ["v1", "websocket", "provisioning", ""]; +const REGISTRATION_PATH: [&str; 3] = ["v1", "registration", ""]; #[allow(dead_code)] pub struct SignalWS { @@ -21,8 +22,8 @@ impl SignalWS { todo!(); } - fn new(server: &str) -> Result { - match SignalWS::connect(server) { + fn new(url: &Url) -> Result { + match SignalWS::connect(url) { Ok(ws) => Ok(Self { ws: Arc::new(Mutex::new(ws)), }), @@ -30,13 +31,21 @@ impl SignalWS { } } - pub fn new_provision(host: &str) -> Result { - Ok(Self::new(&format!("wss://{host}{}", PROVISIONING_PATH))?) + pub fn new_provision(url: &mut Url) -> Result { + url.set_scheme("wss").expect("failed to set scheme"); + url.path_segments_mut() + .expect("failed to add path") + .extend(&PROVISIONING_PATH); + Ok(Self::new(&url)?) } #[allow(dead_code)] - pub fn new_register(host: &str) -> Result { - Ok(Self::new(&format!("wss://{host}{}", REGISTRATION_PATH))?) + pub fn new_register(url: &mut Url) -> Result { + url.set_scheme("wss").expect("failed to set scheme"); + url.path_segments_mut() + .expect("failed to add path") + .extend(®ISTRATION_PATH); + Ok(Self::new(&url)?) } pub fn close(&mut self) { @@ -122,53 +131,49 @@ impl SignalWS { } } + #[allow(dead_code)] + pub fn send(&mut self, _message: Message) -> Result<(), Error> { + todo!() + } + /// Make a websocket connection to host server /// /// # Arguments - /// * `server` - server + /// * `url` - url of Signal server /// /// # Returns /// - fn connect(server: &str) -> Result>, Error> { - log::info!("connecting websocket"); - match url::Url::parse(server) { - Ok(url) => { - log::info!("attempting websocket connection to {}", url.as_str()); - let host = url.host_str().expect("failed to extract host from url"); - match TcpStream::connect((host, 443)) { - Ok(sock) => { - log::info!("tcp connected to {host}"); - let xtls = Tls::new(); - match xtls.stream_owned(host, sock) { - Ok(tls_stream) => { - log::info!("tls configured"); - match tungstenite::client(url, tls_stream) { - Ok((socket, response)) => { - log::info!("Websocket connected to: {}", server); - log::info!("Response HTTP code: {}", response.status()); - Ok(socket) - } - Err(e) => { - log::info!("failed to connect websocket: {}", e); - Err(Error::from(ErrorKind::ConnectionRefused)) - } - } + fn connect(url: &Url) -> Result>, Error> { + log::info!("attempting websocket connection to {}", url.as_str()); + let host = url.host_str().expect("failed to extract host from url"); + match TcpStream::connect((host, 443)) { + Ok(sock) => { + log::info!("tcp connected to {host}"); + let xtls = Tls::new(); + match xtls.stream_owned(host, sock) { + Ok(tls_stream) => { + log::info!("tls configured"); + match tungstenite::client(url, tls_stream) { + Ok((socket, response)) => { + log::info!("Websocket connected to: {}", url.as_str()); + log::info!("Response HTTP code: {}", response.status()); + Ok(socket) } Err(e) => { - log::warn!("failed to configure tls: {e}"); - Err(e) + log::info!("failed to connect websocket: {}", e); + Err(Error::from(ErrorKind::ConnectionRefused)) } } } Err(e) => { - log::warn!("failed to connect tcp: {e}"); + log::warn!("failed to configure tls: {e}"); Err(e) } } } Err(e) => { - log::info!("failed to parse server url: {e}"); - Err(Error::new(ErrorKind::InvalidData, e)) + log::warn!("failed to connect tcp: {e}"); + Err(e) } } }