-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathtls.rs
More file actions
169 lines (151 loc) · 6.04 KB
/
Copy pathtls.rs
File metadata and controls
169 lines (151 loc) · 6.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//! TLS helpers for serving JSON-RPC over HTTPS.
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{bail, Context};
use jsonrpsee::server::{
serve_with_graceful_shutdown,
stop_channel,
HttpBody,
Methods,
ServerBuilder,
ServerConfig,
ServerHandle,
};
use tokio::net::TcpListener;
use tokio_rustls::rustls::pki_types::pem::PemObject;
use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer};
use tokio_rustls::rustls::ServerConfig as RustlsServerConfig;
use tokio_rustls::TlsAcceptor;
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
use tower_http::cors::CorsLayer;
use tower_http::map_request_body::MapRequestBodyLayer;
use tower_http::map_response_body::MapResponseBodyLayer;
use tracing::warn;
use crate::server::{
HealthLayer,
HttpMetricsLayer,
MetricsLayer,
OhttpJsonrpseeLayer,
RequestLogLayer,
RequestSpanLayer,
};
/// Maximum time allowed for a TLS handshake before the connection is dropped.
const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// Binds an HTTPS JSON-RPC server using the given TLS certificate and key.
///
/// Returns the bound local address and a handle that can be used to await or stop the server.
#[allow(clippy::too_many_arguments)]
pub async fn start_tls_server(
addr: SocketAddr,
cert_path: &Path,
key_path: &Path,
methods: impl Into<Methods>,
max_connections: u32,
max_request_body_size: u32,
cors_layer: Option<CorsLayer>,
ohttp_layer: Option<OhttpJsonrpseeLayer>,
metrics_layer: Option<MetricsLayer>,
) -> anyhow::Result<(SocketAddr, ServerHandle)> {
let tls_acceptor = load_tls_acceptor(cert_path, key_path)?;
let server_config = ServerConfig::builder()
.max_connections(max_connections)
.max_request_body_size(max_request_body_size)
.build();
// See `prover_http_middleware!` for the full layer-order rationale.
let svc_builder = ServerBuilder::default()
.set_config(server_config)
.set_http_middleware(prover_http_middleware!(metrics_layer, cors_layer, ohttp_layer))
.to_service_builder();
let listener = TcpListener::bind(addr)
.await
.context(format!("Failed to bind HTTPS JSON-RPC server to {addr}"))?;
let local_addr =
listener.local_addr().context("Failed to read local address for HTTPS listener")?;
let methods: Methods = methods.into();
let (stop_handle, server_handle) = stop_channel();
tokio::spawn(async move {
loop {
let accept_result = tokio::select! {
accept_result = listener.accept() => accept_result,
_ = stop_handle.clone().shutdown() => break,
};
let (socket, remote_addr) = match accept_result {
Ok(conn) => conn,
Err(err) => {
warn!(error = %err, "Failed to accept incoming TCP connection");
continue;
}
};
let tls_acceptor = tls_acceptor.clone();
let stop_handle = stop_handle.clone();
let methods = methods.clone();
let svc_builder = svc_builder.clone();
tokio::spawn(async move {
let tls_stream =
match tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, tls_acceptor.accept(socket))
.await
{
Ok(Ok(stream)) => stream,
Ok(Err(err)) => {
warn!(
remote_address = %remote_addr,
error = %err,
"TLS handshake failed"
);
return;
}
Err(_) => {
warn!(
remote_address = %remote_addr,
"TLS handshake timed out"
);
return;
}
};
let svc = svc_builder.build(methods, stop_handle.clone());
if let Err(err) =
serve_with_graceful_shutdown(tls_stream, svc, stop_handle.shutdown()).await
{
warn!(
remote_address = %remote_addr,
error = %err,
"HTTPS connection terminated with error"
);
}
});
}
});
Ok((local_addr, server_handle))
}
/// Loads a certificate chain and private key from PEM files and builds a TLS acceptor.
fn load_tls_acceptor(cert_path: &Path, key_path: &Path) -> anyhow::Result<TlsAcceptor> {
let cert_pem = std::fs::read(cert_path)
.with_context(|| format!("Failed to read TLS certificate file: {}", cert_path.display()))?;
let cert_chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(&cert_pem).collect::<Result<Vec<_>, _>>().with_context(
|| format!("Failed to parse TLS certificate PEM chain from {}", cert_path.display()),
)?;
if cert_chain.is_empty() {
bail!(
"TLS certificate file does not contain any certificate PEM blocks: {}",
cert_path.display()
);
}
let key_pem = std::fs::read(key_path)
.with_context(|| format!("Failed to read TLS private key file: {}", key_path.display()))?;
let private_key = PrivateKeyDer::from_pem_slice(&key_pem).with_context(|| {
format!(
"Failed to parse TLS private key PEM from {} (supported: PKCS#1, PKCS#8, SEC1)",
key_path.display()
)
})?;
let mut tls_config = RustlsServerConfig::builder()
.with_no_client_auth()
.with_single_cert(cert_chain, private_key)
.context("Failed to construct TLS server configuration from certificate and key")?;
tls_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(TlsAcceptor::from(Arc::new(tls_config)))
}