hypershunt 1.1.0

HTTP server and reverse proxy
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
// Built-in server status page: serves request counters, latency
// histogram, sparklines, and top-path tables as HTML or JSON.
//
// HTML uses a sticky sidebar navigation (matching the hypershunt docs
// style), an inline time-period selector, and JavaScript polling
// (?format=json&period=<p> every 3 s) for live updates.
//
// JSON output supports ?period=<p> to return period-specific
// sparkline and path data.

use crate::cert::state::{CertState, SharedCertState};
use crate::config::{AuthBackend, Config, HandlerConfig, TlsConfig};
use crate::error::HttpResponse;
use crate::error::ReqBody;
use crate::handler::Handler;
use crate::headers::RequestContext;
use crate::metrics::{Metrics, TimePeriod};
use async_trait::async_trait;
use hyper::Request;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

mod render_html;
mod render_json;


// -- Server summary ------------------------------------------------

pub struct ListenerSummary {
    pub address: String,
    /// "HTTP", "HTTPS-file", "HTTPS-self-signed", "HTTPS-ACME", "stream", …
    pub protocol: String,
    pub acme_domains: Vec<String>,
    pub max_connections: Option<u32>,
    pub handler_timeout_secs: Option<u64>,
}

pub struct LocationSummary {
    pub path: String,
    pub handler: String,
}

pub struct VHostSummary {
    pub name: String,
    pub aliases: Vec<String>,
    pub locations: Vec<LocationSummary>,
}

pub struct ServerSummary {
    pub version: &'static str,
    pub listeners: Vec<ListenerSummary>,
    pub vhosts: Vec<VHostSummary>,
    /// Structured auth description for the status page.
    pub auth: Option<AuthDesc>,
}

/// Human-readable description of the configured auth backend.
pub struct AuthDesc {
    /// Short type label: "PAM", "LDAP", "Subrequest", "JWT".
    pub kind: &'static str,
    /// Backend address / service name / URL.
    pub detail: String,
    /// True when a JWT session layer wraps another backend.
    pub has_jwt_session: bool,
    /// Validity in seconds when JWT session mode is active.
    pub jwt_validity_secs: Option<u64>,
}

impl ServerSummary {
    pub fn from_config(config: &Config) -> Self {
        let listeners = config
            .listeners
            .iter()
            .map(|l| {
                let (protocol, acme_domains) = listener_protocol(l, config);
                ListenerSummary {
                    address: l.bind.to_url(),
                    protocol,
                    acme_domains,
                    max_connections: l.max_connections,
                    handler_timeout_secs: l.timeouts.handler_secs,
                }
            })
            .collect();

        let vhosts = config
            .vhosts
            .iter()
            .map(|v| VHostSummary {
                name: v.name.value.clone(),
                aliases: v.aliases.iter().map(|a| a.value.clone()).collect(),
                locations: v
                    .locations
                    .iter()
                    .map(|loc| LocationSummary {
                        path: loc.path.clone(),
                        handler: handler_type_name(&loc.handler).to_owned(),
                    })
                    .collect(),
            })
            .collect();

        let auth = config.server.auth.as_ref().map(auth_desc);

        ServerSummary { version: env!("CARGO_PKG_VERSION"), listeners, vhosts, auth }
    }

}

fn auth_desc(b: &AuthBackend) -> AuthDesc {
    match b {
        AuthBackend::Pam { service, .. } => AuthDesc {
            kind: "PAM",
            detail: service.clone(),
            has_jwt_session: false,
            jwt_validity_secs: None,
        },
        AuthBackend::Ldap(c) => AuthDesc {
            kind: "LDAP",
            detail: c.url.clone(),
            has_jwt_session: false,
            jwt_validity_secs: None,
        },
        AuthBackend::File(c) => AuthDesc {
            kind: "File",
            detail: c.path.clone(),
            has_jwt_session: false,
            jwt_validity_secs: None,
        },
        AuthBackend::Subrequest(c) => AuthDesc {
            kind: "Subrequest",
            detail: c.url.clone(),
            has_jwt_session: false,
            jwt_validity_secs: None,
        },
        AuthBackend::Oidc(c) => AuthDesc {
            kind: "OIDC",
            detail: c.issuer.clone(),
            has_jwt_session: false,
            jwt_validity_secs: None,
        },
        AuthBackend::Jwt { inner, validity_secs, .. } => {
            let (kind, detail, has_inner) = match inner {
                None => ("JWT", "standalone".into(), false),
                Some(inner_b) => {
                    let d = auth_desc(inner_b);
                    (d.kind, d.detail, true)
                }
            };
            AuthDesc {
                kind,
                detail,
                has_jwt_session: has_inner,
                jwt_validity_secs: Some(*validity_secs),
            }
        }
    }
}

