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
12 changes: 6 additions & 6 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-util = { version = "0.1.1", features = ["client", "client-legacy"] }
hyper-rustls = { version = "0.27.1", default-features = false, features = ["http1", "http2", "tls12", "logging", "ring"], optional = true }
hyper-util = { version = "0.1.1", features = ["client", "client-legacy", "tokio", "http1", "http2"] }
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, features = ["logging", "std", "tls12", "ring"] }
rustls-platform-verifier = { version = "0.3", 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

niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
# Does nothing on its own.
niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
__tls = ["hyper-rustls"]
tls = ["hyper-rustls", "rustls", "rustls-platform-verifier"]

[package.metadata.docs.rs]
all-features = true
Expand Down
115 changes: 88 additions & 27 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,84 @@ impl<L> HttpClientBuilder<L> {
self
}

/// Force to use the rustls native certificate store.
///
/// Since multiple certificate stores can be optionally enabled, this option will
/// force the `native certificate store` to be used.
/// Force to use rustls-platform-verifier as certification store.
/// If you want to use a custom certificate store, use [`HttpClientBuilder::with_tls_config`] instead.
/// 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 {
niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
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_http_client::HttpClientBuilder;
/// 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 = HttpClientBuilder::new().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 Expand Up @@ -171,6 +227,7 @@ impl<L> HttpClientBuilder<L> {
/// Set custom tower middleware.
pub fn set_http_middleware<T>(self, service_builder: tower::ServiceBuilder<T>) -> HttpClientBuilder<T> {
HttpClientBuilder {
#[cfg(feature = "tls")]
certificate_store: self.certificate_store,
id_kind: self.id_kind,
headers: self.headers,
Expand Down Expand Up @@ -200,6 +257,7 @@ where
max_response_size,
max_concurrent_requests,
request_timeout,
#[cfg(feature = "tls")]
certificate_store,
id_kind,
headers,
Expand All @@ -209,16 +267,18 @@ where
..
} = self;

let transport = HttpTransportClientBuilder::new()
.max_request_size(max_request_size)
.max_response_size(max_response_size)
.set_headers(headers)
.set_tcp_no_delay(tcp_no_delay)
.set_max_logging_length(max_log_length)
.set_service(service_builder)
.set_certification_store(certificate_store)
.build(target)
.map_err(|e| Error::Transport(e.into()))?;
let transport = HttpTransportClientBuilder {
max_request_size,
max_response_size,
headers,
max_log_length,
tcp_no_delay,
service_builder,
#[cfg(feature = "tls")]
certificate_store,
}
.build(target)
.map_err(|e| Error::Transport(e.into()))?;

Ok(HttpClient {
transport,
Expand All @@ -235,6 +295,7 @@ impl Default for HttpClientBuilder<Identity> {
max_response_size: TEN_MB_SIZE_BYTES,
request_timeout: Duration::from_secs(60),
max_concurrent_requests: 256,
#[cfg(feature = "tls")]
certificate_store: CertificateStore::Native,
id_kind: IdKind::Number,
max_log_length: 4096,
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),
}
Loading
Loading