rama 0.3.0-rc1

modular service framework
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! IP '[`Service`] that echos the client IP either over http or directly over tcp.
//!
//! [`Service`]: crate::Service

#![expect(
    clippy::allow_attributes,
    reason = "feature-gated `mut self` consumed by some cfg branches but not others β€” `#[allow(unused_mut)]` would warn unfulfilled in the cfg arm where it IS used"
)]

use crate::{
    Layer, Service,
    cli::ForwardKind,
    combinators::Either,
    combinators::Either7,
    error::{BoxError, BoxErrorExt, ErrorExt as _},
    extensions::ExtensionsRef,
    http::BodyLimitLayer,
    http::{
        Request, Response, StatusCode,
        headers::exotic::XClacksOverhead,
        headers::forwarded::{CFConnectingIp, ClientIp, TrueClientIp, XClientIp, XRealIp},
        headers::{Accept, HeaderMapExt},
        layer::{
            forwarded::GetForwardedHeaderLayer, required_header::AddRequiredResponseHeadersLayer,
            set_header::SetResponseHeaderLayer, trace::TraceLayer,
        },
        mime,
        server::HttpServer,
        service::web::response::{Css, IntoResponse, Json, Redirect, Script},
    },
    io::Io,
    layer::limit::policy::UnlimitedPolicy,
    layer::{ConsumeErrLayer, LimitLayer, TimeoutLayer, limit::policy::ConcurrentPolicy},
    net::address::ip::geo::{GeoLocation, IpGeoDb, IpGeoInfo},
    net::forwarded::Forwarded,
    net::stream::SocketInfo,
    proxy::haproxy::server::HaProxyLayer,
    rt::Executor,
    tcp::TcpStream,
    telemetry::tracing,
    utils::octets::mib,
};

use std::{convert::Infallible, marker::PhantomData, net::IpAddr, sync::Arc, time::Duration};
use tokio::io::AsyncWriteExt;

core::cfg_select! {
    feature = "boring" => {
        use crate::tls::boring::server::TlsAcceptorLayer;
    }
    feature = "rustls" => {
        use crate::tls::rustls::server::TlsAcceptorLayer;
    }
    _ => {}
}

#[cfg(any(feature = "rustls", feature = "boring"))]
use crate::{http::headers::StrictTransportSecurity, tls::server::TlsServerConfig};

#[derive(Debug, Clone)]
/// Builder that can be used to run your own ip [`Service`],
/// echo'ing back the client IP over http or tcp.
pub struct IpServiceBuilder<M> {
    #[cfg(any(feature = "rustls", feature = "boring"))]
    tls_server_config: Option<TlsServerConfig>,
    concurrent_limit: usize,
    timeout: Duration,
    forward: Option<ForwardKind>,
    geo_db: Option<Arc<IpGeoDb>>,
    _mode: PhantomData<fn(M)>,
}

impl IpServiceBuilder<mode::Http> {
    /// Create a new [`IpServiceBuilder`], echoing the IP back over L4.
    #[must_use]
    pub fn http() -> Self {
        Self {
            #[cfg(any(feature = "rustls", feature = "boring"))]
            tls_server_config: None,
            concurrent_limit: 0,
            timeout: Duration::ZERO,
            forward: None,
            geo_db: None,
            _mode: PhantomData,
        }
    }
}

impl IpServiceBuilder<mode::Transport> {
    /// Create a new [`IpServiceBuilder`], echoing the IP back over L4.
    #[must_use]
    pub fn tcp() -> Self {
        Self {
            #[cfg(any(feature = "rustls", feature = "boring"))]
            tls_server_config: None,
            concurrent_limit: 0,
            timeout: Duration::ZERO,
            forward: None,
            geo_db: None,
            _mode: PhantomData,
        }
    }
}

impl<M> IpServiceBuilder<M> {
    crate::utils::macros::generate_set_and_with! {
        /// set the number of concurrent connections to allow
        #[must_use]
        pub fn concurrent(mut self, limit: usize) -> Self {
            self.concurrent_limit = limit;
            self
        }
    }