fn listener_protocol(
    l: &crate::config::ListenerConfig,
    config: &Config,
) -> (String, Vec<String>) {
    let kind = l.bind.kind;
    let has_proxy = l.proxy.is_some();
    // Datagram-stream listeners.  On udp:// a `tls` block -> HTTP/3;
    // otherwise raw dgram-proxy.  DTLS termination would slot in here
    // but is currently reserved (validate rejects).
    if kind.is_datagram_stream() {
        return match (&l.tls, has_proxy) {
            (Some(tls), false) => tls_protocol_name(tls, "HTTP/3", config),
            (None, true) => ("dgram-proxy".into(), Vec::new()),
            _ => ("HTTP/3".into(), Vec::new()),
        };
    }
    // Byte-stream listeners.
    if has_proxy {
        match &l.tls {
            None => ("stream".into(), Vec::new()),
            Some(tls) => tls_protocol_name(tls, "TLS-stream", config),
        }
    } else {
        match &l.tls {
            None => ("HTTP".into(), Vec::new()),
            Some(tls) => tls_protocol_name(tls, "HTTPS", config),
        }
    }
}

fn tls_protocol_name(
    tls: &crate::config::TlsListenerConfig,
    prefix: &str,
    config: &Config,
) -> (String, Vec<String>) {
    // Follow a Ref one level to the underlying source.  After
    // validation a Ref always resolves; treat an unresolved ref as
    // "unknown" rather than panic.
    let source = config.resolve_cert(&tls.cert).unwrap_or(&tls.cert);
    match source {
        TlsConfig::Files { .. } => {
            (format!("{prefix}-file"), Vec::new())
        }
        TlsConfig::SelfSigned => {
            (format!("{prefix}-self-signed"), Vec::new())
        }
        TlsConfig::Acme { domains, .. } => {
            (format!("{prefix}-ACME"), domains.clone())
        }
        TlsConfig::Ref(_) => (format!("{prefix}-unknown"), Vec::new()),
    }
}

fn handler_type_name(h: &HandlerConfig) -> &'static str {
    match h {
        HandlerConfig::Static { .. } => "static",
        HandlerConfig::Proxy { .. } => "proxy",
        HandlerConfig::Redirect { .. } => "redirect",
        HandlerConfig::Respond { .. } => "respond",
        HandlerConfig::FastCgi { .. } => "fastcgi",
        HandlerConfig::Scgi { .. } => "scgi",
        HandlerConfig::Cgi { .. } => "cgi",
        HandlerConfig::Status => "status",
        HandlerConfig::AuthRequest => "auth-request",
    }
}

// -- Reverse-proxy pool registry -----------------------------------

/// One reverse-proxy pool plus a human label (vhost + location path),
/// collected at router-construction time so the status page can render
/// a live per-upstream health table.
pub struct LbPoolEntry {
    pub label: String,
    pub pool: Arc<crate::lb::UpstreamPool>,
}

/// Shared registry of all reverse-proxy pools.  Built fresh on every
/// router build (startup and SIGHUP), so a wholesale `AppState` swap
/// keeps the table consistent after reload — no per-entry locking.
pub type SharedLbRegistry = Arc<arc_swap::ArcSwap<Vec<LbPoolEntry>>>;

/// Flattened, point-in-time view of one upstream for the renderers.
pub struct UpstreamRow {
    pub label: String,
    pub url: String,
    pub weight: u32,
    pub in_flight: u32,
    pub healthy: bool,
    pub ejected: bool,
}

