Skip to content

Commit

Permalink
Switch to reqwest and reqwest-websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
gferon committed Oct 17, 2024
1 parent ae55eb8 commit dc8d574
Show file tree
Hide file tree
Showing 15 changed files with 573 additions and 1,050 deletions.
16 changes: 4 additions & 12 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,14 @@ url = { version = "2.1", features = ["serde"] }
uuid = { version = "1", features = ["serde"] }

# http
hyper = "1.0"
hyper-util = { version = "0.1", features = ["client", "client-legacy"] }
hyper-rustls = { version = "0.27", default-features = false, features = ["http1", "http2", "ring", "logging"] }
hyper-timeout = "0.5"
headers = "0.4"
http-body-util = "0.1"
mpart-async = "0.7"
async-tungstenite = { version = "0.27", features = ["tokio-rustls-native-certs", "url"] }
tokio = { version = "1.0", features = ["macros"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "ring"] }

rustls-pemfile = "2.0"
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "rustls-tls-manual-roots", "stream"] }
reqwest-websocket = { version = "0.4.2", features = ["json"] }

tracing = { version = "0.1", features = ["log"] }
tracing-futures = "0.2"

tokio = { version = "1.0", features = ["macros"] }

[build-dependencies]
prost-build = "0.13"

Expand Down
73 changes: 41 additions & 32 deletions src/account_manager.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use base64::prelude::*;
use phonenumber::PhoneNumber;
use reqwest::Method;
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};

Expand Down Expand Up @@ -28,9 +29,9 @@ use crate::proto::sync_message::PniChangeNumber;
use crate::proto::{DeviceName, SyncMessage};
use crate::provisioning::generate_registration_id;
use crate::push_service::{
AvatarWrite, DeviceActivationRequest, DeviceInfo, RecaptchaAttributes,
RegistrationMethod, ServiceIdType, VerifyAccountResponse,
DEFAULT_DEVICE_ID,
AvatarWrite, DeviceActivationRequest, DeviceInfo, HttpAuthOverride,
RecaptchaAttributes, RegistrationMethod, ReqwestExt, ServiceIdType,
VerifyAccountResponse, DEFAULT_DEVICE_ID,
};
use crate::sender::OutgoingPushMessage;
use crate::session_store::SessionStoreExt;
Expand All @@ -44,9 +45,7 @@ use crate::{
profile_name::ProfileName,
proto::{ProvisionEnvelope, ProvisionMessage, ProvisioningVersion},
provisioning::{ProvisioningCipher, ProvisioningError},
push_service::{
AccountAttributes, HttpAuthOverride, PushService, ServiceError,
},
push_service::{AccountAttributes, PushService, ServiceError},
utils::serde_base64,
};

Expand Down Expand Up @@ -224,13 +223,17 @@ impl AccountManager {

let dc: DeviceCode = self
.service
.get_json(
.request(
Method::GET,
Endpoint::Service,
"/v1/devices/provisioning/code",
&[],
HttpAuthOverride::NoOverride,
)
)?
.send_to_signal()
.await?
.json()
.await?;

Ok(dc.verification_code)
}

Expand All @@ -247,16 +250,19 @@ impl AccountManager {
let body = env.encode_to_vec();

self.service
.put_json(
.request(
Method::PUT,
Endpoint::Service,
&format!("/v1/provisioning/{}", destination),

Check warning on line 256 in src/account_manager.rs

View workflow job for this annotation

GitHub Actions / clippy

the borrowed expression implements the required traits

warning: the borrowed expression implements the required traits --> src/account_manager.rs:256:17 | 256 | &format!("/v1/provisioning/{}", destination), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: change this to: `format!("/v1/provisioning/{}", destination)` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrows_for_generic_args = note: `#[warn(clippy::needless_borrows_for_generic_args)]` on by default
&[],
HttpAuthOverride::NoOverride,
&ProvisioningMessage {
body: BASE64_RELAXED.encode(body),
},
)
.await
)?
.json(&ProvisioningMessage {
body: BASE64_RELAXED.encode(body),
})
.send_to_signal()
.await?;

Ok(())
}

/// Link a new device, given a tsurl.
Expand Down Expand Up @@ -582,15 +588,16 @@ impl AccountManager {
}

self.service
.put_json::<(), _>(
.request(
Method::PUT,
Endpoint::Service,
"/v1/accounts/name",
&[],
HttpAuthOverride::NoOverride,
Data {
device_name: encrypted_device_name.encode_to_vec(),
},
)
)?
.json(&Data {
device_name: encrypted_device_name.encode_to_vec(),
})
.send_to_signal()
.await?;

Ok(())
Expand All @@ -607,20 +614,22 @@ impl AccountManager {
token: &str,
captcha: &str,
) -> Result<(), ServiceError> {
let payload = RecaptchaAttributes {
r#type: String::from("recaptcha"),
token: String::from(token),
captcha: String::from(captcha),
};
self.service
.put_json(
.request(
Method::PUT,
Endpoint::Service,
"/v1/challenge",
&[],
HttpAuthOverride::NoOverride,
payload,
)
.await
)?
.json(&RecaptchaAttributes {
r#type: String::from("recaptcha"),
token: String::from(token),
captcha: String::from(captcha),
})
.send_to_signal()
.await?;

Ok(())
}

