rama/cli/service/
echo.rs

1//! Echo '[`Service`] that echos the [`http`] [`Request`] and [`tls`] client config.
2//!
3//! [`Service`]: crate::Service
4//! [`http`]: crate::http
5//! [`Request`]: crate::http::Request
6//! [`tls`]: crate::tls
7
8use crate::{
9    Layer, Service,
10    cli::ForwardKind,
11    combinators::{Either3, Either7},
12    error::{BoxError, ErrorContext, OpaqueError},
13    extensions::ExtensionsRef,
14    http::{
15        Request, Response, Version,
16        body::util::BodyExt,
17        convert::curl,
18        core::h2::frame::EarlyFrameCapture,
19        header::USER_AGENT,
20        headers::forwarded::{CFConnectingIp, ClientIp, TrueClientIp, XClientIp, XRealIp},
21        layer::{
22            forwarded::GetForwardedHeaderLayer,
23            required_header::AddRequiredResponseHeadersLayer,
24            trace::TraceLayer,
25            ua::{UserAgent, UserAgentClassifierLayer},
26        },
27        proto::h1::Http1HeaderMap,
28        proto::h2::PseudoHeaderOrder,
29        server::{HttpServer, layer::upgrade::UpgradeLayer},
30        service::web::{extract::Json, response::IntoResponse},
31        ws::handshake::server::{WebSocketAcceptor, WebSocketEchoService, WebSocketMatcher},
32    },
33    layer::{ConsumeErrLayer, LimitLayer, TimeoutLayer, limit::policy::ConcurrentPolicy},
34    net::fingerprint::AkamaiH2,
35    net::fingerprint::Ja4H,
36    net::forwarded::Forwarded,
37    net::http::RequestContext,
38    net::stream::{SocketInfo, layer::http::BodyLimitLayer},
39    proxy::haproxy::server::HaProxyLayer,
40    rt::Executor,
41    tcp::TcpStream,
42    telemetry::tracing,
43    ua::profile::UserAgentDatabase,
44};
45
46use serde::Serialize;
47use serde_json::json;
48use std::{convert::Infallible, time::Duration};
49
50#[cfg(all(feature = "rustls", not(feature = "boring")))]
51use crate::tls::rustls::server::{TlsAcceptorData, TlsAcceptorLayer};
52
53#[cfg(any(feature = "rustls", feature = "boring"))]
54use crate::{
55    net::fingerprint::{Ja3, Ja4, PeetPrint},
56    net::tls::{
57        SecureTransport,
58        client::ClientHelloExtension,
59        client::{ECHClientHello, NegotiatedTlsParameters},
60    },
61};
62#[cfg(feature = "boring")]
63use crate::{
64    net::tls::server::ServerConfig,
65    tls::boring::server::{TlsAcceptorData, TlsAcceptorLayer},
66};
67
68#[cfg(feature = "boring")]
69type TlsConfig = ServerConfig;
70
71#[cfg(all(feature = "rustls", not(feature = "boring")))]
72type TlsConfig = TlsAcceptorData;
73
74#[derive(Debug, Clone)]
75/// Builder that can be used to run your own echo [`Service`],
76/// echo'ing back information about that request and its underlying transport / presentation layers.
77pub struct EchoServiceBuilder<H> {
78    concurrent_limit: usize,
79    body_limit: usize,
80    timeout: Duration,
81    forward: Option<ForwardKind>,
82
83    #[cfg(any(feature = "rustls", feature = "boring"))]
84    tls_server_config: Option<TlsConfig>,
85
86    http_version: Option<Version>,
87
88    ws_support: bool,
89
90    http_service_builder: H,
91
92    uadb: Option<std::sync::Arc<UserAgentDatabase>>,
93}
94
95impl Default for EchoServiceBuilder<()> {
96    fn default() -> Self {
97        Self {
98            concurrent_limit: 0,
99            body_limit: 1024 * 1024,
100            timeout: Duration::ZERO,
101            forward: None,
102
103            #[cfg(any(feature = "rustls", feature = "boring"))]
104            tls_server_config: None,
105
106            http_version: None,
107
108            ws_support: false,
109
110            http_service_builder: (),
111
112            uadb: None,
113        }
114    }
115}
116
117impl EchoServiceBuilder<()> {
118    /// Create a new [`EchoServiceBuilder`].
119    #[must_use]
120    pub fn new() -> Self {
121        Self::default()
122    }
123}
124
125impl<H> EchoServiceBuilder<H> {
126    crate::utils::macros::generate_set_and_with! {
127        /// set the number of concurrent connections to allow
128        ///
129        /// (0 = no limit)
130        pub fn concurrent(mut self, limit: usize) -> Self {
131            self.concurrent_limit = limit;
132            self
133        }
134    }
135
136    crate::utils::macros::generate_set_and_with! {
137        /// set the body limit in bytes for each request
138        pub fn body_limit(mut self, limit: usize) -> Self {
139            self.body_limit = limit;
140            self
141        }
142    }
143
144    crate::utils::macros::generate_set_and_with! {
145        /// set the timeout in seconds for each connection
146        ///
147        /// (0 = no timeout)
148        pub fn timeout(mut self, timeout: Duration) -> Self {
149            self.timeout = timeout;
150            self
151        }
152    }
153
154    crate::utils::macros::generate_set_and_with! {
155        /// enable support for one of the following "forward" headers or protocols
156        ///
157        /// Supported headers:
158        ///
159        /// Forwarded ("for="), X-Forwarded-For
160        ///
161        /// X-Client-IP Client-IP, X-Real-IP
162        ///
163        /// CF-Connecting-IP, True-Client-IP
164        ///
165        /// Or using HaProxy protocol.
166        pub fn forward(mut self, kind: Option<ForwardKind>) -> Self {
167            self.forward = kind;
168            self
169        }
170    }
171
172    crate::utils::macros::generate_set_and_with! {
173        #[cfg(any(feature = "rustls", feature = "boring"))]
174        /// define a tls server cert config to be used for tls terminaton
175        /// by the echo service.
176        pub fn tls_server_config(mut self, cfg: Option<TlsConfig>) -> Self {
177            self.tls_server_config = cfg;
178            self
179        }
180    }
181
182    crate::utils::macros::generate_set_and_with! {
183        /// set the http version to use for the http server (auto by default)
184        pub fn http_version(mut self, version: Option<Version>) -> Self {
185            self.http_version = version;
186            self
187        }
188    }
189
190    /// add a custom http layer which will be applied to the existing http layers
191    pub fn with_http_layer<H2>(self, layer: H2) -> EchoServiceBuilder<(H, H2)> {
192        EchoServiceBuilder {
193            concurrent_limit: self.concurrent_limit,
194            body_limit: self.body_limit,
195            timeout: self.timeout,
196            forward: self.forward,
197
198            #[cfg(any(feature = "rustls", feature = "boring"))]
199            tls_server_config: self.tls_server_config,
200
201            http_version: self.http_version,
202
203            ws_support: self.ws_support,
204
205            http_service_builder: (self.http_service_builder, layer),
206
207            uadb: self.uadb,
208        }
209    }
210
211    crate::utils::macros::generate_set_and_with! {
212        /// maybe set the user agent datasbase that if set would be used to look up
213        /// a user agent (by ua header string) to see if we have a ja3/ja4 hash.
214        pub fn user_agent_database(
215            mut self,
216            db: Option<std::sync::Arc<UserAgentDatabase>>,
217        ) -> Self {
218            self.uadb = db;
219            self
220        }
221    }
222
223    crate::utils::macros::generate_set_and_with! {
224        /// define whether or not WS support is enabled
225        pub fn ws_support(
226            mut self,
227            support: bool,
228        ) -> Self {
229            self.ws_support = support;
230            self
231        }
232    }
233}
234
235impl<H> EchoServiceBuilder<H>
236where
237    H: Layer<EchoService, Service: Service<Request, Response = Response, Error = BoxError>>,
238{
239    #[allow(unused_mut)]
240    /// build a tcp service ready to echo http traffic back
241    pub fn build(
242        mut self,
243        executor: Executor,
244    ) -> Result<impl Service<TcpStream, Response = (), Error = Infallible>, BoxError> {
245        let tcp_forwarded_layer = match &self.forward {
246            Some(ForwardKind::HaProxy) => Some(HaProxyLayer::default()),
247            _ => None,
248        };
249
250        let http_service = self.build_http();
251
252        #[cfg(all(feature = "rustls", not(feature = "boring")))]
253        let tls_cfg = self.tls_server_config;
254
255        #[cfg(feature = "boring")]
256        let tls_cfg: Option<TlsAcceptorData> = match self.tls_server_config {
257            Some(cfg) => Some(cfg.try_into()?),
258            None => None,
259        };
260
261        let tcp_service_builder = (
262            ConsumeErrLayer::trace(tracing::Level::DEBUG),
263            (self.concurrent_limit > 0)
264                .then(|| LimitLayer::new(ConcurrentPolicy::max(self.concurrent_limit))),
265            (!self.timeout.is_zero()).then(|| TimeoutLayer::new(self.timeout)),
266            tcp_forwarded_layer,
267            BodyLimitLayer::request_only(self.body_limit),
268            #[cfg(any(feature = "rustls", feature = "boring"))]
269            tls_cfg.map(|cfg| TlsAcceptorLayer::new(cfg).with_store_client_hello(true)),
270        );
271
272        let http_transport_service = match self.http_version {
273            Some(Version::HTTP_2) => Either3::A({
274                let mut http = HttpServer::h2(executor);
275                if self.ws_support {
276                    http.h2_mut().enable_connect_protocol();
277                }
278                http.service(http_service)
279            }),
280            Some(Version::HTTP_11 | Version::HTTP_10 | Version::HTTP_09) => {
281                Either3::B(HttpServer::http1().service(http_service))
282            }
283            Some(_) => {
284                return Err(OpaqueError::from_display("unsupported http version").into_boxed());
285            }
286            None => Either3::C({
287                let mut http = HttpServer::auto(executor);
288                if self.ws_support {
289                    http.h2_mut().enable_connect_protocol();
290                }
291                http.service(http_service)
292            }),
293        };
294
295        Ok(tcp_service_builder.into_layer(http_transport_service))
296    }
297
298    /// build an http service ready to echo http traffic back
299    pub fn build_http(
300        &self,
301    ) -> impl Service<Request, Response: IntoResponse, Error = Infallible> + use<H> {
302        let http_forwarded_layer = match &self.forward {
303            None | Some(ForwardKind::HaProxy) => None,
304            Some(ForwardKind::Forwarded) => Some(Either7::A(GetForwardedHeaderLayer::forwarded())),
305            Some(ForwardKind::XForwardedFor) => {
306                Some(Either7::B(GetForwardedHeaderLayer::x_forwarded_for()))
307            }
308            Some(ForwardKind::XClientIp) => {
309                Some(Either7::C(GetForwardedHeaderLayer::<XClientIp>::new()))
310            }
311            Some(ForwardKind::ClientIp) => {
312                Some(Either7::D(GetForwardedHeaderLayer::<ClientIp>::new()))
313            }
314            Some(ForwardKind::XRealIp) => {
315                Some(Either7::E(GetForwardedHeaderLayer::<XRealIp>::new()))
316            }
317            Some(ForwardKind::CFConnectingIp) => {
318                Some(Either7::F(GetForwardedHeaderLayer::<CFConnectingIp>::new()))
319            }
320            Some(ForwardKind::TrueClientIp) => {
321                Some(Either7::G(GetForwardedHeaderLayer::<TrueClientIp>::new()))
322            }
323        };
324
325        (
326            TraceLayer::new_for_http(),
327            AddRequiredResponseHeadersLayer::default(),
328            UserAgentClassifierLayer::new(),
329            ConsumeErrLayer::default(),
330            http_forwarded_layer,
331            self.ws_support.then(|| {
332                UpgradeLayer::new(
333                    WebSocketMatcher::default(),
334                    {
335                        let acceptor = WebSocketAcceptor::default()
336                            .with_protocols_flex(true)
337                            .with_echo_protocols();
338
339                        #[cfg(feature = "compression")]
340                        {
341                            acceptor.with_per_message_deflate_overwrite_extensions()
342                        }
343                        #[cfg(not(feature = "compression"))]
344                        {
345                            acceptor
346                        }
347                    },
348                    ConsumeErrLayer::trace(tracing::Level::DEBUG)
349                        .into_layer(WebSocketEchoService::default()),
350                )
351            }),
352        )
353            .into_layer(self.http_service_builder.layer(EchoService {
354                uadb: self.uadb.clone(),
355            }))
356    }
357}
358
359#[derive(Debug, Clone)]
360#[non_exhaustive]
361/// The inner echo-service used by the [`EchoServiceBuilder`].
362pub struct EchoService {
363    uadb: Option<std::sync::Arc<UserAgentDatabase>>,
364}
365
366impl Service<Request> for EchoService {
367    type Response = Response;
368    type Error = BoxError;
369
370    async fn serve(&self, req: Request) -> Result<Self::Response, Self::Error> {
371        let user_agent_info = req
372            .extensions()
373            .get()
374            .map(|ua: &UserAgent| {
375                json!({
376                    "user_agent": ua.header_str().to_owned(),
377                    "kind": ua.info().map(|info| info.kind.to_string()),
378                    "version": ua.info().and_then(|info| info.version),
379                    "platform": ua.platform().map(|v| v.to_string()),
380                })
381            })
382            .unwrap_or_default();
383
384        let request_context = RequestContext::try_from(&req)?;
385
386        let authority = request_context.authority.to_string();
387        let scheme = request_context.protocol.to_string();
388
389        let ua_str = req
390            .headers()
391            .get(USER_AGENT)
392            .and_then(|h| h.to_str().ok())
393            .map(ToOwned::to_owned);
394        tracing::debug!(
395            user_agent.original = ua_str,
396            "echo request received from ua with ua header",
397        );
398
399        #[derive(Debug, Serialize)]
400        struct FingerprintProfileData {
401            hash: String,
402            verbose: String,
403            matched: bool,
404        }
405
406        let ja4h = Ja4H::compute(&req)
407            .inspect_err(|err| tracing::error!("ja4h compute failure: {err:?}"))
408            .ok()
409            .map(|ja4h| {
410                let mut profile_ja4h: Option<FingerprintProfileData> = None;
411
412                if let Some(uadb) = self.uadb.as_deref()
413                    && let Some(profile) =
414                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
415                    {
416                        let matched_ja4h = match req.version() {
417                            Version::HTTP_10 | Version::HTTP_11 => profile
418                                .http
419                                .ja4h_h1_navigate(Some(req.method().clone()))
420                                .inspect_err(|err| {
421                                    tracing::trace!(
422                                        "ja4h computation of matched profile for incoming h1 req: {err:?}"
423                                    )
424                                })
425                                .ok(),
426                            Version::HTTP_2 => profile
427                                .http
428                                .ja4h_h2_navigate(Some(req.method().clone()))
429                                .inspect_err(|err| {
430                                    tracing::trace!(
431                                        "ja4h computation of matched profile for incoming h2 req: {err:?}"
432                                    )
433                                })
434                                .ok(),
435                            _ => None,
436                        };
437                        if let Some(tgt) = matched_ja4h {
438                            let hash = format!("{tgt}");
439                            let matched = format!("{ja4h}") == hash;
440                            profile_ja4h = Some(FingerprintProfileData {
441                                hash,
442                                verbose: format!("{tgt:?}"),
443                                matched,
444                            });
445                        }
446                    }
447
448                json!({
449                    "hash": format!("{ja4h}"),
450                    "verbose": format!("{ja4h:?}"),
451                    "profile": profile_ja4h,
452                })
453            });
454
455        let (mut parts, body) = req.into_parts();
456
457        let body = body
458            .collect()
459            .await
460            .context("collect request body for echo purposes")?
461            .to_bytes();
462
463        let curl_request = curl::cmd_string_for_request_parts_and_payload(&parts, &body);
464
465        let headers: Vec<_> = Http1HeaderMap::new(parts.headers, Some(&mut parts.extensions))
466            .into_iter()
467            .map(|(name, value)| {
468                (
469                    name,
470                    std::str::from_utf8(value.as_bytes())
471                        .map(|s| s.to_owned())
472                        .unwrap_or_else(|_| format!("0x{:x?}", value.as_bytes())),
473                )
474            })
475            .collect();
476
477        let body = hex::encode(body.as_ref());
478
479        #[cfg(any(feature = "rustls", feature = "boring"))]
480        let tls_info = parts
481            .extensions
482            .get::<SecureTransport>()
483            .and_then(|st| st.client_hello())
484            .map(|hello| {
485                let ja4 = Ja4::compute(parts.extensions.extensions())
486                    .inspect_err(|err| tracing::trace!("ja4 computation: {err:?}"))
487                    .ok();
488
489                let mut profile_ja4: Option<FingerprintProfileData> = None;
490
491                if let Some(uadb) = self.uadb.as_deref()
492                    && let Some(profile) =
493                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
494                {
495                    let matched_ja4 = profile
496                        .tls
497                        .compute_ja4(
498                            parts
499                                .extensions
500                                .get::<NegotiatedTlsParameters>()
501                                .map(|param| param.protocol_version),
502                        )
503                        .inspect_err(|err| {
504                            tracing::trace!("ja4 computation of matched profile: {err:?}")
505                        })
506                        .ok();
507                    if let (Some(src), Some(tgt)) = (ja4.as_ref(), matched_ja4) {
508                        let hash = format!("{tgt}");
509                        let matched = format!("{src}") == hash;
510                        profile_ja4 = Some(FingerprintProfileData {
511                            hash,
512                            verbose: format!("{tgt:?}"),
513                            matched,
514                        });
515                    }
516                }
517
518                let ja4 = ja4.map(|ja4| {
519                    json!({
520                        "hash": format!("{ja4}"),
521                        "verbose": format!("{ja4:?}"),
522                        "profile": profile_ja4,
523                    })
524                });
525
526                let ja3 = Ja3::compute(parts.extensions.extensions())
527                    .inspect_err(|err| tracing::trace!("ja3 computation: {err:?}"))
528                    .ok();
529
530                let mut profile_ja3: Option<FingerprintProfileData> = None;
531
532                if let Some(uadb) = self.uadb.as_deref()
533                    && let Some(profile) =
534                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
535                {
536                    let matched_ja3 = profile
537                        .tls
538                        .compute_ja3(
539                            parts
540                                .extensions
541                                .get::<NegotiatedTlsParameters>()
542                                .map(|param| param.protocol_version),
543                        )
544                        .inspect_err(|err| {
545                            tracing::trace!("ja3 computation of matched profile: {err:?}")
546                        })
547                        .ok();
548                    if let (Some(src), Some(tgt)) = (ja3.as_ref(), matched_ja3) {
549                        let hash = format!("{tgt:x}");
550                        let matched = format!("{src:x}") == hash;
551                        profile_ja3 = Some(FingerprintProfileData {
552                            hash,
553                            verbose: format!("{tgt}"),
554                            matched,
555                        });
556                    }
557                }
558
559                let ja3 = ja3.map(|ja3| {
560                    json!({
561                        "hash": format!("{ja3:x}"),
562                        "verbose": format!("{ja3}"),
563                        "profile": profile_ja3,
564                    })
565                });
566
567                let peet = PeetPrint::compute(parts.extensions.extensions())
568                    .inspect_err(|err| tracing::trace!("peet computation: {err:?}"))
569                    .ok();
570
571                let mut profile_peet: Option<FingerprintProfileData> = None;
572
573                if let Some(uadb) = self.uadb.as_deref()
574                    && let Some(profile) =
575                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
576                {
577                    let matched_peet = profile
578                        .tls
579                        .compute_peet()
580                        .inspect_err(|err| {
581                            tracing::trace!("peetprint computation of matched profile: {err:?}")
582                        })
583                        .ok();
584                    if let (Some(src), Some(tgt)) = (peet.as_ref(), matched_peet) {
585                        let hash = format!("{tgt}");
586                        let matched = format!("{src}") == hash;
587                        profile_peet = Some(FingerprintProfileData {
588                            hash,
589                            verbose: format!("{tgt:?}"),
590                            matched,
591                        });
592                    }
593                }
594
595                let peet = peet.map(|peet| {
596                    json!({
597                        "hash": format!("{peet}"),
598                        "verbose": format!("{peet:?}"),
599                        "profile": profile_peet,
600                    })
601                });
602
603                json!({
604                    "header": {
605                        "version": hello.protocol_version().to_string(),
606                        "cipher_suites": hello
607                        .cipher_suites().iter().map(|s| s.to_string()).collect::<Vec<_>>(),
608                        "compression_algorithms": hello
609                        .compression_algorithms().iter().map(|s| s.to_string()).collect::<Vec<_>>(),
610                    },
611                    "extensions": hello.extensions().iter().map(|extension| match extension {
612                        ClientHelloExtension::ServerName(domain) => json!({
613                            "id": extension.id().to_string(),
614                            "data": domain,
615                        }),
616                        ClientHelloExtension::SignatureAlgorithms(v) => json!({
617                            "id": extension.id().to_string(),
618                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
619                        }),
620                        ClientHelloExtension::SupportedVersions(v) => json!({
621                            "id": extension.id().to_string(),
622                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
623                        }),
624                        ClientHelloExtension::ApplicationLayerProtocolNegotiation(v) => json!({
625                            "id": extension.id().to_string(),
626                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
627                        }),
628                        ClientHelloExtension::ApplicationSettings(v) => json!({
629                            "id": extension.id().to_string(),
630                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
631                        }),
632                        ClientHelloExtension::SupportedGroups(v) => json!({
633                            "id": extension.id().to_string(),
634                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
635                        }),
636                        ClientHelloExtension::ECPointFormats(v) => json!({
637                            "id": extension.id().to_string(),
638                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
639                        }),
640                        ClientHelloExtension::CertificateCompression(v) => json!({
641                            "id": extension.id().to_string(),
642                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
643                        }),
644                        ClientHelloExtension::DelegatedCredentials(v) => json!({
645                            "id": extension.id().to_string(),
646                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
647                        }),
648                        ClientHelloExtension::RecordSizeLimit(v) => json!({
649                            "id": extension.id().to_string(),
650                            "data": v.to_string(),
651                        }),
652                        ClientHelloExtension::EncryptedClientHello(ech) => match ech {
653                            ECHClientHello::Outer(ech) => json!({
654                                "id": extension.id().to_string(),
655                                "data": {
656                                    "type": "outer",
657                                    "cipher_suite": {
658                                        "aead_id": ech.cipher_suite.aead_id.to_string(),
659                                        "kdf_id": ech.cipher_suite.kdf_id.to_string(),
660                                    },
661                                    "config_id": ech.config_id,
662                                    "enc":  format!("0x{}", hex::encode(&ech.enc)),
663                                    "payload": format!("0x{}", hex::encode(&ech.payload)),
664                                },
665                            }),
666                            ECHClientHello::Inner => json!({
667                                "id": extension.id().to_string(),
668                                "data": {
669                                    "type": "inner",
670                                },
671                            })
672
673                        }
674                        ClientHelloExtension::Opaque { id, data } => if data.is_empty() {
675                            json!({
676                                "id": id.to_string()
677                            })
678                        } else {
679                            json!({
680                                "id": id.to_string(),
681                                "data": format!("0x{}", hex::encode(data))
682                            })
683                        },
684                    }).collect::<Vec<_>>(),
685                    "ja3": ja3,
686                    "ja4": ja4,
687                    "peet": peet
688                })
689            });
690
691        #[cfg(not(any(feature = "rustls", feature = "boring")))]
692        let tls_info: Option<()> = None;
693
694        let mut h2 = None;
695        if parts.version == Version::HTTP_2 {
696            let early_frames = parts.extensions.get::<EarlyFrameCapture>();
697            let pseudo_headers = parts.extensions.get::<PseudoHeaderOrder>();
698            let akamai_h2 = AkamaiH2::compute(&parts.extensions)
699                .inspect_err(|err| tracing::trace!("akamai h2 compute failure: {err:?}"))
700                .ok()
701                .map(|akamai| {
702                    json!({
703                        "hash": format!("{akamai}"),
704                        "verbose": format!("{akamai:?}"),
705                    })
706                });
707
708            h2 = Some(json!({
709                "early_frames": early_frames,
710                "pseudo_headers": pseudo_headers,
711                "akamai_h2": akamai_h2,
712            }));
713        }
714
715        Ok(Json(json!({
716            "ua": user_agent_info,
717            "http": {
718                "version": format!("{:?}", parts.version),
719                "scheme": scheme,
720                "method": format!("{:?}", parts.method),
721                "authority": authority,
722                "path": parts.uri.path().to_owned(),
723                "query": parts.uri.query().map(str::to_owned),
724                "h2": h2,
725                "headers": headers,
726                "payload": body,
727                "ja4h": ja4h,
728                "curl": curl_request,
729            },
730            "tls": tls_info,
731            "socket_addr": parts.extensions.get::<Forwarded>()
732                .and_then(|f|
733                        f.client_socket_addr().map(|addr| addr.to_string())
734                            .or_else(|| f.client_ip().map(|ip| ip.to_string()))
735                ).or_else(|| parts.extensions.get::<SocketInfo>().map(|v| v.peer_addr().to_string())),
736        }))
737        .into_response())
738    }
739}