Skip to main content

rings_node/
remote_endpoint.rs

1//! Public HTTP(S) JSON-RPC endpoints of remote nodes: the validated form and the client over it.
2//!
3//! [`RemoteRpcEndpoint`] is the proof that a URL passed the endpoint policy — HTTP(S) scheme,
4//! no credentials or fragment, a public host — and every client is built from that proof, so
5//! the policy runs once, where a string enters, and the proof travels as a type.
6
7use std::fmt;
8
9use crate::error::Error;
10use crate::error::Result;
11
12/// A URL that passed the remote RPC endpoint policy.
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub struct RemoteRpcEndpoint(reqwest::Url);
15
16impl RemoteRpcEndpoint {
17    /// Parse `url` as a public HTTP(S) RPC endpoint: no credentials, no fragment, and a host
18    /// the network policy permits.
19    pub fn parse(url: &str) -> Result<Self> {
20        reqwest::Url::parse(url)
21            .map_err(|error| Error::UnsafeRemoteRpcTarget(error.to_string()))
22            .and_then(|parsed| {
23                matches!(parsed.scheme(), "http" | "https")
24                    .then_some(parsed)
25                    .ok_or_else(|| {
26                        Error::UnsafeRemoteRpcTarget(
27                            "only HTTP(S) endpoints are supported".to_string(),
28                        )
29                    })
30            })
31            .and_then(|parsed| {
32                (parsed.username().is_empty()
33                    && parsed.password().is_none()
34                    && parsed.fragment().is_none())
35                .then_some(parsed)
36                .ok_or_else(|| {
37                    Error::UnsafeRemoteRpcTarget(
38                        "credentials and fragments are not permitted in an RPC endpoint URL"
39                            .to_string(),
40                    )
41                })
42            })
43            .and_then(|parsed| {
44                rings_network_policy::validate_public_url_host(&parsed)
45                    .map_err(|error| Error::UnsafeRemoteRpcTarget(error.to_string()))
46                    .map(|()| Self(parsed))
47            })
48    }
49
50    /// The endpoint as a URL string.
51    pub fn as_str(&self) -> &str {
52        self.0.as_str()
53    }
54}
55
56impl fmt::Display for RemoteRpcEndpoint {
57    /// Render the endpoint as its URL.
58    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59        formatter.write_str(self.as_str())
60    }
61}
62
63/// An HTTP(S) proxy URL that passed the remote RPC proxy policy: `http` or `https` scheme, a host
64/// and usable port, root path (`/`), and no credentials, query parameters, or fragment.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct RemoteRpcProxy(reqwest::Url);
67
68impl RemoteRpcProxy {
69    /// Parse `url` as an HTTP(S) proxy for remote RPC endpoints via a pure `Result::and_then`
70    /// Kleisli validation pipeline (scheme -> authority/path/query/fragment -> host/port ->
71    /// native proxy builder).
72    pub fn parse(url: &str) -> Result<Self> {
73        reqwest::Url::parse(url)
74            .map_err(|error| Error::InvalidConfig(format!("invalid remote_rpc_proxy_url: {error}")))
75            .and_then(|parsed| {
76                matches!(parsed.scheme(), "http" | "https")
77                    .then_some(parsed)
78                    .ok_or_else(|| {
79                        Error::InvalidConfig(
80                            "remote_rpc_proxy_url must use http:// or https://".to_string(),
81                        )
82                    })
83            })
84            .and_then(|parsed| {
85                (parsed.username().is_empty()
86                    && parsed.password().is_none()
87                    && parsed.path() == "/"
88                    && parsed.query().is_none()
89                    && parsed.fragment().is_none())
90                .then_some(parsed)
91                .ok_or_else(|| {
92                    Error::InvalidConfig(
93                        "credentials, non-root paths, query parameters, and fragments are not \
94                         permitted in remote_rpc_proxy_url"
95                            .to_string(),
96                    )
97                })
98            })
99            .and_then(|parsed| {
100                (parsed.host().is_some() && parsed.port_or_known_default().is_some())
101                    .then_some(parsed)
102                    .ok_or_else(|| {
103                        Error::InvalidConfig(
104                            "remote_rpc_proxy_url must include a host and usable port".to_string(),
105                        )
106                    })
107            })
108            .and_then(Self::validate_native_proxy)
109            .map(Self)
110    }
111
112    #[cfg(rings_native)]
113    fn validate_native_proxy(parsed: reqwest::Url) -> Result<reqwest::Url> {
114        reqwest::Proxy::all(parsed.as_str())
115            .map(|_| parsed)
116            .map_err(|error| Error::InvalidConfig(format!("invalid remote_rpc_proxy_url: {error}")))
117    }
118
119    #[cfg(not(rings_native))]
120    #[allow(clippy::unnecessary_wraps)]
121    const fn validate_native_proxy(parsed: reqwest::Url) -> Result<reqwest::Url> {
122        Ok(parsed)
123    }
124
125    /// The proxy URL as a string.
126    pub fn as_str(&self) -> &str {
127        self.0.as_str()
128    }
129
130    /// Build the `reqwest::Proxy` for this proxy URL.
131    #[cfg(rings_native)]
132    pub(crate) fn to_reqwest_proxy(&self) -> Result<reqwest::Proxy> {
133        reqwest::Proxy::all(self.as_str()).map_err(|error| Error::RemoteRpcError(error.to_string()))
134    }
135}
136
137impl fmt::Display for RemoteRpcProxy {
138    /// Render the proxy as its URL.
139    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
140        formatter.write_str(self.as_str())
141    }
142}
143
144/// Kleisli combinator attaching `api_token` (when `Some`) as a Bearer header on `client`, or
145/// acting as the identity `Ok(client)` when `None`.
146pub(crate) fn attach_bearer_token(
147    client: rings_rpc::jsonrpc::Client,
148    api_token: Option<&str>,
149) -> Result<rings_rpc::jsonrpc::Client> {
150    match api_token {
151        Some(token) => client
152            .with_bearer_token(token.to_owned())
153            .map_err(|error| Error::RemoteRpcError(error.to_string())),
154        None => Ok(client),
155    }
156}
157
158/// Bound on every HTTP request to a remote endpoint, and on the resolution of its host, so an
159/// endpoint that accepts a connection and never answers, or a resolver that never does, cannot
160/// hold a caller indefinitely.
161#[cfg(rings_native)]
162const REMOTE_RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
163
164/// A JSON-RPC client for `endpoint`: no redirects, a request timeout, and the bearer token
165/// attached when given.
166///
167/// By default (`proxy = None`), ambient proxy variables are ignored and a domain endpoint is
168/// resolved once through the public-target resolver and pinned to the returned addresses. When
169/// `proxy` is `Some`, requests are routed through that explicit HTTP(S) proxy and local DNS
170/// pinning is skipped so the proxy resolves the target (for example on `CONNECT host:port`),
171/// while [`RemoteRpcEndpoint`] still enforces the public-host URL policy before any request is
172/// sent.
173#[cfg(rings_native)]
174pub(crate) async fn remote_rpc_client(
175    endpoint: &RemoteRpcEndpoint,
176    api_token: Option<&str>,
177    proxy: Option<&RemoteRpcProxy>,
178) -> Result<rings_rpc::jsonrpc::Client> {
179    let mut builder = reqwest::Client::builder()
180        .no_proxy()
181        .redirect(reqwest::redirect::Policy::none())
182        .timeout(REMOTE_RPC_TIMEOUT);
183    let target = resolution_target(&endpoint.0)?;
184    let client = match proxy {
185        Some(proxy) => rings_rpc::jsonrpc::Client::with_http_client_builder_and_proxy(
186            endpoint.as_str(),
187            builder,
188            proxy.to_reqwest_proxy()?,
189        ),
190        None => {
191            if let Some(target) = target {
192                let addresses = tokio::time::timeout(
193                    REMOTE_RPC_TIMEOUT,
194                    crate::onion::target::resolve_public_target(&target.lookup),
195                )
196                .await
197                .map_err(|_| {
198                    Error::RemoteRpcError("endpoint resolution timed out".to_string())
199                })??;
200                builder = builder.resolve_to_addrs(&target.pin_host, &addresses);
201            }
202            rings_rpc::jsonrpc::Client::with_http_client_builder(endpoint.as_str(), builder)
203        }
204    }
205    .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
206    attach_bearer_token(client, api_token)
207}
208
209/// The DNS resolution to pin for a domain endpoint; `None` for an IP literal, which needs no
210/// resolution and therefore no pin.
211#[cfg(rings_native)]
212fn resolution_target(parsed: &reqwest::Url) -> Result<Option<ResolutionTarget>> {
213    let port = parsed.port_or_known_default().ok_or_else(|| {
214        Error::UnsafeRemoteRpcTarget("endpoint URL has no usable port".to_string())
215    })?;
216    let no_host = || Error::UnsafeRemoteRpcTarget("endpoint URL has no host".to_string());
217    let pin_host = parsed.host_str().ok_or_else(no_host)?;
218    match parsed.host().ok_or_else(no_host)? {
219        url::Host::Domain(host) => crate::onion::OnionProxyTarget::new(host, port).map(|lookup| {
220            Some(ResolutionTarget {
221                lookup,
222                pin_host: pin_host.to_string(),
223            })
224        }),
225        url::Host::Ipv4(_) | url::Host::Ipv6(_) => Ok(None),
226    }
227}
228
229/// A domain endpoint's resolver target and the host name its addresses are pinned under.
230#[cfg(rings_native)]
231#[derive(Debug, Eq, PartialEq)]
232struct ResolutionTarget {
233    /// The canonical host and port the public-target resolver looks up.
234    lookup: crate::onion::OnionProxyTarget,
235    /// The host name exactly as the HTTP client connects with it, the key its pin lives under.
236    pin_host: String,
237}
238
239/// A JSON-RPC client for `endpoint` with the bearer token attached when given; the browser
240/// enforces its own origin and proxy policy and rejects an explicit `remote_rpc_proxy_url`.
241#[cfg(rings_browser)]
242pub(crate) async fn remote_rpc_client(
243    endpoint: &RemoteRpcEndpoint,
244    api_token: Option<&str>,
245    proxy: Option<&RemoteRpcProxy>,
246) -> Result<rings_rpc::jsonrpc::Client> {
247    proxy
248        .is_none()
249        .then_some(())
250        .ok_or_else(|| {
251            Error::InvalidConfig(
252                "remote_rpc_proxy_url is supported only on native targets".to_string(),
253            )
254        })
255        .and_then(|()| {
256            rings_rpc::jsonrpc::Client::new(endpoint.as_str())
257                .map_err(|error| Error::RemoteRpcError(error.to_string()))
258        })
259        .and_then(|client| attach_bearer_token(client, api_token))
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    /// Local, link-local, single-label, credentialed and non-HTTP targets are refused.
267    #[test]
268    fn endpoint_rejects_local_targets_and_url_credentials() {
269        for target in [
270            "http://127.0.0.1:50001/",
271            "http://169.254.169.254/latest/meta-data/",
272            "https://intranet:50001/",
273            "https://token@example.com:50001/",
274            "file:///tmp/socket",
275        ] {
276            assert!(matches!(
277                RemoteRpcEndpoint::parse(target),
278                Err(Error::UnsafeRemoteRpcTarget(_))
279            ));
280        }
281    }
282
283    /// Public HTTP and HTTPS targets, by name or IP literal, are accepted.
284    #[test]
285    fn endpoint_accepts_public_http_and_https_targets() {
286        for target in [
287            "http://example.com:50001/",
288            "https://1.1.1.1/rpc",
289            "https://[2606:4700:4700::1111]/rpc",
290        ] {
291            assert!(RemoteRpcEndpoint::parse(target).is_ok());
292        }
293    }
294
295    /// IP literals need no DNS pin.
296    #[cfg(rings_native)]
297    #[test]
298    fn literal_endpoints_skip_dns_pinning() -> Result<()> {
299        for target in ["https://1.1.1.1/rpc", "https://[2606:4700:4700::1111]/rpc"] {
300            let endpoint = RemoteRpcEndpoint::parse(target)?;
301            assert_eq!(resolution_target(&endpoint.0)?, None);
302        }
303        Ok(())
304    }
305
306    /// A domain endpoint resolves its host and port and pins under the connect-time host name.
307    #[cfg(rings_native)]
308    #[test]
309    fn domain_endpoints_preserve_connect_time_host_for_dns_pin() -> Result<()> {
310        let endpoint = RemoteRpcEndpoint::parse("https://example.com:8443/rpc")?;
311        let target = resolution_target(&endpoint.0)?;
312        assert!(matches!(
313            target,
314            Some(target)
315                if target.lookup.host() == "example.com"
316                    && target.lookup.port() == 8443
317                    && target.pin_host == "example.com"
318        ));
319        Ok(())
320    }
321
322    /// A trailing-dot domain keeps the dotted spelling as its pin key, the one the HTTP client
323    /// connects with, while resolving the canonical name.
324    #[cfg(rings_native)]
325    #[test]
326    fn trailing_dot_domains_keep_dotted_dns_pin_key() -> Result<()> {
327        let endpoint = RemoteRpcEndpoint::parse("https://example.com.:8443/rpc")?;
328        let target = resolution_target(&endpoint.0)?;
329        assert!(matches!(
330            target,
331            Some(target)
332                if target.lookup.host() == "example.com"
333                    && target.lookup.port() == 8443
334                    && target.pin_host == "example.com."
335        ));
336        Ok(())
337    }
338
339    /// Non-HTTP(S), credentialed, non-root-path, query-bearing, and fragment-bearing proxy URLs
340    /// are rejected.
341    #[test]
342    fn proxy_rejects_non_http_and_credentialed_urls() {
343        for proxy_url in [
344            "socks5://127.0.0.1:1080",
345            "http://user:pass@127.0.0.1:8080",
346            "http://127.0.0.1:8080/subpath",
347            "http://127.0.0.1:8080?mode=direct",
348            "http://127.0.0.1:8080#section",
349            "not-a-url",
350        ] {
351            assert!(matches!(
352                RemoteRpcProxy::parse(proxy_url),
353                Err(Error::InvalidConfig(_))
354            ));
355        }
356    }
357
358    /// Valid HTTP and HTTPS proxy URLs are accepted.
359    #[test]
360    fn proxy_accepts_http_and_https_urls() {
361        for proxy_url in ["http://127.0.0.1:18080", "https://proxy.example.com:8443"] {
362            assert!(RemoteRpcProxy::parse(proxy_url).is_ok());
363        }
364    }
365
366    /// Without an opt-in proxy, `remote_rpc_client` resolves domain endpoints locally (failing on
367    /// `.test`); with `Some(proxy)`, it skips local DNS pinning and forwards the request through
368    /// the configured HTTP proxy, while local `Client::new` connects directly on loopback.
369    #[cfg(rings_native)]
370    #[tokio::test]
371    async fn remote_rpc_client_uses_proxy_only_when_opted_in() -> Result<()> {
372        use tokio::io::AsyncReadExt;
373        use tokio::io::AsyncWriteExt;
374        use tokio::net::TcpListener;
375
376        use crate::test_support::TestTask;
377
378        let proxy_listener = TcpListener::bind("127.0.0.1:0")
379            .await
380            .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
381        let proxy_addr = proxy_listener
382            .local_addr()
383            .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
384        let proxy_url = format!("http://{proxy_addr}");
385        let proxy = RemoteRpcProxy::parse(proxy_url.as_str())?;
386
387        let local_listener = TcpListener::bind("127.0.0.1:0")
388            .await
389            .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
390        let local_addr = local_listener
391            .local_addr()
392            .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
393
394        let unresolvable = RemoteRpcEndpoint::parse("http://seed.example.test:50001/rpc")?;
395        assert!(remote_rpc_client(&unresolvable, None, None).await.is_err());
396
397        let local_task = TestTask::spawn(async move {
398            let (mut stream, _) = local_listener
399                .accept()
400                .await
401                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
402            let mut buf = vec![0_u8; 2048];
403            let read = stream
404                .read(&mut buf)
405                .await
406                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
407            let req = String::from_utf8_lossy(buf.get(..read).unwrap_or_default()).to_string();
408            let body = r#"{"jsonrpc":"2.0","result":{"did":"0x01"},"id":0}"#;
409            let response = format!(
410                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
411                body.len(),
412                body
413            );
414            stream
415                .write_all(response.as_bytes())
416                .await
417                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
418            Ok::<String, Error>(req)
419        });
420
421        let local_client =
422            rings_rpc::jsonrpc::Client::new(format!("http://{local_addr}/").as_str())
423                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
424        let request = rings_rpc::protos::rings_node::NodeDidRequest {};
425        let local_resp: rings_rpc::protos::rings_node::NodeDidResponse = local_client
426            .call_method(rings_rpc::method::Method::NodeDid, &request)
427            .await
428            .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
429        assert_eq!(local_resp.did, "0x01");
430        let local_request_line = local_task
431            .await
432            .map_err(|error| Error::RemoteRpcError(error.to_string()))??;
433        assert!(local_request_line.starts_with("POST / HTTP/1.1\r\n"));
434
435        let proxy_task = TestTask::spawn(async move {
436            let (mut stream, _) = proxy_listener
437                .accept()
438                .await
439                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
440            let mut buf = vec![0_u8; 2048];
441            let read = stream
442                .read(&mut buf)
443                .await
444                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
445            let req = String::from_utf8_lossy(buf.get(..read).unwrap_or_default()).to_string();
446            let body = r#"{"jsonrpc":"2.0","result":{"did":"0x02"},"id":0}"#;
447            let response = format!(
448                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
449                body.len(),
450                body
451            );
452            stream
453                .write_all(response.as_bytes())
454                .await
455                .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
456            Ok::<String, Error>(req)
457        });
458
459        let proxied_client = remote_rpc_client(&unresolvable, None, Some(&proxy)).await?;
460        let proxied_resp: rings_rpc::protos::rings_node::NodeDidResponse = proxied_client
461            .call_method(rings_rpc::method::Method::NodeDid, &request)
462            .await
463            .map_err(|error| Error::RemoteRpcError(error.to_string()))?;
464        assert_eq!(proxied_resp.did, "0x02");
465        let proxy_request_line = proxy_task
466            .await
467            .map_err(|error| Error::RemoteRpcError(error.to_string()))??;
468        assert!(
469            proxy_request_line.starts_with("POST http://seed.example.test:50001/rpc HTTP/1.1\r\n"),
470            "unexpected proxy request: {proxy_request_line}"
471        );
472        Ok(())
473    }
474}