1use crate::BatchRequestConfig;
22use std::{
23 error::Error as StdError,
24 net::{IpAddr, SocketAddr},
25 num::NonZeroU32,
26 str::FromStr,
27};
28
29use forwarded_header_value::ForwardedHeaderValue;
30use http::header::{HeaderName, HeaderValue};
31use ip_network::IpNetwork;
32use jsonrpsee::{server::middleware::http::HostFilterLayer, RpcModule};
33use sc_rpc_api::DenyUnsafe;
34use tower_http::cors::{AllowOrigin, CorsLayer};
35
36const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
37const X_REAL_IP: HeaderName = HeaderName::from_static("x-real-ip");
38const FORWARDED: HeaderName = HeaderName::from_static("forwarded");
39
40#[derive(Debug)]
41pub(crate) struct ListenAddrError;
42
43impl std::error::Error for ListenAddrError {}
44
45impl std::fmt::Display for ListenAddrError {
46 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
47 write!(f, "No listen address was successfully bound")
48 }
49}
50
51#[derive(Debug, Copy, Clone)]
53pub enum RpcMethods {
54 Safe,
56 Unsafe,
58 Auto,
60}
61
62impl Default for RpcMethods {
63 fn default() -> Self {
64 RpcMethods::Auto
65 }
66}
67
68impl FromStr for RpcMethods {
69 type Err = String;
70
71 fn from_str(s: &str) -> Result<Self, Self::Err> {
72 match s {
73 "safe" => Ok(RpcMethods::Safe),
74 "unsafe" => Ok(RpcMethods::Unsafe),
75 "auto" => Ok(RpcMethods::Auto),
76 invalid => Err(format!("Invalid rpc methods {invalid}")),
77 }
78 }
79}
80
81#[derive(Debug, Clone)]
82pub(crate) struct RpcSettings {
83 pub(crate) batch_config: BatchRequestConfig,
84 pub(crate) max_connections: u32,
85 pub(crate) max_payload_in_mb: u32,
86 pub(crate) max_payload_out_mb: u32,
87 pub(crate) max_subscriptions_per_connection: u32,
88 pub(crate) max_buffer_capacity_per_connection: u32,
89 pub(crate) rpc_methods: RpcMethods,
90 pub(crate) rate_limit: Option<NonZeroU32>,
91 pub(crate) rate_limit_trust_proxy_headers: bool,
92 pub(crate) rate_limit_whitelisted_ips: Vec<IpNetwork>,
93 pub(crate) cors: CorsLayer,
94 pub(crate) host_filter: Option<HostFilterLayer>,
95}
96
97#[derive(Debug, Clone)]
99pub struct RpcEndpoint {
100 pub listen_addr: SocketAddr,
102 pub batch_config: BatchRequestConfig,
104 pub max_connections: u32,
106 pub max_payload_in_mb: u32,
108 pub max_payload_out_mb: u32,
110 pub max_subscriptions_per_connection: u32,
112 pub max_buffer_capacity_per_connection: u32,
114 pub rate_limit: Option<NonZeroU32>,
116 pub rate_limit_trust_proxy_headers: bool,
118 pub rate_limit_whitelisted_ips: Vec<IpNetwork>,
120 pub cors: Option<Vec<String>>,
122 pub rpc_methods: RpcMethods,
124 pub is_optional: bool,
128 pub retry_random_port: bool,
130}
131
132impl RpcEndpoint {
133 pub(crate) async fn bind(self) -> Result<Listener, Box<dyn StdError + Send + Sync>> {
135 let listener = match tokio::net::TcpListener::bind(self.listen_addr).await {
136 Ok(listener) => listener,
137 Err(_) if self.retry_random_port => {
138 let mut addr = self.listen_addr;
139 addr.set_port(0);
140
141 tokio::net::TcpListener::bind(addr).await?
142 },
143 Err(e) => return Err(e.into()),
144 };
145 let local_addr = listener.local_addr()?;
146 let host_filter = host_filtering(self.cors.is_some(), local_addr);
147 let cors = try_into_cors(self.cors)?;
148
149 Ok(Listener {
150 listener,
151 local_addr,
152 cfg: RpcSettings {
153 batch_config: self.batch_config,
154 max_connections: self.max_connections,
155 max_payload_in_mb: self.max_payload_in_mb,
156 max_payload_out_mb: self.max_payload_out_mb,
157 max_subscriptions_per_connection: self.max_subscriptions_per_connection,
158 max_buffer_capacity_per_connection: self.max_buffer_capacity_per_connection,
159 rpc_methods: self.rpc_methods,
160 rate_limit: self.rate_limit,
161 rate_limit_trust_proxy_headers: self.rate_limit_trust_proxy_headers,
162 rate_limit_whitelisted_ips: self.rate_limit_whitelisted_ips,
163 host_filter,
164 cors,
165 },
166 })
167 }
168}
169
170pub(crate) struct Listener {
172 listener: tokio::net::TcpListener,
173 local_addr: SocketAddr,
174 cfg: RpcSettings,
175}
176
177impl Listener {
178 pub(crate) async fn accept(&mut self) -> std::io::Result<(tokio::net::TcpStream, SocketAddr)> {
180 let (sock, remote_addr) = self.listener.accept().await?;
181 Ok((sock, remote_addr))
182 }
183
184 pub fn local_addr(&self) -> SocketAddr {
186 self.local_addr
187 }
188
189 pub fn rpc_settings(&self) -> RpcSettings {
190 self.cfg.clone()
191 }
192}
193
194pub(crate) fn host_filtering(enabled: bool, addr: SocketAddr) -> Option<HostFilterLayer> {
195 if enabled {
196 let hosts = [
199 format!("localhost:{}", addr.port()),
200 format!("127.0.0.1:{}", addr.port()),
201 format!("[::1]:{}", addr.port()),
202 ];
203
204 Some(HostFilterLayer::new(hosts).expect("Valid hosts; qed"))
205 } else {
206 None
207 }
208}
209
210pub(crate) fn build_rpc_api<M: Send + Sync + 'static>(mut rpc_api: RpcModule<M>) -> RpcModule<M> {
211 let mut available_methods = rpc_api.method_names().collect::<Vec<_>>();
212 available_methods.push("rpc_methods");
214 available_methods.sort();
215
216 rpc_api
217 .register_method("rpc_methods", move |_, _, _| {
218 serde_json::json!({
219 "methods": available_methods,
220 })
221 })
222 .expect("infallible all other methods have their own address space; qed");
223
224 rpc_api
225}
226
227pub(crate) fn try_into_cors(
228 maybe_cors: Option<Vec<String>>,
229) -> Result<CorsLayer, Box<dyn StdError + Send + Sync>> {
230 if let Some(cors) = maybe_cors {
231 let mut list = Vec::new();
232
233 for origin in cors {
234 list.push(HeaderValue::from_str(&origin)?)
235 }
236
237 Ok(CorsLayer::new().allow_origin(AllowOrigin::list(list)))
238 } else {
239 Ok(CorsLayer::permissive())
241 }
242}
243
244pub(crate) fn get_proxy_ip<B>(req: &http::Request<B>) -> Option<IpAddr> {
251 if let Some(ip) = req
252 .headers()
253 .get(&FORWARDED)
254 .and_then(|v| v.to_str().ok())
255 .and_then(|v| ForwardedHeaderValue::from_forwarded(v).ok())
256 .and_then(|v| v.remotest_forwarded_for_ip())
257 {
258 return Some(ip);
259 }
260
261 if let Some(ip) = req
262 .headers()
263 .get(&X_FORWARDED_FOR)
264 .and_then(|v| v.to_str().ok())
265 .and_then(|v| ForwardedHeaderValue::from_x_forwarded_for(v).ok())
266 .and_then(|v| v.remotest_forwarded_for_ip())
267 {
268 return Some(ip);
269 }
270
271 if let Some(ip) = req
272 .headers()
273 .get(&X_REAL_IP)
274 .and_then(|v| v.to_str().ok())
275 .and_then(|v| IpAddr::from_str(v).ok())
276 {
277 return Some(ip);
278 }
279
280 None
281}
282
283pub fn deny_unsafe(addr: &SocketAddr, methods: &RpcMethods) -> DenyUnsafe {
285 match (addr.ip().is_loopback(), methods) {
286 (_, RpcMethods::Unsafe) | (true, RpcMethods::Auto) => DenyUnsafe::No,
287 _ => DenyUnsafe::Yes,
288 }
289}
290
291pub(crate) fn format_listen_addrs(addr: &[SocketAddr]) -> String {
292 let mut s = String::new();
293
294 let mut it = addr.iter().peekable();
295
296 while let Some(addr) = it.next() {
297 s.push_str(&addr.to_string());
298
299 if it.peek().is_some() {
300 s.push(',');
301 }
302 }
303
304 if addr.len() == 1 {
305 s.push(',');
306 }
307
308 s
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use hyper::header::HeaderValue;
315 use jsonrpsee::server::{HttpBody, HttpRequest};
316
317 fn request() -> http::Request<HttpBody> {
318 HttpRequest::builder().body(HttpBody::empty()).unwrap()
319 }
320
321 #[test]
322 fn empty_works() {
323 let req = request();
324 let host = get_proxy_ip(&req);
325 assert!(host.is_none())
326 }
327
328 #[test]
329 fn host_from_x_real_ip() {
330 let mut req = request();
331
332 req.headers_mut().insert(&X_REAL_IP, HeaderValue::from_static("127.0.0.1"));
333 let ip = get_proxy_ip(&req);
334 assert_eq!(Some(IpAddr::from_str("127.0.0.1").unwrap()), ip);
335 }
336
337 #[test]
338 fn ip_from_forwarded_works() {
339 let mut req = request();
340
341 req.headers_mut().insert(
342 &FORWARDED,
343 HeaderValue::from_static("for=192.0.2.60;proto=http;by=203.0.113.43;host=example.com"),
344 );
345 let ip = get_proxy_ip(&req);
346 assert_eq!(Some(IpAddr::from_str("192.0.2.60").unwrap()), ip);
347 }
348
349 #[test]
350 fn ip_from_forwarded_multiple() {
351 let mut req = request();
352
353 req.headers_mut().append(&FORWARDED, HeaderValue::from_static("for=127.0.0.1"));
354 req.headers_mut().append(&FORWARDED, HeaderValue::from_static("for=192.0.2.60"));
355 req.headers_mut().append(&FORWARDED, HeaderValue::from_static("for=192.0.2.61"));
356 let ip = get_proxy_ip(&req);
357 assert_eq!(Some(IpAddr::from_str("127.0.0.1").unwrap()), ip);
358 }
359
360 #[test]
361 fn ip_from_x_forwarded_works() {
362 let mut req = request();
363
364 req.headers_mut()
365 .insert(&X_FORWARDED_FOR, HeaderValue::from_static("127.0.0.1,192.0.2.60,0.0.0.1"));
366 let ip = get_proxy_ip(&req);
367 assert_eq!(Some(IpAddr::from_str("127.0.0.1").unwrap()), ip);
368 }
369}