    crate::utils::macros::generate_set_and_with! {
        /// set the timeout in seconds for each connection
        #[must_use]
        pub fn timeout(mut self, timeout: Duration) -> Self {
            self.timeout = timeout;
            self
        }
    }

    crate::utils::macros::generate_set_and_with! {
        /// maybe enable support for one of the following "forward" headers or protocols
        ///
        /// Supported headers:
        ///
        /// Forwarded ("for="), X-Forwarded-For
        ///
        /// X-Client-IP Client-IP, X-Real-IP
        ///
        /// CF-Connecting-IP, True-Client-IP
        ///
        /// Or using HaProxy protocol.
        #[must_use]
        pub fn forward(mut self, maybe_kind: Option<ForwardKind>) -> Self {
            self.forward = maybe_kind;
            self
        }
    }

    crate::utils::macros::generate_set_and_with! {
        /// attach an IP geolocation database, enabling geo enrichment of the
        /// HTTP (JSON) response. Typically built from `RAMA_IP_GEO_DB`.
        #[must_use]
        pub fn geo_db(mut self, db: Option<Arc<IpGeoDb>>) -> Self {
            self.geo_db = db;
            self
        }
    }

    crate::utils::macros::generate_set_and_with! {
        #[cfg(any(feature = "rustls", feature = "boring"))]
        /// define a tls server cert config to be used for tls terminaton
        /// by the IP service.
        pub fn tls_server_config(mut self, cfg: Option<TlsServerConfig>) -> Self {
            self.tls_server_config = cfg;
            self
        }
    }
}

impl IpServiceBuilder<mode::Http> {
    #[allow(unused_mut)]
    #[inline]
    /// build a tcp service ready to echo the client IP back
    pub fn build(
        mut self,
        executor: Executor,
    ) -> Result<impl Service<TcpStream, Output = (), Error = Infallible>, BoxError> {
        #[cfg(any(feature = "rustls", feature = "boring"))]
        {
            let maybe_tls_acceptor_layer = self.tls_server_config.take().map(TlsAcceptorLayer::new);
            self.build_http(executor, maybe_tls_acceptor_layer)
        }

        #[cfg(not(any(feature = "rustls", feature = "boring")))]
        self.build_http(executor)
    }
}

#[derive(Debug, Clone)]
/// The inner http ip-service used by the [`IpServiceBuilder`]. Mounted at
/// `/` by the surrounding [`crate::http::service::web::Router`] in
/// [`IpServiceBuilder::build_http`]; the asset sidecars are sibling
/// routes on the same router.
struct HttpIpService {
    /// Optional geolocation database; when present, the JSON response is
    /// enriched with the resolved location (merged + per-source).
    geo_db: Option<Arc<IpGeoDb>>,
}

impl Service<Request> for HttpIpService {
    type Output = Response;
    type Error = Infallible;

    async fn serve(&self, req: Request) -> Result<Self::Output, Self::Error> {
        let peer_ip = req
            .extensions()
            .get_ref::<Forwarded>()
            .and_then(|f| f.client_ip())
            .or_else(|| {
                req.extensions()
                    .get_ref::<SocketInfo>()
                    .map(|s| s.peer_addr().ip_addr)
            });

        Ok(match peer_ip {
            Some(ip) => match HttpBodyContentFormat::derive_from_req(&req) {
                HttpBodyContentFormat::Txt => ip.to_string().into_response(),
                HttpBodyContentFormat::Html => {
                    let geo = self.geo_db.as_ref().and_then(|db| db.resolve(ip));
                    let attributions: Vec<_> = self
                        .geo_db
                        .as_ref()
                        .map(|db| db.attributions().collect())
                        .unwrap_or_default();
                    render_html_page(ip, geo.as_ref(), &attributions).into_response()
                }
                HttpBodyContentFormat::Json => {
                    let geo = self.geo_db.as_ref().and_then(|db| db.resolve(ip));
                    let mut body = serde_json::json!({ "ip": ip });
                    if let Some(info) = geo {
                        // attribution rides in the x-geo-attribution header, not the body
                        body["geo"] = serde_json::to_value(&info).unwrap_or_default();
                    }
                    Json(body).into_response()
                }
            },
            None => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
        })
    }
}

