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

refactor: use rustls-platform-verifier cert store #1373

Merged
merged 11 commits into from
May 28, 2024
10 changes: 5 additions & 5 deletions client/http-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ publish = true
[dependencies]
async-trait = "0.1"
hyper = { version = "1.3", features = ["client", "http1", "http2"] }
hyper-rustls = { version = "0.27.1", optional = true, default-features = false, features = ["http1", "http2", "tls12", "logging"] }
hyper-rustls = { version = "0.27.1", optional = true, default-features = false, features = ["http1", "http2", "tls12", "logging", "rustls-platform-verifier", "ring"] }
rustls-platform-verifier = { version = "0.3", optional = true }
hyper-util = { version = "0.1.1", features = ["client", "client-legacy"] }
http-body = "1"
jsonrpsee-types = { workspace = true }
jsonrpsee-core = { workspace = true, features = ["client", "http-helpers"] }
rustls = { version = "0.23.7", default-features = false, optional = true }
serde = { version = "1.0", default-features = false, features = ["derive"] }
serde_json = "1"
thiserror = "1"
Expand All @@ -35,13 +37,11 @@ jsonrpsee-test-utils = { path = "../../test-utils" }
tokio = { version = "1.16", features = ["net", "rt-multi-thread", "macros"] }

[features]
default = ["native-tls"]
native-tls = ["hyper-rustls/native-tokio", "hyper-rustls/ring", "__tls"]
webpki-tls = ["hyper-rustls/webpki-tokio", "hyper-rustls/ring", "__tls"]
default = ["tls"]

# Internal feature to indicate whether TLS is enabled.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Not internal any more then? :)

Copy link
Member Author

Choose a reason for hiding this comment

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

We had two feature flags for tls (native-tls, webpki-tls) before which was public but we don't need them anymore because we only support rustls-platform-verifier and the internal feature flag is not needed anymore

Copy link
Member Author

Choose a reason for hiding this comment

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

ah ok, I guess you were referring to the outdated comment, removed now

# Does nothing on its own.
__tls = ["hyper-rustls"]
tls = ["hyper-rustls", "rustls", "rustls-platform-verifier"]

[package.metadata.docs.rs]
all-features = true
Expand Down
89 changes: 73 additions & 16 deletions client/http-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ use async_trait::async_trait;
use hyper::body::Bytes;
use hyper::http::HeaderMap;
use jsonrpsee_core::client::{
generate_batch_id_range, BatchResponse, CertificateStore, ClientT, Error, IdKind, RequestIdManager, Subscription,
SubscriptionClientT,
generate_batch_id_range, BatchResponse, ClientT, Error, IdKind, RequestIdManager, Subscription, SubscriptionClientT,
};
use jsonrpsee_core::params::BatchRequestBuilder;
use jsonrpsee_core::traits::ToRpcParams;
Expand All @@ -48,6 +47,9 @@ use tower::layer::util::Identity;
use tower::{Layer, Service};
use tracing::instrument;

#[cfg(feature = "tls")]
use crate::{CertificateStore, TlsConfig};

