Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clients: feature gate tls #545

Merged
merged 6 commits into from
Dec 6, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion http-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ documentation = "https://docs.rs/jsonrpsee-http-client"

[dependencies]
async-trait = "0.1"
hyper-rustls = "0.22"
hyper-rustls = { version = "0.22", optional = true }
hyper = { version = "0.14.10", features = ["client", "http1", "http2", "tcp"] }
jsonrpsee-types = { path = "../types", version = "0.4.1" }
jsonrpsee-utils = { path = "../utils", version = "0.4.1", features = ["http-helpers"] }
Expand All @@ -26,3 +26,7 @@ fnv = "1"
[dev-dependencies]
jsonrpsee-test-utils = { path = "../test-utils" }
tokio = { package = "tokio", version = "1", features = ["net", "rt-multi-thread", "macros"] }

[features]
default = ["tls"]
tls = ["hyper-rustls"]
50 changes: 41 additions & 9 deletions http-client/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,37 @@

use crate::types::error::GenericTransportError;
use hyper::client::{Client, HttpConnector};
use hyper_rustls::HttpsConnector;
use jsonrpsee_utils::http_helpers;
use thiserror::Error;

const CONTENT_TYPE_JSON: &str = "application/json";

#[derive(Debug, Clone)]
enum HyperClient {
/// Hyper client with https connector.
#[cfg(feature = "tls")]
Https(Client<hyper_rustls::HttpsConnector<HttpConnector>>),
/// Hyper client with http connector.
Http(Client<HttpConnector>),
}

impl HyperClient {
fn request(&self, req: hyper::Request<hyper::Body>) -> hyper::client::ResponseFuture {
match self {
Self::Http(client) => client.request(req),
#[cfg(feature = "tls")]
Self::Https(client) => client.request(req),
}
}
}