/// Sidecar stylesheet for the HTML page. Served as a separate route so
/// the defence-in-depth CSP can keep `style-src 'self'` (blocking
/// inline `<style>`) without breaking the page.
const IP_STYLE_CSS: &str = include_str!("ip.css");

/// Sidecar clipboard-copy script. Served separately for the same
/// reason as [`IP_STYLE_CSS`] (`script-src 'self'`).
const IP_SCRIPT_JS: &str = include_str!("ip.js");

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum HttpBodyContentFormat {
    #[default]
    Txt,
    Html,
    Json,
}

impl HttpBodyContentFormat {
    fn derive_from_req(req: &Request) -> Self {
        let Some(accept) = req.headers().typed_get::<Accept>() else {
            return Self::default();
        };
        // honour q-values: try the most-preferred media types first (stable
        // sort, so equal-quality entries keep their header order)
        let mut entries: Vec<_> = accept.0.iter().collect();
        entries.sort_by_key(|qv| std::cmp::Reverse(qv.quality));
        entries
            .into_iter()
            .find_map(|qv| {
                let r#type = qv.value.subtype();
                if r#type == mime::JSON {
                    Some(Self::Json)
                } else if r#type == mime::HTML {
                    Some(Self::Html)
                } else if r#type == mime::TEXT {
                    Some(Self::Txt)
                } else {
                    None
                }
            })
            .unwrap_or_default()
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
/// The inner tcp echo-service used by the [`IpServiceBuilder`].
struct TcpIpService;

impl<Input> Service<Input> for TcpIpService
where
    Input: Io + Unpin + ExtensionsRef,
{
    type Output = ();
    type Error = BoxError;

    async fn serve(&self, stream: Input) -> Result<Self::Output, Self::Error> {
        tracing::info!("connection received");
        let peer_ip = stream
            .extensions()
            .get_ref::<Forwarded>()
            .and_then(|f| f.client_ip())
            .or_else(|| {
                stream
                    .extensions()
                    .get_ref::<SocketInfo>()
                    .map(|s| s.peer_addr().ip_addr)
            });
        let Some(peer_ip) = peer_ip else {
            tracing::error!("missing peer information");
            return Ok(());
        };

        let mut stream = std::pin::pin!(stream);

        match peer_ip {
            std::net::IpAddr::V4(ip) => {
                if let Err(err) = stream.write_all(&ip.octets()).await {
                    tracing::error!("error writing IPv4 of peer to peer: {}", err);
                }
            }
            std::net::IpAddr::V6(ip) => {
                if let Err(err) = stream.write_all(&ip.octets()).await {
                    tracing::error!("error writing IPv6 of peer to peer: {}", err);
                }
            }
        };

        Ok(())
    }
}

impl IpServiceBuilder<mode::Transport> {
    #[allow(unused_mut)]
    #[inline]
    /// build a tcp service ready to echo client IP back
    pub fn build(
        mut self,
    ) -> Result<impl Service<TcpStream, Output = (), Error = Infallible>, BoxError> {
        #[cfg(any(feature = "rustls", feature = "boring"))]
        {
            let maybe_tls_acceptor_layer = self.tls_server_config.take().map(TlsAcceptorLayer::new);
            self.build_tcp(maybe_tls_acceptor_layer)
        }

        #[cfg(not(any(feature = "rustls", feature = "boring")))]
        self.build_tcp()
    }
}

