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
13 changes: 6 additions & 7 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,10 @@ 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.
# 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
105 changes: 78 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, CustomCertStore};

/// 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 @@ -111,24 +114,67 @@ impl<L> HttpClientBuilder<L> {
///
/// # Optional
///
/// This requires the optional `native-tls` feature.
#[cfg(feature = "native-tls")]
pub fn use_native_rustls(mut self) -> Self {
self.certificate_store = CertificateStore::Native;
self
}

/// Force to use the rustls webpki certificate store.
/// This requires the optional `tls` feature.
///
/// Since multiple certificate stores can be optionally enabled, this option will
/// force the `webpki certificate store` to be used.
/// # Example
///
/// # Optional
/// ```no_run
/// use jsonrpsee_http_client::{HttpClientBuilder, CustomCertStore};
/// 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())
/// }
///
/// This requires the optional `webpki-tls` feature.
#[cfg(feature = "webpki-tls")]
pub fn use_webpki_rustls(mut self) -> Self {
self.certificate_store = CertificateStore::WebPki;
/// fn verify_tls13_signature(
/// &self,
/// _: &[u8],
/// _: &CertificateDer<'_>,
/// _: &rustls::DigitallySignedStruct,
/// ) -> Result<HandshakeSignatureValid, Error> {
/// Ok(HandshakeSignatureValid::assertion())
/// }
/// }
///
/// let tls_cfg = CustomCertStore::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_custom_cert_store(tls_cfg);
/// ```
#[cfg(feature = "tls")]
pub fn with_custom_cert_store(mut self, cfg: CustomCertStore) -> Self {
self.certificate_store = CertificateStore::Custom(cfg);
self
}

Expand Down Expand Up @@ -165,6 +211,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 @@ -193,6 +240,7 @@ where
max_request_size,
max_response_size,
request_timeout,
#[cfg(feature = "tls")]
certificate_store,
id_kind,
headers,
Expand All @@ -202,16 +250,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, id_manager: Arc::new(RequestIdManager::new(id_kind)), request_timeout })
}
Expand All @@ -224,6 +274,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 CustomCertStore = rustls::ClientConfig;

#[cfg(feature = "tls")]
#[derive(Debug)]
pub(crate) enum CertificateStore {
Native,
Custom(CustomCertStore),
}
Loading
Loading