// -- Handler -------------------------------------------------------

pub(crate) struct StatusHandler {
    metrics: Arc<Metrics>,
    summary: Arc<ServerSummary>,
    cert_state: Option<SharedCertState>,
    lb_registry: Option<SharedLbRegistry>,
}

impl StatusHandler {
    pub(crate) fn new(metrics: Arc<Metrics>, summary: Arc<ServerSummary>) -> Self {
        Self { metrics, summary, cert_state: None, lb_registry: None }
    }

    pub(crate) fn with_cert_state(mut self, state: SharedCertState) -> Self {
        self.cert_state = Some(state);
        self
    }

    pub(crate) fn with_lb_registry(mut self, registry: SharedLbRegistry) -> Self {
        self.lb_registry = Some(registry);
        self
    }

    fn read_cert_states(&self) -> Vec<CertState> {
        self.cert_state.as_ref().map_or_else(Vec::new, |s| {
            s.read().unwrap_or_else(|p| p.into_inner()).clone()
        })
    }

    /// Flatten the pool registry into per-upstream rows for rendering.
    fn read_upstreams(&self) -> Vec<UpstreamRow> {
        let Some(reg) = &self.lb_registry else {
            return Vec::new();
        };
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;
        let mut rows = Vec::new();
        for entry in reg.load().iter() {
            for u in entry.pool.upstreams() {
                rows.push(UpstreamRow {
                    label: entry.label.clone(),
                    url: u.url.clone(),
                    weight: u.weight,
                    in_flight: u.in_flight(),
                    healthy: u.is_healthy(),
                    ejected: u.is_ejected(now_ms),
                });
            }
        }
        rows
    }

}

#[async_trait]
impl Handler for StatusHandler {
    async fn handle(
        &self,
        req: Request<ReqBody>,
        matched_prefix: &str,
        _ctx: &RequestContext<'_>,
    ) -> HttpResponse {
        // Brand-asset requests (the sidebar lockup and the square
        // favicon) are intercepted before content-negotiation so the
        // browser caches them independently of the page HTML.
        match req.uri().path().rsplit('/').next() {
            Some(f) if f == render_html::ICON_FILE => {
                return render_html::serve_icon(req.headers());
            }
            Some(f) if f == render_html::FAVICON_FILE => {
                return render_html::serve_favicon(req.headers());
            }
            _ => {}
        }
        let period = query_period(req.uri());
        let snap = self.metrics.snapshot();
        let sparkline = self.metrics.sparkline_for_period(period);
        let top_paths = self.metrics.paths_for_period(period);
        let certs = self.read_cert_states();
        let upstreams = self.read_upstreams();
        if accept_json(req.headers()) || query_wants_json(req.uri()) {
            render_json::render_json(
                &snap, &sparkline, &top_paths, period,
                &self.summary, &certs, &upstreams,
            )
        } else {
            render_html::render_html(
                &snap, &sparkline, &top_paths, period,
                &self.summary, &certs, &upstreams,
                matched_prefix,
            )
        }
    }
}

fn accept_json(headers: &hyper::HeaderMap) -> bool {
    headers
        .get("accept")
        .and_then(|v| v.to_str().ok())
        .map(|v| v.contains("application/json"))
        .unwrap_or(false)
}

fn query_wants_json(uri: &hyper::Uri) -> bool {
    uri.query()
        .unwrap_or("")
        .split('&')
        .any(|kv| kv == "format=json")
}

fn query_period(uri: &hyper::Uri) -> TimePeriod {
    uri.query()
        .unwrap_or("")
        .split('&')
        .find_map(|kv| {
            kv.strip_prefix("period=").map(TimePeriod::from_query)
        })
        .unwrap_or(TimePeriod::Min15)
}