impl<M> IpServiceBuilder<M> {
    fn build_tcp<S: Io + ExtensionsRef + Unpin + Sync>(
        self,
        #[cfg(any(feature = "rustls", feature = "boring"))] maybe_tls_accept_layer: Option<
            TlsAcceptorLayer,
        >,
    ) -> Result<impl Service<S, Output = (), Error = Infallible>, BoxError> {
        let tcp_forwarded_layer = match &self.forward {
            None => None,
            Some(ForwardKind::HaProxy) => Some(HaProxyLayer::default()),
            Some(other) => {
                return Err(
                    BoxError::from_static_str("invalid forward kind for Transport mode")
                        .with_context_debug_field("kind", || other.clone()),
                );
            }
        };

        let tcp_service_builder = (
            ConsumeErrLayer::trace_as(tracing::Level::DEBUG),
            LimitLayer::new(if self.concurrent_limit > 0 {
                Either::A(ConcurrentPolicy::max(self.concurrent_limit))
            } else {
                Either::B(UnlimitedPolicy::new())
            }),
            if !self.timeout.is_zero() {
                TimeoutLayer::new(self.timeout)
            } else {
                TimeoutLayer::never()
            },
            tcp_forwarded_layer,
            #[cfg(any(feature = "rustls", feature = "boring"))]
            maybe_tls_accept_layer,
        );

        Ok(tcp_service_builder.into_layer(TcpIpService))
    }

    fn build_http<S: Io + Unpin + Sync + ExtensionsRef>(
        self,
        executor: Executor,
        #[cfg(any(feature = "rustls", feature = "boring"))] maybe_tls_accept_layer: Option<
            TlsAcceptorLayer,
        >,
    ) -> Result<impl Service<S, Output = (), Error = Infallible>, BoxError> {
        let (tcp_forwarded_layer, http_forwarded_layer) = match &self.forward {
            None => (None, None),
            Some(ForwardKind::Forwarded) => {
                (None, Some(Either7::A(GetForwardedHeaderLayer::forwarded())))
            }
            Some(ForwardKind::XForwardedFor) => (
                None,
                Some(Either7::B(GetForwardedHeaderLayer::x_forwarded_for())),
            ),
            Some(ForwardKind::XClientIp) => (
                None,
                Some(Either7::C(GetForwardedHeaderLayer::<XClientIp>::new())),
            ),
            Some(ForwardKind::ClientIp) => (
                None,
                Some(Either7::D(GetForwardedHeaderLayer::<ClientIp>::new())),
            ),
            Some(ForwardKind::XRealIp) => (
                None,
                Some(Either7::E(GetForwardedHeaderLayer::<XRealIp>::new())),
            ),
            Some(ForwardKind::CFConnectingIp) => (
                None,
                Some(Either7::F(GetForwardedHeaderLayer::<CFConnectingIp>::new())),
            ),
            Some(ForwardKind::TrueClientIp) => (
                None,
                Some(Either7::G(GetForwardedHeaderLayer::<TrueClientIp>::new())),
            ),
            Some(ForwardKind::HaProxy) => (Some(HaProxyLayer::default()), None),
        };

        #[cfg(any(feature = "rustls", feature = "boring"))]
        let hsts_layer = maybe_tls_accept_layer.is_some().then(|| {
            SetResponseHeaderLayer::if_not_present_typed(
                StrictTransportSecurity::excluding_subdomains_for_max_seconds(31536000),
            )
        });

        let tcp_service_builder = (
            ConsumeErrLayer::trace_as(tracing::Level::DEBUG),
            (self.concurrent_limit > 0)
                .then(|| LimitLayer::new(ConcurrentPolicy::max(self.concurrent_limit))),
            (!self.timeout.is_zero()).then(|| TimeoutLayer::new(self.timeout)),
            tcp_forwarded_layer,
            // Limit the body size to 1MB for requests
            BodyLimitLayer::request_only(mib(1)),
            #[cfg(any(feature = "rustls", feature = "boring"))]
            maybe_tls_accept_layer,
        );

        // Defence-in-depth response headers for the HTML page (txt/json
        // responses also get them β€” they're benign there and means
        // any future widening of HTML emission is already covered).
        // The page loads `/style/ip.css` and `/script/ip.js` from the
        // same origin, no inline scripts/styles, no external requests:
        // the strict-self baseline (banner image whitelisted in the
        // shared helper) covers it.
        let (csp_layer, nosniff_layer, referrer_layer, frame_layer) =
            crate::cli::service::http_security::defence_in_depth_layer(
                crate::cli::service::http_security::rama_html_csp(),
            );

        // Attribution header, derived from the loaded databases' notices.
        let geo_attribution = self.geo_db.as_ref().and_then(|db| {
            let notices: Vec<_> = db.attributions().collect();
            (!notices.is_empty()).then(|| crate::cli::service::geo::geo_attribution_layer(notices))
        });

        // Route the IP echo + its asset sidecars through a Router so we
        // get clean method-aware matching (anything outside the three
        // known routes redirects to `/`).
        let router = crate::http::service::web::Router::new()
            .with_get(
                "/",
                HttpIpService {
                    geo_db: self.geo_db,
                },
            )
            .with_get("/style/ip.css", Css(IP_STYLE_CSS))
            .with_get("/script/ip.js", Script(IP_SCRIPT_JS))
            .with_not_found(async || Redirect::permanent("/"));

        let http_service = (
            TraceLayer::new_for_http(),
            SetResponseHeaderLayer::<XClacksOverhead>::if_not_present_default_typed(),
            AddRequiredResponseHeadersLayer::default(),
            geo_attribution,
            csp_layer,
            nosniff_layer,
            referrer_layer,
            frame_layer,
            ConsumeErrLayer::default(),
            #[cfg(any(feature = "rustls", feature = "boring"))]
            hsts_layer,
            http_forwarded_layer,
        )
            .into_layer(router);

        // Wrap in `Arc` because `Router` is not `Clone` and
        // `HttpServer::service` requires a cloneable inner service so it
        // can hand a copy to each connection's task.
        let http_service = Arc::new(http_service);
        Ok(tcp_service_builder.into_layer(HttpServer::auto(executor).service(http_service)))
    }
}