/// Initialize PNI on linked devices.
Expand Down
18 changes: 12 additions & 6 deletions src/groups_v2/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ use std::{collections::HashMap, convert::TryInto};

use crate::{
configuration::Endpoint,
groups_v2::model::{Group, GroupChanges},
groups_v2::operations::{GroupDecodingError, GroupOperations},
groups_v2::{
model::{Group, GroupChanges},
operations::{GroupDecodingError, GroupOperations},
},
prelude::{PushService, ServiceError},
proto::GroupContextV2,
push_service::{HttpAuth, HttpAuthOverride, ServiceIds},
push_service::{HttpAuth, HttpAuthOverride, ReqwestExt, ServiceIds},
utils::BASE64_RELAXED,
};

Expand All @@ -15,6 +17,7 @@ use bytes::Bytes;
use chrono::{Days, NaiveDate, NaiveTime, Utc};
use futures::AsyncReadExt;
use rand::RngCore;
use reqwest::Method;
use serde::Deserialize;
use zkgroup::{
auth::AuthCredentialWithPniResponse,
Expand Down Expand Up @@ -165,12 +168,15 @@ impl<C: CredentialsCache> GroupsManager<C> {

let credentials_response: CredentialResponse = self
.push_service
.get_json(
.request(
Method::GET,
Endpoint::Service,
&path,
&[],
HttpAuthOverride::NoOverride,
)
)?
.send_to_signal()
.await?
.json()
.await?;
self.credentials_cache
.write(credentials_response.parse()?)?;
Expand Down
27 changes: 0 additions & 27 deletions src/messagepipe.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use bytes::Bytes;
use futures::{
channel::{
mpsc::{self, Sender},
oneshot,
},
prelude::*,
stream::FusedStream,
};

pub use crate::{
Expand All @@ -18,24 +16,12 @@ pub use crate::{

use crate::{push_service::ServiceError, websocket::SignalWebSocket};

pub enum WebSocketStreamItem {
Message(Bytes),
KeepAliveRequest,
}

#[derive(Debug)]
pub enum Incoming {
Envelope(Envelope),
QueueEmpty,
}

#[async_trait::async_trait]
pub trait WebSocketService {
type Stream: FusedStream<Item = WebSocketStreamItem> + Unpin;

async fn send_message(&mut self, msg: Bytes) -> Result<(), ServiceError>;
}

pub struct MessagePipe {
ws: SignalWebSocket,
credentials: ServiceCredentials,
Expand Down Expand Up @@ -133,16 +119,3 @@ impl MessagePipe {
combined.filter_map(|x| async { x })
}
}

/// WebSocketService that panics on every request, mainly for example code.
pub struct PanicingWebSocketService;

#[allow(clippy::diverging_sub_expression)]
#[async_trait::async_trait]
impl WebSocketService for PanicingWebSocketService {
type Stream = futures::channel::mpsc::Receiver<WebSocketStreamItem>;

async fn send_message(&mut self, _msg: Bytes) -> Result<(), ServiceError> {
todo!();
}
}
47 changes: 27 additions & 20 deletions src/push_service/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ use std::fmt;

use chrono::{DateTime, Utc};
use phonenumber::PhoneNumber;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::{HttpAuthOverride, PushService, ServiceError};
use super::{HttpAuthOverride, PushService, ReqwestExt, ServiceError};
use crate::{
configuration::Endpoint,
utils::{serde_optional_base64, serde_phone_number},
Expand Down Expand Up @@ -127,13 +128,17 @@ pub struct WhoAmIResponse {
impl PushService {
/// Method used to check our own UUID
pub async fn whoami(&mut self) -> Result<WhoAmIResponse, ServiceError> {
self.get_json(
self.request(
Method::GET,
Endpoint::Service,
"/v1/accounts/whoami",
&[],
HttpAuthOverride::NoOverride,
)
)?
.send_to_signal()
.await?
.json()
.await
.map_err(Into::into)
}

/// Fetches a list of all devices tied to the authenticated account.
Expand All @@ -146,12 +151,15 @@ impl PushService {
}

let devices: DeviceInfoList = self
.get_json(
.request(
Method::GET,
Endpoint::Service,
"/v1/devices/",
&[],
HttpAuthOverride::NoOverride,
)
)?
.send_to_signal()
.await?
.json()
.await?;

Ok(devices.devices)
Expand All @@ -166,18 +174,17 @@ impl PushService {
"only one of PIN and registration lock can be set."
);

match self
.put_json(
Endpoint::Service,
"/v1/accounts/attributes/",
&[],
HttpAuthOverride::NoOverride,
attributes,
)
.await
{
Err(ServiceError::JsonDecodeError { .. }) => Ok(()),
r => r,
}
self.request(
Method::PUT,
Endpoint::Service,
"/v1/accounts/attributes/",
HttpAuthOverride::NoOverride,
)?
.json(&attributes)
.send_to_signal()
.await?
.json()
.await
.map_err(Into::into)
}
}
Loading

0 comments on commit dc8d574

Please sign in to comment.