Skip to content

Commit

Permalink
De-duplicate provisioning code (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
gferon authored Apr 20, 2021
1 parent 0544a61 commit e26dfbe
Show file tree
Hide file tree
Showing 14 changed files with 1,033 additions and 1,017 deletions.
23 changes: 13 additions & 10 deletions libsignal-service-actix/examples/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ use qrcode::QrCode;
use rand::{distributions::Alphanumeric, Rng, RngCore};
use structopt::StructOpt;

use libsignal_protocol::{crypto::DefaultCrypto, Context};
use libsignal_service_actix::provisioning::{
provision_secondary_device, SecondaryDeviceProvisioning,
use libsignal_protocol::Context;

use libsignal_service::{
provisioning::LinkingManager, provisioning::SecondaryDeviceProvisioning,
USER_AGENT,
};
use libsignal_service_actix::prelude::AwcPushService;

#[derive(Debug, StructOpt)]
struct Args {
Expand All @@ -34,7 +37,7 @@ async fn main() -> Result<(), Error> {
// generate a random 16 bytes password
let mut rng = rand::rngs::OsRng::default();
let password: Vec<u8> = rng.sample_iter(&Alphanumeric).take(24).collect();
let password = std::str::from_utf8(&password)?;
let password = String::from_utf8(password)?;

// generate a 52 bytes signaling key
let mut signaling_key = [0u8; 52];
Expand All @@ -44,17 +47,17 @@ async fn main() -> Result<(), Error> {
base64::encode(&signaling_key.to_vec())
);

let signal_context = Context::new(DefaultCrypto::default()).unwrap();
let service_configuration = args.servers.into();
let signal_context = Context::default();

let mut provision_manager: LinkingManager<AwcPushService> =
LinkingManager::new(args.servers, USER_AGENT.into(), password);

let (tx, mut rx) = channel(1);

let (fut1, fut2) = future::join(
provision_secondary_device(
provision_manager.provision_secondary_device(
&signal_context,
&service_configuration,
&signaling_key,
password,
signaling_key,
&args.device_name,
tx,
),
Expand Down
74 changes: 18 additions & 56 deletions libsignal-service-actix/examples/registering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,46 +18,32 @@
//! ```
use failure::Error;
use libsignal_protocol::Context;
use libsignal_service::{configuration::*, AccountManager};
use libsignal_service_actix::push_service::AwcPushService;
use std::io;
use libsignal_service::{
configuration::*, provisioning::ProvisioningManager, USER_AGENT,
};
use libsignal_service_actix::prelude::AwcPushService;
use structopt::StructOpt;

#[actix_rt::main]
async fn main() -> Result<(), Error> {
env_logger::init();

let args = Args::from_args();

// Only used with MessageSender and MessageReceiver
let password = args.get_password()?;

let config: ServiceConfiguration = SignalServers::Staging.into();

let mut signaling_key = [0u8; 52];
base64::decode_config_slice(
args.signaling_key,
base64::STANDARD,
&mut signaling_key,
)
.unwrap();
let credentials = ServiceCredentials {
uuid: None,
phonenumber: args.username.clone(),
password: Some(password),
signaling_key: Some(signaling_key),
device_id: None,
};
// let password = args.get_password()?;

let signal_context = Context::default();
let mut provision_manager: ProvisioningManager<AwcPushService> =
ProvisioningManager::new(
args.servers,
USER_AGENT.into(),
args.username,
args.password.unwrap(),
);

let push_service =
AwcPushService::new(config, Some(credentials), &args.user_agent);

let mut account_manager =
AccountManager::new(signal_context, push_service, None);
account_manager
provision_manager
// You probably want to generate a reCAPTCHA though!
.request_sms_verification_code(args.username, None, None)
.request_sms_verification_code(None, None)
.await?;

Ok(())
Expand All @@ -67,8 +53,8 @@ async fn main() -> Result<(), Error> {
pub struct Args {
#[structopt(
short = "s",
long = "server",
help = "The server to connect to",
long = "servers",
help = "The servers to connect to",
default_value = "staging"
)]
pub servers: SignalServers,
Expand All @@ -85,28 +71,4 @@ pub struct Args {
help = "The password to use. Read from stdin if not provided"
)]
pub password: Option<String>,
#[structopt(
long = "user-agent",
help = "The user agent to use when contacting servers",
default_value = "libsignal_service::USER_AGENT"
)]
pub user_agent: String,
#[structopt(
long = "signaling-key",
help = "The key used to encrypt and authenticate messages in transit, base64 encoded."
)]
pub signaling_key: String,
}

impl Args {
pub fn get_password(&self) -> Result<String, Error> {
if let Some(ref pw) = self.password {
return Ok(pw.clone());
}

let mut line = String::new();
io::stdin().read_line(&mut line)?;

Ok(line.trim().to_string())
}
}
2 changes: 0 additions & 2 deletions libsignal-service-actix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,3 @@ pub mod websocket;
pub mod prelude {
pub use crate::push_service::*;
}

pub mod provisioning;
161 changes: 0 additions & 161 deletions libsignal-service-actix/src/provisioning.rs

This file was deleted.

33 changes: 17 additions & 16 deletions libsignal-service-actix/src/push_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,6 @@ pub struct AwcPushService {
}

impl AwcPushService {
/// Creates a new AwcPushService
pub fn new(
cfg: ServiceConfiguration,
credentials: Option<ServiceCredentials>,
user_agent: &str,
) -> Self {
let client = get_client(&cfg, user_agent);
Self {
cfg,
credentials: credentials.and_then(|c| c.authorization()),
client,
}
}

fn request(
&self,
method: Method,
Expand Down Expand Up @@ -120,6 +106,20 @@ impl PushService for AwcPushService {
type ByteStream = Box<dyn futures::io::AsyncRead + Unpin>;
type WebSocket = AwcWebSocket;

fn new(
cfg: impl Into<ServiceConfiguration>,
credentials: Option<ServiceCredentials>,
user_agent: String,
) -> Self {
let cfg = cfg.into();
let client = get_client(&cfg, user_agent);
Self {
cfg,
credentials: credentials.and_then(|c| c.authorization()),
client,
}
}

async fn get_json<T>(
&mut self,
endpoint: Endpoint,
Expand Down Expand Up @@ -240,14 +240,15 @@ impl PushService for AwcPushService {
&mut self,
endpoint: Endpoint,
path: &str,
credentials_override: Option<HttpCredentials>,
value: S,
) -> Result<D, ServiceError>
where
for<'de> D: Deserialize<'de>,
S: Serialize,
{
let mut response = self
.request(Method::PUT, endpoint, path, None)?
.request(Method::PUT, endpoint, path, credentials_override)?
.send_json(&value)
.await
.map_err(|e| ServiceError::SendError {
Expand Down Expand Up @@ -486,7 +487,7 @@ impl PushService for AwcPushService {
/// * 10s timeout on TCP connection
/// * 65s timeout on HTTP request
/// * provided user-agent
fn get_client(cfg: &ServiceConfiguration, user_agent: &str) -> Client {
fn get_client(cfg: &ServiceConfiguration, user_agent: String) -> Client {
let mut ssl_config = rustls::ClientConfig::new();
ssl_config.alpn_protocols = vec![b"http/1.1".to_vec()];
ssl_config
Expand Down
2 changes: 0 additions & 2 deletions libsignal-service-hyper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,3 @@ pub mod websocket;
pub mod prelude {
pub use crate::push_service::*;
}

// pub mod provisioning;
Loading

0 comments on commit e26dfbe

Please sign in to comment.