pub mod mode {
    //! operation modes of the ip service

    #[derive(Debug, Clone)]
    #[non_exhaustive]
    /// Default mode of the Ip service, echo'ng the info back over http
    pub struct Http;

    #[derive(Debug, Clone)]
    #[non_exhaustive]
    /// Alternative mode of the Ip service, echo'ng the ip info over tcp
    pub struct Transport;
}

fn render_html_page(
    ip: IpAddr,
    geo: Option<&IpGeoInfo>,
    attributions: &[&str],
) -> impl crate::http::protocols::html::IntoHtml + IntoResponse {
    use crate::http::protocols::html::*;

    // attribution comment from the loaded databases; geo panel when resolved
    let geo_comment =
        crate::cli::service::geo::geo_attribution_html_comment(attributions).map(PreEscaped);
    let geo_panel = geo.map(|info| {
        let rows = |loc: &GeoLocation| {
            crate::cli::service::geo::geo_location_rows(loc)
                .into_iter()
                .map(|(k, v)| div!(class = "georow", div!(class = "muted", k), div!(code!(v))))
                .collect::<Vec<_>>()
        };
        // merged result + one card per source, laid out in a responsive grid
        let card = |label: String, loc: &GeoLocation| {
            div!(
                class = "panel geo-card",
                div!(class = "muted geo-source", label),
                rows(loc),
            )
        };
        let mut cards = vec![card("merged".to_owned(), &info.location)];
        cards.extend(
            info.by_source
                .iter()
                .map(|src| card(src.label.to_string(), &src.location)),
        );
        div!(
            class = "geo-section",
            role = "region",
            "aria-label" = "geo panel",
            div!(class = "muted geo-title", "Geolocation"),
            div!(class = "geo-grid", cards),
        )
    });

    html!(
        lang = "en",
        head!(
            meta!(charset = "utf-8"),
            meta!(
                name = "viewport",
                content = "width=device-width,initial-scale=1"
            ),
            link!(
                rel = "icon",
                href = PreEscaped(
                    "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'>\
                     <text y='0.9em' font-size='90'>πŸ¦™</text></svg>"
                ),
            ),
            title!("Rama IP"),
            link!(
                rel = "stylesheet",
                r#type = "text/css",
                href = "/style/ip.css"
            ),
        ),
        body!(
            geo_comment,
            div!(
                class = "card",
                div!(
                    class = "logo",
                    div!("πŸ¦™"),
                    div!(a!(href = "https://ramaproxy.org", "γƒ©γƒž")),
                ),
                div!(
                    class = "panel",
                    role = "region",
                    "aria-label" = "ip panel",
                    div!(class = "muted", "Your public ip"),
                    div!(id = "ip", class = "ip", code!(ip.to_string())),
                    div!(
                        class = "controls",
                        button!(
                            id = "copyBtn",
                            class = "primary",
                            title = "Copy ip to clipboard",
                            "πŸ“‹ Copy IP",
                        ),
                    ),
                ),
                geo_panel,
                script!(src = "/script/ip.js"),
            )
        ),
    )
}