// -- Tests ---------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::metrics::{Metrics, Snapshot, SparklineData, TimePeriod};
    use hyper::header::HeaderValue;

    use std::time::Duration;

    // Re-export the renderers under their unqualified names so the
    // existing test bodies (which pre-date the html/json split) keep
    // calling `render_json(...)` and `render_html(...)` directly.
    use super::render_html::{fmt_num, fmt_unix_ts, render_html};
    use super::render_json::render_json;

    fn sample_snap() -> Snapshot {
        Snapshot {
            uptime: Duration::from_secs(3661),
            requests_total: 1234,
            requests_active: 3,
            status_2xx: 1100,
            status_3xx: 80,
            status_4xx: 50,
            status_5xx: 4,
            latency: [800, 300, 100, 20, 10, 4],
            rate_current: 12.5,
            rate_1min: 10.2,
            rate_5min: 8.7,
            rate_15min: 7.1,
            memory_kb: Some(32768),
            cpu_percent: Some(5.2),
            auth_failures_total: 5,
            jwt_failures_total: 2,
            jwt_expiries_total: 1,
            jwt_issued_total: 10,
            auth_fail_1h: 1,
            jwt_fail_1h: 0,
            jwt_expiry_1h: 0,
            jwt_issued_1h: 3,
            quic_handshakes_total: 0,
            quic_handshake_failures_total: 0,
            quic_connections_active: 0,
            quic_requests_total: 0,
            quic_outbound_handshakes_total: 0,
            ..Default::default()
        }
    }

    fn sample_sparkline() -> SparklineData {
        SparklineData {
            step_secs: 5,
            req_rate: vec![1.0; 180],
            mem_kb: vec![Some(32768); 180],
            cpu_pct: vec![Some(5.0); 180],
            auth_fail: vec![0; 180],
            jwt_fail: vec![0; 180],
            jwt_expiry: vec![0; 180],
            jwt_issued: vec![0; 180],
            err4xx: vec![0; 180],
            err5xx: vec![0; 180],
            active: vec![0; 180],
        }
    }

    fn sample_summary() -> ServerSummary {
        ServerSummary {
            version: "0.0.0-test",
            listeners: vec![ListenerSummary {
                address: "0.0.0.0:80".into(),
                protocol: "HTTP".into(),
                acme_domains: Vec::new(),
                max_connections: None,
                handler_timeout_secs: None,
            }],
            vhosts: vec![VHostSummary {
                name: "example.com".into(),
                aliases: vec!["www.example.com".into()],
                locations: vec![LocationSummary {
                    path: "/".into(),
                    handler: "static".into(),
                }],
            }],
            auth: None,
        }
    }

    // -- accept_json -----------------------------------------------

    #[test]
    fn accept_json_true_for_application_json() {
        let mut map = hyper::HeaderMap::new();
        map.insert("accept", HeaderValue::from_static("application/json"));
        assert!(accept_json(&map));
    }

    #[test]
    fn accept_json_false_for_text_html() {
        let mut map = hyper::HeaderMap::new();
        map.insert("accept", HeaderValue::from_static("text/html"));
        assert!(!accept_json(&map));
    }

    #[test]
    fn accept_json_false_when_header_absent() {
        assert!(!accept_json(&hyper::HeaderMap::new()));
    }

    // -- query helpers ---------------------------------------------

    #[test]
    fn query_wants_json_true_for_format_param() {
        let uri: hyper::Uri = "/status?format=json".parse().unwrap();
        assert!(query_wants_json(&uri));
    }

    #[test]
    fn query_wants_json_true_with_other_params() {
        let uri: hyper::Uri =
            "/status?foo=bar&format=json".parse().unwrap();
        assert!(query_wants_json(&uri));
    }

    #[test]
    fn query_wants_json_false_for_no_param() {
        let uri: hyper::Uri = "/status".parse().unwrap();
        assert!(!query_wants_json(&uri));
    }

    #[test]
    fn query_period_defaults_to_min15() {
        let uri: hyper::Uri = "/status".parse().unwrap();
        assert_eq!(query_period(&uri), TimePeriod::Min15);
    }

    #[test]
    fn query_period_parses_period_param() {
        let uri: hyper::Uri = "/status?period=7d".parse().unwrap();
        assert_eq!(query_period(&uri), TimePeriod::Day7);
    }

    // -- render_json -----------------------------------------------

    #[tokio::test]
    async fn render_json_contains_required_keys() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
        );
        assert_eq!(resp.status(), 200);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let text = std::str::from_utf8(&bytes).unwrap();
        assert!(text.contains("\"uptime_secs\""));
        assert!(text.contains("\"requests_total\""));
        assert!(text.contains("\"rates\""));
        assert!(text.contains("\"latency_ms\""));
        assert!(text.contains("\"memory_kb\""));
        assert!(text.contains("\"auth_failures_total\""));
        assert!(text.contains("\"sparkline\""));
        assert!(text.contains("\"top_paths\""));
    }

    #[tokio::test]
    async fn render_json_sparkline_present() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(v["sparkline"].is_object());
        assert!(v["sparkline"]["req_rate"].is_array());
        assert_eq!(
            v["sparkline"]["req_rate"].as_array().unwrap().len(),
            180
        );
        assert_eq!(v["period"], "15min");
    }

    #[tokio::test]
    async fn render_json_top_paths_is_array() {
        use http_body_util::BodyExt;
        let paths = vec![
            ("/".to_owned(), 100u64),
            ("/api".to_owned(), 50u64),
        ];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(v["top_paths"].is_array());
        assert_eq!(v["top_paths"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn render_json_cert_state_included() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let certs = vec![CertState {
            domains: vec!["test.example.com".into()],
            expiry_ts: 9_999_999_999,
            next_renewal_ts: 9_997_406_399,
        }];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &certs,
            &[],
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(v["certs"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn render_json_auth_null_when_absent() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(v["auth"].is_null());
    }

    // -- render_html -----------------------------------------------

    #[tokio::test]
    async fn render_html_no_meta_refresh() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(
            !html.contains("http-equiv"),
            "meta refresh must be removed"
        );
    }

    #[tokio::test]
    async fn render_html_has_live_indicator() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(
            html.contains("live-dot"),
            "live indicator must be present"
        );
    }

    #[tokio::test]
    async fn render_html_contains_status_classes() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        assert_eq!(resp.status(), 200);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("2xx"), "missing 2xx label");
        assert!(html.contains("5xx"), "missing 5xx label");
        assert!(html.contains("Uptime"), "missing Uptime");
        assert!(html.contains("Request Rate"), "missing rates section");
        assert!(html.contains("Latency"), "missing latency section");
        assert!(html.contains("Memory"), "missing memory section");
    }

    #[tokio::test]
    async fn render_html_has_sparkline_ids() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("id=\"spark-rate\""));
        assert!(html.contains("id=\"spark-mem\""));
        assert!(html.contains("id=\"spark-cpu\""));
    }

    #[tokio::test]
    async fn render_html_no_memory_section_when_none() {
        use http_body_util::BodyExt;
        let mut snap = sample_snap();
        snap.memory_kb = None;
        snap.cpu_percent = None;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &snap,
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(!html.contains("sec-system"), "system section absent");
    }

    #[tokio::test]
    async fn render_html_certs_section_hidden_when_empty() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(
            html.contains("certs-section"),
            "certs section must be rendered"
        );
        assert!(
            html.contains("display:none"),
            "certs section must be hidden when empty"
        );
    }

    #[tokio::test]
    async fn render_html_certs_section_visible_when_present() {
        use http_body_util::BodyExt;
        let certs = vec![CertState {
            domains: vec!["example.com".into()],
            expiry_ts: 9_999_999_999,
            next_renewal_ts: 9_997_406_399,
        }];
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &certs,
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("TLS Certificates"));
        assert!(html.contains("example.com"));
    }

    #[tokio::test]
    async fn render_html_contains_listeners_section() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("Listeners"));
        assert!(html.contains("0.0.0.0:80"));
        assert!(html.contains("HTTP"));
    }

    #[tokio::test]
    async fn render_html_contains_vhosts_section() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("Virtual Hosts"));
        assert!(html.contains("example.com"));
    }

    #[tokio::test]
    async fn render_html_shows_version() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("0.0.0-test"));
    }

    #[tokio::test]
    async fn render_html_period_selector_present() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("period-sel"));
        assert!(html.contains("value=\"1y\""));
    }

    #[tokio::test]
    async fn render_html_security_section_when_auth_present() {
        use http_body_util::BodyExt;
        let mut sum = sample_summary();
        sum.auth = Some(AuthDesc {
            kind: "PAM",
            detail: "hypershunt".into(),
            has_jwt_session: false,
            jwt_validity_secs: None,
        });
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sum,
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("sec-security"));
        assert!(html.contains("Auth Backend"));
        assert!(html.contains("spark-auth"));
        assert!(html.contains("spark-jwt"));
    }

    // -- Newly-surfaced sections -----------------------------------

    fn stream_summary() -> ServerSummary {
        let mut s = sample_summary();
        s.listeners = vec![ListenerSummary {
            address: "0.0.0.0:5432".into(),
            protocol: "stream".into(),
            acme_domains: Vec::new(),
            max_connections: None,
            handler_timeout_secs: None,
        }];
        s
    }

    #[tokio::test]
    async fn render_json_contains_new_subsystem_keys() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value =
            serde_json::from_slice(&bytes).unwrap();
        for key in [
            "stream", "datagram", "compression", "tls", "geoip",
            "shutdown", "acme", "ocsp", "proxy_lb", "proxy_upstream",
            "rate_limit", "oidc", "http_conns", "backends", "by_handler",
            "by_vhost", "upstreams",
        ] {
            assert!(v.get(key).is_some(), "missing JSON key {key}");
        }
    }

    #[tokio::test]
    async fn render_html_proxying_hidden_when_idle() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(!html.contains("id=\"sec-proxying\""));
    }

    #[tokio::test]
    async fn render_html_proxying_shown_with_stream_listener() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &stream_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("id=\"sec-proxying\""));
        assert!(html.contains("TCP Stream Proxy"));
    }

    #[tokio::test]
    async fn render_html_compression_shown_when_active() {
        use http_body_util::BodyExt;
        let mut snap = sample_snap();
        snap.compression.responses = 5;
        snap.compression.bytes_in = 1000;
        snap.compression.bytes_out = 300;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &snap,
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("Response Compression"));
        assert!(html.contains("val-cmp-resp"));
    }

    #[tokio::test]
    async fn render_html_upstream_table_lists_rows() {
        use http_body_util::BodyExt;
        let ups = vec![UpstreamRow {
            label: "h /api".into(),
            url: "http://10.0.0.1:8080".into(),
            weight: 2,
            in_flight: 1,
            healthy: true,
            ejected: false,
        }];
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &ups,
            "",
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        assert!(html.contains("Upstream Health"));
        assert!(html.contains("http://10.0.0.1:8080"));
        assert!(html.contains("Healthy"));
    }

    #[tokio::test]
    async fn render_json_upstreams_serialized() {
        use http_body_util::BodyExt;
        let ups = vec![UpstreamRow {
            label: "h /api".into(),
            url: "http://10.0.0.1:8080".into(),
            weight: 1,
            in_flight: 0,
            healthy: false,
            ejected: true,
        }];
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_json(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &ups,
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value =
            serde_json::from_slice(&bytes).unwrap();
        let arr = v["upstreams"].as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["url"], "http://10.0.0.1:8080");
        assert_eq!(arr[0]["ejected"], true);
    }

    // -- ServerSummary::from_config --------------------------------

    fn summary_from(kdl: &str) -> ServerSummary {
        let cfg = Config::parse(kdl).unwrap();
        ServerSummary::from_config(&cfg)
    }

    #[test]
    fn summary_plain_http() {
        let s = summary_from(
            r#"
            listener "tcp://0.0.0.0:80"
            vhost "h" {
                location "/" { static root="." }
            }
        "#,
        );
        assert_eq!(s.listeners[0].protocol, "HTTP");
        assert!(s.listeners[0].acme_domains.is_empty());
        assert!(s.auth.is_none());
    }

    #[test]
    fn summary_https_file() {
        let s = summary_from(
            r#"
            listener "tcp://0.0.0.0:443" {
                tls "files" cert="cert.pem" key="key.pem"
}
            vhost "h" {
                location "/" { static root="." }
}
        "#,
        );
        assert_eq!(s.listeners[0].protocol, "HTTPS-file");
    }

    #[test]
    fn summary_https_self_signed() {
        let s = summary_from(
            r#"
            listener "tcp://0.0.0.0:443" {
                tls "self-signed"
}
            vhost "h" {
                location "/" { static root="." }
}
        "#,
        );
        assert_eq!(s.listeners[0].protocol, "HTTPS-self-signed");
    }

    #[test]
    fn summary_https_acme() {
        let s = summary_from(
            r#"
            server state-dir="/tmp/t"
            listener "tcp://[::]:443" {
                tls "acme" {
                    domain "example.com"
                    domain "www.example.com"
}
}
            vhost "h" {
                location "/" { static root="." }
            }
        "#,
        );
        assert_eq!(s.listeners[0].protocol, "HTTPS-ACME");
        assert_eq!(
            s.listeners[0].acme_domains,
            ["example.com", "www.example.com"]
        );
    }

    #[test]
    fn summary_stream_proxy() {
        let s = summary_from(
            r#"listener "tcp://[::]:5432" { proxy "tcp://127.0.0.1:5432"
}"#,
        );
        assert_eq!(s.listeners[0].protocol, "stream");
    }

    #[test]
    fn summary_tls_stream_proxy() {
        let s = summary_from(
            r#"
            listener "tcp://[::]:443" {
                tls "self-signed"
                proxy "tcp://127.0.0.1:5432"
}
            vhost "h" { location "/" { static root="." }
}
        "#,
        );
        assert_eq!(s.listeners[0].protocol, "TLS-stream-self-signed");
    }

    #[test]
    fn summary_auth_pam() {
        let s = summary_from(
            r#"
            server { auth "pam" service="hypershunt"
}
            listener "tcp://0.0.0.0:80"
            vhost "h" { location "/" { static root="." } }
        "#,
        );
        let a = s.auth.as_ref().unwrap();
        assert_eq!(a.kind, "PAM");
        assert_eq!(a.detail, "hypershunt");
    }

    #[test]
    fn summary_auth_ldap() {
        let s = summary_from(
            r#"
            server {
                auth "ldap" url="ldap://localhost:389" bind-dn="uid={user},dc=example,dc=com" base-dn="dc=example,dc=com"
}
            listener "tcp://0.0.0.0:80"
            vhost "h" { location "/" { static root="." } }
        "#,
        );
        let a = s.auth.as_ref().unwrap();
        assert_eq!(a.kind, "LDAP");
        assert!(a.detail.starts_with("ldap://"), "detail={}", a.detail);
    }

    #[test]
    fn summary_auth_none() {
        let s = summary_from(
            r#"
            listener "tcp://0.0.0.0:80"
            vhost "h" { location "/" { static root="." } }
        "#,
        );
        assert!(s.auth.is_none());
    }

    #[test]
    fn summary_vhost_locations() {
        let s = summary_from(
            r#"
            listener "tcp://0.0.0.0:80"
            vhost "h" {
                location "/static/" { static root="." }
                location "/api/" {
                    proxy {
 upstream "http://127.0.0.1:3000"
}
                }
            }
        "#,
        );
        assert_eq!(s.vhosts[0].locations.len(), 2);
        assert_eq!(s.vhosts[0].locations[0].handler, "static");
        assert_eq!(s.vhosts[0].locations[1].handler, "proxy");
    }

    // -- fmt_num ---------------------------------------------------

    #[test]
    fn fmt_num_zero() {
        assert_eq!(fmt_num(0), "0");
    }

    #[test]
    fn fmt_num_adds_commas() {
        assert_eq!(fmt_num(1000), "1,000");
        assert_eq!(fmt_num(1234567), "1,234,567");
    }

    // -- fmt_unix_ts -----------------------------------------------

    #[test]
    fn fmt_unix_ts_zero_or_negative_is_expired() {
        assert_eq!(fmt_unix_ts(0), "expired");
        assert_eq!(fmt_unix_ts(-1), "expired");
    }

    #[test]
    fn fmt_unix_ts_known_date() {
        // 2024-01-15 10:30:00 UTC = 1705314600
        assert_eq!(fmt_unix_ts(1705314600), "2024-01-15 10:30 UTC");
    }

    #[test]
    fn fmt_unix_ts_epoch_start() {
        // Unix epoch: 1970-01-01 00:00 UTC
        assert_eq!(fmt_unix_ts(1), "1970-01-01 00:00 UTC");
    }

    // -- Integration: serve() uses Metrics -------------------------

    #[test]
    fn metrics_sparkline_matches_period() {
        let m = Metrics::new();
        let sd = m.sparkline_for_period(TimePeriod::Day7);
        assert_eq!(sd.step_secs, TimePeriod::Day7.step_secs());
        assert_eq!(sd.req_rate.len(), 168);
    }

    #[test]
    fn listener_summary_includes_timeout() {
        let s = summary_from(
            r#"
            listener "tcp://0.0.0.0:80" {
                timeouts handler=30
}
            vhost "h" { location "/" { static root="." } }
        "#,
        );
        assert_eq!(s.listeners[0].handler_timeout_secs, Some(30));
    }

    // -- brand icon endpoint ---------------------------------------

    #[tokio::test]
    async fn serve_icon_returns_svg() {
        use http_body_util::BodyExt;
        use hyper::HeaderMap;
        let resp = render_html::serve_icon(&HeaderMap::new());
        assert_eq!(resp.status(), 200);
        assert_eq!(
            resp.headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok()),
            Some("image/svg+xml"),
        );
        let bytes =
            resp.into_body().collect().await.unwrap().to_bytes();
        assert!(!bytes.is_empty());
    }

    #[tokio::test]
    async fn serve_icon_304_on_matching_etag() {
        use http_body_util::BodyExt;
        use hyper::HeaderMap;
        // First request to learn the ETag.
        let resp = render_html::serve_icon(&HeaderMap::new());
        let etag = resp
            .headers()
            .get("etag")
            .unwrap()
            .clone();
        // Second request with matching If-None-Match.
        let mut hdrs = HeaderMap::new();
        hdrs.insert("if-none-match", etag);
        let resp2 = render_html::serve_icon(&hdrs);
        assert_eq!(resp2.status(), 304);
        let bytes =
            resp2.into_body().collect().await.unwrap().to_bytes();
        assert!(bytes.is_empty());
    }

    #[tokio::test]
    async fn render_html_icon_refs_reflect_prefix() {
        use http_body_util::BodyExt;
        let paths: Vec<(String, u64)> = vec![];
        let resp = render_html(
            &sample_snap(),
            &sample_sparkline(),
            &paths,
            TimePeriod::Min15,
            &sample_summary(),
            &[],
            &[],
            "/status",
        );
        let bytes =
            resp.into_body().collect().await.unwrap().to_bytes();
        let html = std::str::from_utf8(&bytes).unwrap();
        // The sidebar brand image uses the wide lockup at the prefix.
        assert!(
            html.contains("src=\"/status/hs-icon.svg\""),
            "img src must use the matched prefix: {html}",
        );
        // The browser-tab favicon uses the square crop, not the lockup.
        assert!(
            html.contains(
                "rel=\"icon\" type=\"image/svg+xml\" \
                 href=\"/status/hs-favicon.svg\""
            ),
            "favicon link must use the square favicon: {html}",
        );
    }

    #[tokio::test]
    async fn serve_favicon_returns_svg() {
        use http_body_util::BodyExt;
        use hyper::HeaderMap;
        let resp = render_html::serve_favicon(&HeaderMap::new());
        assert_eq!(resp.status(), 200);
        assert_eq!(
            resp.headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok()),
            Some("image/svg+xml"),
        );
        let bytes =
            resp.into_body().collect().await.unwrap().to_bytes();
        assert!(!bytes.is_empty());
    }
}