Skip to main content

foundry_common/provider/
runtime_transport.rs

1//! Runtime transport that connects on first request, which can take either of an HTTP,
2//! WebSocket, or IPC transport. Retries are handled by a client layer (e.g.,
3//! `RetryBackoffLayer`) when used.
4
5use crate::{
6    DEFAULT_USER_AGENT, REQUEST_TIMEOUT,
7    provider::{
8        mpp::transport::{LazyMppHttpTransport, lazy_mpp_ws_connect},
9        redact_url,
10    },
11};
12use alloy_json_rpc::{RequestPacket, ResponsePacket};
13use alloy_pubsub::{PubSubConnect, PubSubFrontend};
14use alloy_rpc_types_engine::{Claims, JwtSecret};
15use alloy_transport::{
16    Authorization, BoxTransport, TransportError, TransportErrorKind, TransportFut,
17    utils::guess_local_url,
18};
19use alloy_transport_ipc::IpcConnect;
20use alloy_transport_ws::WsConnect;
21use regex::{Captures, Regex};
22use reqwest::header::{HeaderName, HeaderValue};
23use std::{
24    error::Error as StdError,
25    fmt,
26    path::PathBuf,
27    str::FromStr,
28    sync::{Arc, LazyLock},
29};
30use thiserror::Error;
31use tokio::{
32    runtime::{Handle, Id},
33    sync::RwLock,
34};
35use tower::Service;
36use url::Url;
37
38/// Known MPP-enabled RPC host suffixes.
39///
40/// Endpoints matching these patterns always use the MPP WebSocket transport,
41/// regardless of whether local MPP keys have been discovered.
42const KNOWN_MPP_HOSTS: &[&str] = &[".mpp.tempo.xyz", ".mpp.moderato.tempo.xyz"];
43
44static HTTP_URL_RE: LazyLock<Regex> =
45    LazyLock::new(|| Regex::new(r#"(?i)https?://[^\s<>"']+"#).expect("valid URL regex"));
46
47/// An enum representing the different transports that can be used to connect to a runtime.
48/// Only meant to be used internally by [RuntimeTransport].
49#[derive(Clone, Debug)]
50pub enum InnerTransport {
51    /// HTTP transport with lazy MPP 402 handling.
52    ///
53    /// Unless MPP is disabled, for known Tempo endpoints the MPP layer additionally
54    /// runs the `wallet.tempo.xyz` device-code flow on a 402 when no local access key
55    /// is configured (see [`crate::tempo::ensure_access_key`]).
56    Http(LazyMppHttpTransport),
57    /// WebSocket transport
58    Ws(PubSubFrontend),
59    /// IPC transport
60    Ipc(PubSubFrontend),
61}
62
63/// Error type for the runtime transport.
64#[derive(Error, Debug)]
65pub enum RuntimeTransportError {
66    /// Internal transport error
67    #[error("Internal transport error: {0} with {1}")]
68    TransportError(TransportError, String),
69
70    /// Invalid URL scheme
71    #[error("URL scheme is not supported: {0}")]
72    BadScheme(String),
73
74    /// Invalid HTTP header
75    #[error("Invalid HTTP header: {0}")]
76    BadHeader(String),
77
78    /// Invalid file path
79    #[error("Invalid IPC file path: {0}")]
80    BadPath(String),
81
82    /// Invalid construction of Http provider
83    #[error(transparent)]
84    HttpConstructionError(#[from] reqwest::Error),
85
86    /// Invalid JWT
87    #[error("Invalid JWT: {0}")]
88    InvalidJwt(String),
89}
90
91/// Runtime transport that only connects on first request.
92///
93/// A runtime transport is a custom [`alloy_transport::Transport`] that only connects when the
94/// *first* request is made. When the first request is made, it will connect to the runtime using
95/// either an HTTP WebSocket, or IPC transport depending on the URL used.
96/// Retries for rate-limiting and timeout-related errors are handled by an external
97/// client layer (e.g., `RetryBackoffLayer`) when configured.
98#[derive(Clone, Debug)]
99pub struct RuntimeTransport {
100    /// The connection to the URL, established by the first request on each runtime.
101    connection: Arc<RwLock<Connection>>,
102    /// The URL to connect to.
103    url: Url,
104    /// The headers to use for requests.
105    headers: Vec<String>,
106    /// The JWT to use for requests.
107    jwt: Option<String>,
108    /// The timeout for requests.
109    timeout: std::time::Duration,
110    /// Whether to accept invalid certificates.
111    accept_invalid_certs: bool,
112    /// Whether to disable automatic proxy detection.
113    no_proxy: bool,
114    /// Whether to disable MPP: no `MPP_API_KEY` `x-api-key` header and no 402 payments.
115    no_mpp: bool,
116}
117
118/// The connection state of a [RuntimeTransport].
119#[derive(Debug)]
120enum Connection {
121    /// No request has connected yet.
122    Disconnected,
123    /// Connected from the Tokio runtime with ID `runtime`.
124    ///
125    /// Connections may own tasks and I/O resources on their originating runtime, so a request
126    /// from another runtime reconnects.
127    Connected { runtime: Id, transport: InnerTransport },
128}
129
130impl Connection {
131    /// Returns the transport if it was connected from `runtime`.
132    fn transport_for(&self, runtime: Id) -> Option<InnerTransport> {
133        match self {
134            Self::Connected { runtime: connected, transport } if *connected == runtime => {
135                Some(transport.clone())
136            }
137            Self::Connected { .. } | Self::Disconnected => None,
138        }
139    }
140}
141
142/// A builder for [RuntimeTransport].
143#[derive(Debug)]
144pub struct RuntimeTransportBuilder {
145    url: Url,
146    headers: Vec<String>,
147    jwt: Option<String>,
148    timeout: std::time::Duration,
149    accept_invalid_certs: bool,
150    no_proxy: bool,
151    no_mpp: bool,
152}
153
154impl RuntimeTransportBuilder {
155    /// Create a new builder with the given URL.
156    pub const fn new(url: Url) -> Self {
157        Self {
158            url,
159            headers: vec![],
160            jwt: None,
161            timeout: REQUEST_TIMEOUT,
162            accept_invalid_certs: false,
163            no_proxy: false,
164            no_mpp: false,
165        }
166    }
167
168    /// Set the URL for the transport.
169    pub fn with_headers(mut self, headers: Vec<String>) -> Self {
170        self.headers = headers;
171        self
172    }
173
174    /// Set the JWT for the transport.
175    pub fn with_jwt(mut self, jwt: Option<String>) -> Self {
176        self.jwt = jwt;
177        self
178    }
179
180    /// Set the timeout for the transport.
181    pub const fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
182        self.timeout = timeout;
183        self
184    }
185
186    /// Set whether to accept invalid certificates.
187    pub const fn accept_invalid_certs(mut self, accept_invalid_certs: bool) -> Self {
188        self.accept_invalid_certs = accept_invalid_certs;
189        self
190    }
191
192    /// Set whether to disable automatic proxy detection.
193    ///
194    /// This can help in sandboxed environments (e.g., Cursor IDE sandbox, macOS App Sandbox)
195    /// where system proxy detection via SCDynamicStore causes crashes.
196    pub const fn no_proxy(mut self, no_proxy: bool) -> Self {
197        self.no_proxy = no_proxy;
198        self
199    }
200
201    /// Set whether to disable MPP: no `MPP_API_KEY` `x-api-key` header and no 402 payments.
202    pub const fn no_mpp(mut self, no_mpp: bool) -> Self {
203        self.no_mpp = no_mpp;
204        self
205    }
206
207    /// Builds the [RuntimeTransport] and returns it in a disconnected state.
208    /// The runtime transport will then connect when the first request happens.
209    pub fn build(self) -> RuntimeTransport {
210        RuntimeTransport {
211            connection: Arc::new(RwLock::new(Connection::Disconnected)),
212            url: self.url,
213            headers: self.headers,
214            jwt: self.jwt,
215            timeout: self.timeout,
216            accept_invalid_certs: self.accept_invalid_certs,
217            no_proxy: self.no_proxy,
218            no_mpp: self.no_mpp,
219        }
220    }
221}
222
223impl fmt::Display for RuntimeTransport {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        write!(f, "RuntimeTransport {}", redact_url(self.url.as_str()))
226    }
227}
228
229impl RuntimeTransport {
230    /// Connects the underlying transport, depending on the URL scheme.
231    pub async fn connect(&self) -> Result<InnerTransport, RuntimeTransportError> {
232        match self.url.scheme() {
233            "http" | "https" => self.connect_http(),
234            "ws" | "wss" => self.connect_ws().await,
235            "file" => self.connect_ipc().await,
236            _ => Err(RuntimeTransportError::BadScheme(self.url.scheme().to_string())),
237        }
238    }
239
240    fn reqwest_headers(&self) -> Result<reqwest::header::HeaderMap, RuntimeTransportError> {
241        let mut headers = reqwest::header::HeaderMap::new();
242
243        // If there's a JWT, add it to the headers if we can decode it.
244        if let Some(jwt) = self.jwt.clone() {
245            let auth =
246                build_auth(jwt).map_err(|e| RuntimeTransportError::InvalidJwt(e.to_string()))?;
247
248            let mut auth_value: HeaderValue =
249                HeaderValue::from_str(&auth.to_string()).expect("Header should be valid string");
250            auth_value.set_sensitive(true);
251
252            headers.insert(reqwest::header::AUTHORIZATION, auth_value);
253        };
254
255        // Add any custom headers.
256        for header in &self.headers {
257            let make_err = || RuntimeTransportError::BadHeader(header.clone());
258
259            let (key, val) = header.split_once(':').ok_or_else(make_err)?;
260
261            headers.insert(
262                HeaderName::from_str(key.trim()).map_err(|_| make_err())?,
263                HeaderValue::from_str(val.trim()).map_err(|_| make_err())?,
264            );
265        }
266
267        if !headers.contains_key(reqwest::header::USER_AGENT) {
268            headers.insert(
269                reqwest::header::USER_AGENT,
270                HeaderValue::from_str(DEFAULT_USER_AGENT)
271                    .expect("User-Agent should be valid string"),
272            );
273        }
274
275        // If MPP_API_KEY is set, attach it as x-api-key for gated MPP proxies.
276        // Does not override an explicit x-api-key header from the user.
277        if !self.no_mpp
278            && !headers.contains_key(HeaderName::from_static("x-api-key"))
279            && let Ok(api_key) = std::env::var("MPP_API_KEY")
280        {
281            let api_key = api_key.trim();
282            if !api_key.is_empty() {
283                let mut value = HeaderValue::from_str(api_key)
284                    .map_err(|_| RuntimeTransportError::BadHeader("MPP_API_KEY".to_string()))?;
285                value.set_sensitive(true);
286                headers.insert(HeaderName::from_static("x-api-key"), value);
287            }
288        }
289
290        Ok(headers)
291    }
292
293    fn reqwest_client_with_headers(
294        &self,
295        headers: reqwest::header::HeaderMap,
296    ) -> Result<reqwest::Client, RuntimeTransportError> {
297        let mut client_builder = reqwest::Client::builder()
298            .timeout(self.timeout)
299            .danger_accept_invalid_certs(self.accept_invalid_certs);
300
301        // Custom headers and `x-api-key` may contain credentials that reqwest does not strip on
302        // redirects, so only same-origin redirects are followed when they are sent.
303        if !self.headers.is_empty() || headers.contains_key(HeaderName::from_static("x-api-key")) {
304            client_builder =
305                client_builder.redirect(reqwest::redirect::Policy::custom(|attempt| {
306                    if attempt
307                        .previous()
308                        .last()
309                        .is_some_and(|previous| previous.origin() != attempt.url().origin())
310                    {
311                        attempt.error("cross-origin RPC redirects are not allowed")
312                    } else {
313                        reqwest::redirect::Policy::default().redirect(attempt)
314                    }
315                }));
316        }
317
318        // Disable automatic proxy detection if requested. This helps in sandboxed environments
319        // (e.g., Cursor IDE sandbox, macOS App Sandbox) where system proxy detection via
320        // SCDynamicStore causes crashes. See: https://github.com/foundry-rs/foundry/issues/12733
321        if self.no_proxy || guess_local_url(self.url.as_str()) {
322            client_builder = client_builder.no_proxy();
323        }
324
325        client_builder = client_builder.default_headers(headers);
326
327        Ok(client_builder.build()?)
328    }
329
330    /// Creates a new reqwest client from this transport.
331    pub fn reqwest_client(&self) -> Result<reqwest::Client, RuntimeTransportError> {
332        self.reqwest_client_with_headers(self.reqwest_headers()?)
333    }
334
335    /// Connects to an HTTP transport with lazy MPP 402 handling.
336    fn connect_http(&self) -> Result<InnerTransport, RuntimeTransportError> {
337        let headers = self.reqwest_headers()?;
338        let client = self.reqwest_client_with_headers(headers.clone())?;
339        Ok(InnerTransport::Http(LazyMppHttpTransport::lazy(
340            client,
341            self.url.clone(),
342            headers,
343            !self.no_mpp,
344        )))
345    }
346
347    /// Connects to a WS transport.
348    ///
349    /// Uses the canonical Alloy MPP WebSocket transport when the endpoint is a
350    /// known MPP service; it only pays challenges when MPP is not disabled.
351    /// Otherwise falls back to alloy's plain [`WsConnect`] with zero overhead.
352    async fn connect_ws(&self) -> Result<InnerTransport, RuntimeTransportError> {
353        let auth = self
354            .jwt
355            .as_ref()
356            .map(|jwt| build_auth(jwt.clone()))
357            .transpose()
358            .map_err(|e| RuntimeTransportError::InvalidJwt(e.to_string()))?;
359
360        let service = if is_known_mpp_endpoint(&self.url) {
361            let mut ws = lazy_mpp_ws_connect(&self.url, !self.no_mpp);
362            if let Some(auth) = auth {
363                ws = ws.with_auth(auth);
364            }
365            ws.into_service().await.map_err(|e| {
366                RuntimeTransportError::TransportError(e, redact_url(self.url.as_str()))
367            })?
368        } else {
369            let mut ws = WsConnect::new(self.url.to_string());
370            if let Some(auth) = auth {
371                ws = ws.with_auth(auth);
372            }
373            ws.into_service().await.map_err(|e| {
374                RuntimeTransportError::TransportError(e, redact_url(self.url.as_str()))
375            })?
376        };
377
378        Ok(InnerTransport::Ws(service))
379    }
380
381    /// Connects to an IPC transport.
382    async fn connect_ipc(&self) -> Result<InnerTransport, RuntimeTransportError> {
383        let path = url_to_file_path(&self.url)
384            .map_err(|_| RuntimeTransportError::BadPath(self.url.to_string()))?;
385        let ipc_connector = IpcConnect::new(path.clone());
386        let ipc = ipc_connector.into_service().await.map_err(|e| {
387            RuntimeTransportError::TransportError(e, path.clone().display().to_string())
388        })?;
389        Ok(InnerTransport::Ipc(ipc))
390    }
391
392    /// Sends a request using the underlying transport.
393    /// If this is the first request, it will connect to the appropriate transport depending on the
394    /// URL scheme. Retries are performed by an external client layer (e.g., `RetryBackoffLayer`),
395    /// if such a layer is configured by the caller.
396    /// For sending the actual request, this action is delegated down to the
397    /// underlying transport through Tower's [tower::Service::call]. See tower's [tower::Service]
398    /// trait for more information.
399    pub fn request(&self, req: RequestPacket) -> TransportFut<'static> {
400        let this = self.clone();
401        Box::pin(async move {
402            let runtime = Handle::current().id();
403            let connected = this.connection.read().await.transport_for(runtime);
404            let transport = match connected {
405                Some(transport) => transport,
406                None => {
407                    let mut connection = this.connection.write().await;
408                    // Another request may have connected while waiting for the write lock.
409                    match connection.transport_for(runtime) {
410                        Some(transport) => transport,
411                        None => {
412                            let transport =
413                                this.connect().await.map_err(TransportErrorKind::custom)?;
414                            *connection =
415                                Connection::Connected { runtime, transport: transport.clone() };
416                            transport
417                        }
418                    }
419                }
420            };
421
422            match transport {
423                InnerTransport::Http(mut http) => http
424                    .call(req)
425                    .await
426                    .map_err(|error| redact_http_transport_error(error, &this.url)),
427                InnerTransport::Ws(mut ws) => ws.call(req).await,
428                InnerTransport::Ipc(mut ipc) => ipc.call(req).await,
429            }
430        })
431    }
432
433    /// Convert this transport into a boxed trait object.
434    pub fn boxed(self) -> BoxTransport {
435        BoxTransport::new(self)
436    }
437}
438
439/// Returns `true` if `url` points to a known MPP-enabled RPC service.
440fn is_known_mpp_endpoint(url: &Url) -> bool {
441    url.host_str().is_some_and(|host| KNOWN_MPP_HOSTS.iter().any(|suffix| host.ends_with(suffix)))
442}
443
444fn redact_http_transport_error(error: TransportError, endpoint: &Url) -> TransportError {
445    let alloy_json_rpc::RpcError::Transport(TransportErrorKind::Custom(source)) = &error else {
446        return error;
447    };
448    let safe_endpoint = redact_url(endpoint.as_str());
449
450    let mut message = String::new();
451    let mut error: Option<&(dyn StdError + 'static)> = Some(source.as_ref());
452    while let Some(source) = error {
453        if !message.is_empty() {
454            message.push_str(": ");
455        }
456        message.push_str(&source.to_string());
457        error = source.source();
458    }
459    let message = HTTP_URL_RE.replace_all(&message, |captures: &Captures<'_>| {
460        let candidate = &captures[0];
461        let Ok(url) = Url::parse(candidate) else { return candidate.to_owned() };
462        if url.host() == endpoint.host()
463            && url.port_or_known_default() == endpoint.port_or_known_default()
464        {
465            safe_endpoint.clone()
466        } else {
467            candidate.to_owned()
468        }
469    });
470    TransportErrorKind::custom_str(&message)
471}
472
473impl tower::Service<RequestPacket> for RuntimeTransport {
474    type Response = ResponsePacket;
475    type Error = TransportError;
476    type Future = TransportFut<'static>;
477
478    #[inline]
479    fn poll_ready(
480        &mut self,
481        _cx: &mut std::task::Context<'_>,
482    ) -> std::task::Poll<Result<(), Self::Error>> {
483        std::task::Poll::Ready(Ok(()))
484    }
485
486    #[inline]
487    fn call(&mut self, req: RequestPacket) -> Self::Future {
488        self.request(req)
489    }
490}
491
492impl tower::Service<RequestPacket> for &RuntimeTransport {
493    type Response = ResponsePacket;
494    type Error = TransportError;
495    type Future = TransportFut<'static>;
496
497    #[inline]
498    fn poll_ready(
499        &mut self,
500        _cx: &mut std::task::Context<'_>,
501    ) -> std::task::Poll<Result<(), Self::Error>> {
502        std::task::Poll::Ready(Ok(()))
503    }
504
505    #[inline]
506    fn call(&mut self, req: RequestPacket) -> Self::Future {
507        self.request(req)
508    }
509}
510
511fn build_auth(jwt: String) -> eyre::Result<Authorization> {
512    // Decode jwt from hex, then generate claims (iat with current timestamp)
513    let secret = JwtSecret::from_hex(jwt)?;
514    let claims = Claims::default();
515    let token = secret.encode(&claims)?;
516
517    let auth = Authorization::Bearer(token);
518
519    Ok(auth)
520}
521
522#[cfg(windows)]
523fn url_to_file_path(url: &Url) -> Result<PathBuf, ()> {
524    const PREFIX: &str = "file:///pipe/";
525
526    let url_str = url.as_str();
527
528    if let Some(pipe_name) = url_str.strip_prefix(PREFIX) {
529        let pipe_path = format!(r"\\.\pipe\{pipe_name}");
530        return Ok(PathBuf::from(pipe_path));
531    }
532
533    url.to_file_path()
534}
535
536#[cfg(not(windows))]
537fn url_to_file_path(url: &Url) -> Result<PathBuf, ()> {
538    url.to_file_path()
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use alloy_json_rpc::{Id as RpcId, Request};
545    use axum::{Json, Router, routing::post};
546    use reqwest::header::HeaderMap;
547    use serde_json::{Value, json};
548    use std::{io, time::Duration};
549    use tokio::{runtime::Builder, sync::Notify, time::timeout};
550
551    #[derive(Debug, Error)]
552    #[error("request to https://example.com/private-api-key failed")]
553    struct ProviderError {
554        #[source]
555        source: io::Error,
556    }
557
558    #[test]
559    fn http_transport_errors_preserve_provider_guidance() {
560        let endpoint =
561            Url::parse("https://user:password@example.com/private-api-key?token=secret").unwrap();
562        let error = TransportErrorKind::custom(ProviderError {
563            source: io::Error::other(
564                "Authorize an access key with:\n  cast tempo login --no-browser",
565            ),
566        });
567
568        let report = redact_http_transport_error(error, &endpoint).to_string();
569
570        assert!(report.contains("https://example.com/"));
571        assert!(report.contains("cast tempo login --no-browser"));
572        assert!(!report.contains("password"));
573        assert!(!report.contains("private-api-key"));
574        assert!(!report.contains("secret"));
575    }
576
577    #[test]
578    fn http_transport_errors_redact_endpoint_paths() {
579        let endpoint =
580            Url::parse("https://user:password@example.com/private-api-key?token=secret").unwrap();
581        let error = TransportErrorKind::custom_str(concat!(
582            "request to https://example.com/private-api-key failed: connection refused\n\n",
583            "Authorize an access key with:\n  cast tempo login"
584        ));
585
586        let error = redact_http_transport_error(error, &endpoint);
587        let report = error.to_string();
588
589        assert!(report.contains("https://example.com/"));
590        assert!(!report.contains("password"));
591        assert!(!report.contains("private-api-key"));
592        assert!(!report.contains("secret"));
593        assert!(report.to_lowercase().contains("connection refused"));
594        assert!(report.contains("cast tempo login"));
595    }
596
597    #[test]
598    fn http_transport_errors_redact_normalized_endpoint_variants() {
599        let endpoint =
600            Url::parse("https://user:password@example.com/private-api-key?token=secret").unwrap();
601        let error = TransportErrorKind::custom_str(
602            "request to https://USER:normalized@example.com:443/different%2Fpath?key=other failed",
603        );
604
605        let report = redact_http_transport_error(error, &endpoint).to_string();
606
607        assert!(report.contains("https://example.com/"));
608        assert!(!report.contains("normalized"));
609        assert!(!report.contains("different"));
610        assert!(!report.contains("other"));
611    }
612
613    #[tokio::test]
614    async fn websocket_error_redacts_url_credentials() {
615        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
616        let address = listener.local_addr().unwrap();
617        drop(listener);
618        let url = Url::parse(&format!(
619            "ws://user:password@{address}/private-api-key?token=secret#fragment"
620        ))
621        .unwrap();
622        let transport = RuntimeTransportBuilder::new(url).build();
623
624        let error = transport.connect_ws().await.unwrap_err().to_string();
625
626        assert!(error.contains(&format!("ws://{address}/")));
627        assert!(!error.contains("user"));
628        assert!(!error.contains("password"));
629        assert!(!error.contains("private-api-key"));
630        assert!(!error.contains("secret"));
631    }
632
633    #[tokio::test]
634    async fn test_user_agent_header() {
635        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
636        let url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
637
638        let http_handler = axum::routing::get(|actual_headers: HeaderMap| {
639            let user_agent = HeaderName::from_str("User-Agent").unwrap();
640            assert_eq!(actual_headers[user_agent], HeaderValue::from_str("test-agent").unwrap());
641
642            async { "" }
643        });
644
645        let server_task = tokio::spawn(async move {
646            axum::serve(listener, http_handler.into_make_service()).await.unwrap()
647        });
648
649        let transport = RuntimeTransportBuilder::new(url.clone())
650            .with_headers(vec!["User-Agent: test-agent".to_string()])
651            .build();
652        let inner = transport.connect_http().unwrap();
653
654        match inner {
655            InnerTransport::Http(http) => {
656                let _ = http.client().get(url).send().await.unwrap();
657
658                // assert inside http_handler
659            }
660            _ => unreachable!(),
661        }
662
663        server_task.abort();
664    }
665
666    #[tokio::test]
667    async fn connect_rejects_invalid_jwt() {
668        for scheme in ["http", "https", "ws", "wss"] {
669            for jwt in ["not-hex", "00"] {
670                let url = Url::parse(&format!("{scheme}://127.0.0.1:0")).unwrap();
671                let transport =
672                    RuntimeTransportBuilder::new(url).with_jwt(Some(jwt.to_string())).build();
673
674                let error = transport.connect().await.unwrap_err();
675
676                assert!(
677                    matches!(error, RuntimeTransportError::InvalidJwt(_)),
678                    "expected InvalidJwt for {scheme} with {jwt:?}, got {error:?}"
679                );
680            }
681        }
682    }
683
684    #[tokio::test]
685    async fn pending_request_does_not_block_another_runtime() {
686        let started = Arc::new(Notify::new());
687        let release = Arc::new(Notify::new());
688        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
689        let url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
690        let router = Router::new().route(
691            "/",
692            post({
693                let started = started.clone();
694                let release = release.clone();
695                move |Json(request): Json<Value>| {
696                    let started = started.clone();
697                    let release = release.clone();
698                    async move {
699                        if request["method"] == "hold" {
700                            started.notify_one();
701                            release.notified().await;
702                        }
703                        Json(json!({"jsonrpc": "2.0", "id": request["id"], "result": "0x1"}))
704                    }
705                }
706            }),
707        );
708        let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
709        let transport = RuntimeTransportBuilder::new(url).build();
710        let ready =
711            RequestPacket::from(Request::new("ready", RpcId::Number(1), ()).serialize().unwrap());
712        transport.request(ready.clone()).await.unwrap();
713        let hold = Request::new("hold", RpcId::Number(2), ()).serialize().unwrap().into();
714        let pending = tokio::spawn(transport.request(hold));
715        started.notified().await;
716
717        let result =
718            tokio::task::spawn_blocking(move || {
719                Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
720                    timeout(Duration::from_secs(2), transport.request(ready)).await
721                })
722            })
723            .await
724            .unwrap();
725        release.notify_one();
726        pending.await.unwrap().unwrap();
727        server.abort();
728        result.expect("another runtime waited for an in-flight request").unwrap();
729    }
730}