#[cfg(test)]
mod render_html_page_tests {
    use super::*;
    use crate::http::protocols::html::IntoHtml as _;
    use std::net::Ipv4Addr;

    /// The IP value flows through `html!`'s escape pipeline, so even if a
    /// future `IpAddr::Display` impl produced HTML-special chars they would
    /// be neutralised. Verify the rendered page contains the expected IP
    /// inside `<code>…</code>` and that the page chrome is well-formed.
    #[test]
    fn render_html_page_embeds_ip_safely() {
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let out = render_html_page(ip, None, &[]).into_string();
        assert!(out.starts_with("<!DOCTYPE html><html lang=\"en\">"));
        assert!(out.contains("<title>Rama IP</title>"));
        assert!(out.contains(r#"<div id="ip" class="ip"><code>127.0.0.1</code></div>"#));
        // Copy button is wired by selector ID in the inline script.
        assert!(out.contains(r#"id="copyBtn""#));
    }

    /// The aria-label attribute uses the `"aria-label" = …` syntax (since
    /// `aria-label` is not a Rust ident). Pin the rendered output.
    #[test]
    fn render_html_page_emits_aria_label() {
        let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1));
        let out = render_html_page(ip, None, &[]).into_string();
        assert!(out.contains(r#"aria-label="ip panel""#));
    }

    /// Regression guard against the bug audited 2026-05-18: the IP page
    /// must reference its CSS and JS via `<link>` / `<script src>`
    /// because the surrounding service applies `style-src 'self'` and
    /// `script-src 'self'` β€” an inline `<style>` or `<script>` block
    /// would be blocked at the browser.
    #[test]
    fn render_html_page_uses_external_assets() {
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let out = render_html_page(ip, None, &[]).into_string();
        assert!(
            !out.contains("<style>") && !out.contains("<style "),
            "IP page must not embed inline <style>; CSP blocks it"
        );
        // The renderer is allowed to emit a self-closing `<script src=...>`,
        // but never an inline `<script>...JS...</script>` body.
        assert!(
            !out.contains("<script>"),
            "IP page must not embed inline <script>; CSP blocks it"
        );
        assert!(
            out.contains(r#"<link rel="stylesheet" type="text/css" href="/style/ip.css">"#),
            "IP page must link to /style/ip.css",
        );
        assert!(
            out.contains(r#"<script src="/script/ip.js">"#),
            "IP page must source /script/ip.js",
        );
    }

    /// When a location is resolved, the page renders a geo panel (merged +
    /// per-source) and embeds the attribution as an HTML comment.
    #[test]
    fn render_html_page_renders_geo_panel() {
        use crate::geo::Country;
        use crate::net::address::ip::geo::{GeoLocation, IpGeoInfo, IpGeoSourceResult};
        let ip = IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4));
        let loc = GeoLocation {
            country: Some(Country::Belgium),
            ..Default::default()
        };
        let info = IpGeoInfo {
            ip,
            location: loc.clone(),
            by_source: vec![IpGeoSourceResult {
                label: "geolite2".into(),
                location: loc,
            }],
        };
        let notices = ["This product includes GeoLite2 data created by MaxMind"];
        let out = render_html_page(ip, Some(&info), &notices).into_string();
        assert!(out.contains("Geolocation"), "geo panel title missing");
        assert!(out.contains("Belgium"), "resolved country missing");
        assert!(out.contains("geolite2"), "per-source label missing");
        // attribution is an HTML comment, never visible structured data
        assert!(
            out.contains("<!-- This product includes GeoLite2"),
            "attribution comment missing"
        );

        // …and absent when no database is configured
        let plain = render_html_page(ip, None, &[]).into_string();
        assert!(!plain.contains("Geolocation"));
        assert!(!plain.contains("<!--"));
    }
}