/// HTTP client builder.
///
/// # Examples
Expand Down Expand Up @@ -77,6 +79,7 @@ pub struct HttpClientBuilder<L = Identity> {
max_response_size: u32,
request_timeout: Duration,
max_concurrent_requests: usize,
#[cfg(feature = "tls")]
certificate_store: CertificateStore,
id_kind: IdKind,
max_log_length: u32,
Expand Down Expand Up @@ -110,31 +113,85 @@ impl<L> HttpClientBuilder<L> {
self
}

/// Force to use the rustls native certificate store.
/// Force to use rustls-platform-verifier to select which certificate store to use.
///
///
/// Since multiple certificate stores can be optionally enabled, this option will
/// force the `native certificate store` to be used.
/// This is enabled with the default settings and features.
///
/// # Optional
///
/// This requires the optional `native-tls` feature.
#[cfg(feature = "native-tls")]
pub fn use_native_rustls(mut self) -> Self {
/// This requires the optional `tls` feature.
#[cfg(feature = "tls")]
pub fn with_rustls_platform_verifier(mut self) -> Self {
self.certificate_store = CertificateStore::Native;
self
}

/// Force to use the rustls webpki certificate store.
///
/// Since multiple certificate stores can be optionally enabled, this option will
/// force the `webpki certificate store` to be used.
/// Force to use a custom certificate store.
///
/// # Optional
///
/// This requires the optional `webpki-tls` feature.
#[cfg(feature = "webpki-tls")]
pub fn use_webpki_rustls(mut self) -> Self {
self.certificate_store = CertificateStore::WebPki;
/// This requires the optional `tls` feature.
///
/// # Example
///
/// ```no_run
/// use jsonrpsee_ws_client::WsClientBuilder;
/// use rustls::{
/// client::danger::{self, HandshakeSignatureValid, ServerCertVerified},
/// pki_types::{CertificateDer, ServerName, UnixTime},
/// Error,
/// };
///
/// #[derive(Debug)]
/// struct NoCertificateVerification;
///
/// impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
/// fn verify_server_cert(
/// &self,
/// _: &CertificateDer<'_>,
/// _: &[CertificateDer<'_>],
/// _: &ServerName<'_>,
/// _: &[u8],
/// _: UnixTime,
/// ) -> Result<ServerCertVerified, Error> {
/// Ok(ServerCertVerified::assertion())
/// }
///
/// fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
/// vec![rustls::SignatureScheme::ECDSA_NISTP256_SHA256]
/// }
///
/// fn verify_tls12_signature(
/// &self,
/// _: &[u8],
/// _: &CertificateDer<'_>,
/// _: &rustls::DigitallySignedStruct,
/// ) -> Result<rustls::client::danger::HandshakeSignatureValid, Error> {
/// Ok(HandshakeSignatureValid::assertion())
/// }
///
/// fn verify_tls13_signature(
/// &self,
/// _: &[u8],
/// _: &CertificateDer<'_>,
/// _: &rustls::DigitallySignedStruct,
/// ) -> Result<HandshakeSignatureValid, Error> {
/// Ok(HandshakeSignatureValid::assertion())
/// }
/// }
///
/// let tls_cfg = rustls::ClientConfig::builder()
/// .dangerous()
/// .with_custom_certificate_verifier(std::sync::Arc::new(NoCertificateVerification))
/// .with_no_client_auth();
///
/// // client builder with disabled certificate verification.
/// let client_builder = WsClientBuilder::default().with_tls_config(tls_cfg);
/// ```
#[cfg(feature = "tls")]
pub fn with_tls_config(mut self, cfg: TlsConfig) -> Self {
self.certificate_store = CertificateStore::Custom(cfg);
self
}

Expand Down
11 changes: 11 additions & 0 deletions client/http-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,14 @@ pub type HttpBody = jsonrpsee_core::http_helpers::Body;
pub type HttpRequest<T = HttpBody> = jsonrpsee_core::http_helpers::Request<T>;
/// HTTP response with default body.
pub type HttpResponse<T = HttpBody> = jsonrpsee_core::http_helpers::Response<T>;

/// Custom TLS configuration.
#[cfg(feature = "tls")]
pub type TlsConfig = rustls::ClientConfig;

#[cfg(feature = "tls")]
#[derive(Debug)]
pub(crate) enum CertificateStore {
Native,
Custom(TlsConfig),
}
41 changes: 21 additions & 20 deletions client/http-client/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use hyper::http::{HeaderMap, HeaderValue};
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use jsonrpsee_core::client::CertificateStore;
use jsonrpsee_core::tracing::client::{rx_log_from_bytes, tx_log_from_str};
use jsonrpsee_core::BoxError;
use jsonrpsee_core::{
Expand All @@ -28,13 +27,16 @@ use url::Url;

use crate::{HttpBody, HttpRequest, HttpResponse};

#[cfg(feature = "tls")]
use crate::CertificateStore;

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

/// Wrapper over HTTP transport and connector.
#[derive(Debug)]
pub enum HttpBackend<B = HttpBody> {
/// Hyper client with https connector.
#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
Https(Client<hyper_rustls::HttpsConnector<HttpConnector>, B>),
/// Hyper client with http connector.
Http(Client<HttpConnector, B>),
Expand All @@ -44,7 +46,7 @@ impl<B> Clone for HttpBackend<B> {
fn clone(&self) -> Self {
match self {
Self::Http(inner) => Self::Http(inner.clone()),
#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
Self::Https(inner) => Self::Https(inner.clone()),
}
}
Expand All @@ -63,7 +65,7 @@ where
fn poll_ready(&mut self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self {
Self::Http(inner) => inner.poll_ready(ctx),
#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
Self::Https(inner) => inner.poll_ready(ctx),
}
.map_err(|e| Error::Http(HttpError::Stream(e.into())))
Expand All @@ -72,7 +74,7 @@ where
fn call(&mut self, req: HttpRequest<B>) -> Self::Future {
let resp = match self {
Self::Http(inner) => inner.call(req),
#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
Self::Https(inner) => inner.call(req),
};

Expand Down Expand Up @@ -124,7 +126,8 @@ impl HttpTransportClientBuilder<Identity> {

impl<L> HttpTransportClientBuilder<L> {
/// Set the certificate store.
pub fn set_certification_store(mut self, cert_store: CertificateStore) -> Self {
#[cfg(feature = "tls")]
pub(crate) fn set_certification_store(mut self, cert_store: CertificateStore) -> Self {
self.certificate_store = cert_store;
self
}
Expand Down Expand Up @@ -208,33 +211,31 @@ impl<L> HttpTransportClientBuilder<L> {
connector.set_nodelay(tcp_no_delay);
HttpBackend::Http(Client::builder(TokioExecutor::new()).build(connector))
}
#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
"https" => {
let mut http_conn = HttpConnector::new();
http_conn.set_nodelay(tcp_no_delay);
http_conn.enforce_http(false);

let https_conn = match certificate_store {
#[cfg(feature = "native-tls")]
CertificateStore::Native => hyper_rustls::HttpsConnectorBuilder::new()
.with_native_roots()
.map(|c| c.https_or_http().enable_all_versions().wrap_connector(http_conn))
.map_err(|_| Error::InvalidCertficateStore)?,
#[cfg(feature = "webpki-tls")]
CertificateStore::WebPki => hyper_rustls::HttpsConnectorBuilder::new()
.with_webpki_roots()
.with_platform_verifier()
.https_or_http()
.enable_all_versions()
.wrap_connector(http_conn),
CertificateStore::Custom(tls_config) => hyper_rustls::HttpsConnectorBuilder::new()
.with_tls_config(tls_config)
.https_or_http()
.enable_all_versions()
.wrap_connector(http_conn),
_ => return Err(Error::InvalidCertficateStore),
};

HttpBackend::Https(Client::builder(TokioExecutor::new()).build(https_conn))
}
_ => {
#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
let err = "URL scheme not supported, expects 'http' or 'https'";
#[cfg(not(feature = "__tls"))]
#[cfg(not(feature = "tls"))]
let err = "URL scheme not supported, expects 'http'";
return Err(Error::Url(err.into()));
}
Expand Down Expand Up @@ -368,14 +369,14 @@ mod tests {
assert!(matches!(err, Error::Url(_)));
}

#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
#[test]
fn https_works() {
let client = HttpTransportClientBuilder::new().build("https://localhost").unwrap();
assert_eq!(&client.target, "https://localhost/");
}

#[cfg(not(feature = "__tls"))]
#[cfg(not(feature = "tls"))]
#[test]
fn https_fails_without_tls_feature() {
let err = HttpTransportClientBuilder::new().build("https://localhost").unwrap_err();
Expand Down Expand Up @@ -415,7 +416,7 @@ mod tests {
assert_eq!(&client.target, "http://127.0.0.1/");
}

#[cfg(feature = "__tls")]
#[cfg(feature = "tls")]
#[test]
fn https_custom_port_works() {
let client = HttpTransportClientBuilder::new().build("https://localhost:9999").unwrap();
Expand Down
11 changes: 3 additions & 8 deletions client/transport/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ pin-project = { version = "1", optional = true }
url = { version = "2.4.0", optional = true }

# tls
rustls-native-certs = { version = "0.7", optional = true }
webpki-roots = { version = "0.26", optional = true }
tokio-rustls = { version = "0.26", default-features = false, optional = true, features = ["logging", "tls12", "ring"] }
rustls-pki-types = { version = "1", optional = true }
rustls-platform-verifier = { version = "0.3.1", optional = true }
rustls = { version = "0.23", default-features = false, optional = true }

# ws
soketto = { version = "0.8", optional = true }
Expand All @@ -40,12 +40,7 @@ soketto = { version = "0.8", optional = true }
gloo-net = { version = "0.5.0", default-features = false, features = ["json", "websocket"], optional = true }

[features]
native-tls = ["rustls-native-certs", "__tls"]
webpki-tls = ["webpki-roots", "__tls"]

# Internal feature to indicate whether TLS is enabled.
# Does nothing on its own.
__tls = ["tokio-rustls", "rustls-pki-types"]
tls = ["tokio-rustls", "rustls-pki-types", "rustls-platform-verifier", "rustls"]

ws = [
"futures-util",
Expand Down
Loading
Loading