/// HTTP Transport Client.
#[derive(Debug, Clone)]
pub(crate) struct HttpTransportClient {
/// Target to connect to.
target: url::Url,
/// HTTP client
client: Client<HttpsConnector<HttpConnector>>,
client: HyperClient,
/// Configurable max request body size
max_request_body_size: u32,
}
Expand All @@ -29,13 +47,27 @@ impl HttpTransportClient {
/// Initializes a new HTTP client.
pub(crate) fn new(target: impl AsRef<str>, max_request_body_size: u32) -> Result<Self, Error> {
let target = url::Url::parse(target.as_ref()).map_err(|e| Error::Url(format!("Invalid URL: {}", e)))?;
if target.scheme() == "http" || target.scheme() == "https" {
let connector = HttpsConnector::with_native_roots();
let client = Client::builder().build::<_, hyper::Body>(connector);
Ok(HttpTransportClient { target, client, max_request_body_size })
} else {
Err(Error::Url("URL scheme not supported, expects 'http' or 'https'".into()))
}
let client = match target.scheme() {
"http" => {
let connector = HttpConnector::new();
let client = Client::builder().build::<_, hyper::Body>(connector);
HyperClient::Http(client)
}
#[cfg(feature = "tls")]
"https" => {
let connector = hyper_rustls::HttpsConnector::with_native_roots();
let client = Client::builder().build::<_, hyper::Body>(connector);
HyperClient::Https(client)
}
_ => {
#[cfg(feature = "tls")]
let err = "URL scheme not supported, expects 'http' or 'https'";
#[cfg(not(feature = "tls"))]
let err = "URL scheme not supported, expects 'http'";
return Err(Error::Url(err.into()));
}
};
Ok(Self { target, client, max_request_body_size })
}

async fn inner_send(&self, body: String) -> Result<hyper::Response<hyper::Body>, Error> {
Expand Down
2 changes: 1 addition & 1 deletion tests/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ async fn https_works() {
#[tokio::test]
#[ignore]
async fn wss_works() {
let client = WsClientBuilder::default().build("wss://kusama-rpc.polkadot.io").await.unwrap();
let client = WsClientBuilder::default().build("wss://kusama-rpc.polkadot.io:443").await.unwrap();
niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
let response: String = client.request("system_chain", None).await.unwrap();
assert_eq!(&response, "Kusama");
}
Expand Down
9 changes: 7 additions & 2 deletions ws-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ documentation = "https://docs.rs/jsonrpsee-ws-client"

[dependencies]
tokio = { version = "1", features = ["net", "time", "rt-multi-thread", "macros"] }
tokio-rustls = "0.22"
tokio-rustls = { version = "0.22", optional = true }
tokio-util = { version = "0.6", features = ["compat"] }

async-trait = "0.1"
Expand All @@ -26,9 +26,14 @@ serde_json = "1"
soketto = "0.7"
thiserror = "1"
tracing = "0.1"
webpki-roots = "0.21"

[dev-dependencies]
env_logger = "0.9"
jsonrpsee-test-utils = { path = "../test-utils" }
jsonrpsee-utils = { path = "../utils" }
tokio = { version = "1", features = ["macros"] }
tokio = { version = "1", features = ["macros"] }

[features]
default = ["tls"]
tls = ["tokio-rustls"]
28 changes: 14 additions & 14 deletions ws-client/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,30 +32,29 @@ use futures::{
};
use pin_project::pin_project;
use std::{io::Error as IoError, pin::Pin, task::Context, task::Poll};
use tokio::net::TcpStream;
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};

/// Stream to represent either a unencrypted or encrypted socket stream.
#[pin_project(project = EitherStreamProj)]
#[derive(Debug, Copy, Clone)]
pub enum EitherStream<S, T> {
#[derive(Debug)]
pub enum EitherStream {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did this but I realized I can just used placeholder type such as () to keep the generics here not sure that we need the generics anyway.

Unless we plan to support any transport using tokio rustls :)

/// Unencrypted socket stream.
Plain(#[pin] S),
Plain(#[pin] TcpStream),
/// Encrypted socket stream.
Tls(#[pin] T),
#[cfg(feature = "tls")]
Tls(#[pin] tokio_rustls::client::TlsStream<TcpStream>),
}

impl<S, T> AsyncRead for EitherStream<S, T>
where
S: TokioAsyncReadCompatExt,
T: TokioAsyncReadCompatExt,
{
impl AsyncRead for EitherStream {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<Result<usize, IoError>> {
match self.project() {
EitherStreamProj::Plain(s) => {
let compat = s.compat();
futures::pin_mut!(compat);
AsyncRead::poll_read(compat, cx, buf)
}
#[cfg(feature = "tls")]
EitherStreamProj::Tls(t) => {
let compat = t.compat();
futures::pin_mut!(compat);
Expand All @@ -75,6 +74,7 @@ where
futures::pin_mut!(compat);
AsyncRead::poll_read_vectored(compat, cx, bufs)
}
#[cfg(feature = "tls")]
EitherStreamProj::Tls(t) => {
let compat = t.compat();
futures::pin_mut!(compat);
Expand All @@ -84,18 +84,15 @@ where
}
}

impl<S, T> AsyncWrite for EitherStream<S, T>
where
S: TokioAsyncWriteCompatExt,
T: TokioAsyncWriteCompatExt,
{
impl AsyncWrite for EitherStream {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, IoError>> {
match self.project() {
EitherStreamProj::Plain(s) => {
let compat = s.compat_write();
futures::pin_mut!(compat);
AsyncWrite::poll_write(compat, cx, buf)
}
#[cfg(feature = "tls")]
EitherStreamProj::Tls(t) => {
let compat = t.compat_write();
futures::pin_mut!(compat);
Expand All @@ -111,6 +108,7 @@ where
futures::pin_mut!(compat);
AsyncWrite::poll_write_vectored(compat, cx, bufs)
}
#[cfg(feature = "tls")]
EitherStreamProj::Tls(t) => {
let compat = t.compat_write();
futures::pin_mut!(compat);
Expand All @@ -126,6 +124,7 @@ where
futures::pin_mut!(compat);
AsyncWrite::poll_flush(compat, cx)
}
#[cfg(feature = "tls")]
EitherStreamProj::Tls(t) => {
let compat = t.compat_write();
futures::pin_mut!(compat);
Expand All @@ -141,6 +140,7 @@ where
futures::pin_mut!(compat);
AsyncWrite::poll_close(compat, cx)
}
#[cfg(feature = "tls")]
EitherStreamProj::Tls(t) => {
let compat = t.compat_write();
futures::pin_mut!(compat);
Expand Down
Loading