sagittarius 0.2.0

A fast, self-hosted DNS sinkhole in a single Rust binary
Documentation
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
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
//! Web administration interface.
//!
//! An [`axum`] HTTP server sharing the tokio runtime with the DNS engine.
//! Renders HTML with [`askama`] compile-time templates and drives
//! interactivity via [Datastar](https://data-star.dev/) (SSE-based fragments
//! and reactive signals) — no JavaScript build step.  Styling is
//! [Pico CSS](https://picocss.com/) plus a thin custom layer, both vendored
//! into the binary (see [`assets`]).
//!
//! All routes are authenticated; state-changing requests carry CSRF
//! protection.  See SPEC §9 for the full capability list and security model.
//!
//! # Shared state
//!
//! [`AppState`] bundles the handles the admin handlers need — the database,
//! the shared [`ResolverState`], the telemetry sink, and the blocklist refresh
//! trigger — and is cloned into every request via axum's [`State`] extractor.
//! Fields are added as later subtasks wire them in.

pub mod assets;
pub mod auth;
pub mod blocking;
pub mod blocklists;
pub mod crypto;
pub mod csrf;
pub mod dashboard;
pub mod forward_zones;
pub mod icons;
pub mod lists;
pub mod live_log;
pub mod origin;
pub mod records;
pub mod render;
pub mod settings;
pub mod upstreams;
pub mod wizard;

use std::{
    net::SocketAddr,
    sync::{Arc, atomic::AtomicBool},
};

use axum::{
    Router, middleware,
    routing::{get, post},
};

use crate::web::auth::CurrentUser;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use tracing::warn;

use crate::{
    blocklist::scheduler::RefreshTrigger,
    config::SessionCookieSecurePolicy,
    resolver::{
        reverse::SharedReverseResolver, state::ResolverState, upstream::SharedUpstreamPool,
    },
    storage::{Db, settings::SettingsRepository},
    telemetry::TelemetrySink,
    web::{assets::Assets, icons::Icons},
};
use tokio_util::task::TaskTracker;

// ── Errors ──────────────────────────────────────────────────────────────────

/// Errors that can occur in the web administration server.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The admin HTTP server failed to bind its listen address.
    #[error("failed to bind admin listener on {addr}: {source}")]
    Bind {
        addr: std::net::SocketAddr,
        #[source]
        source: std::io::Error,
    },

    /// An internal server error occurred while handling a request.
    #[error("internal error: {0}")]
    Internal(String),
}

// ── Chrome ──────────────────────────────────────────────────────────────────

/// Per-request page chrome shared by every template via the base layout.
///
/// Carrying these fields in one struct (rather than repeating them on every
/// page template) keeps `base.html` stable as the epic grows: the layout reads
/// `chrome.theme`, highlights the active nav item, and conditionally renders
/// the authenticated controls.
#[derive(Debug, Clone)]
pub struct Chrome {
    /// `data-theme` value driving Pico's colour scheme (`auto` / `light` / `dark`).
    pub theme: String,
    /// Key of the active nav section, e.g. `"dashboard"` — used to mark the
    /// current link and as a fallback page title.
    pub active: &'static str,
    /// Whether to render the top navigation bar (hidden on login / wizard).
    pub show_nav: bool,
    /// Whether an admin session is active (controls the logout control).
    pub authenticated: bool,
    /// Anti-CSRF token embedded in forms (populated from E8.3; empty until then).
    pub csrf_token: String,
    /// Seconds of blocking-pause remaining, or `None` when blocking is active
    /// (E12). When `Some`, `base.html` renders the countdown banner on every
    /// page; the value seeds the client-side Datastar countdown.
    pub pause_remaining: Option<i64>,
    /// Cache-busting token appended to embedded-asset URLs (`?v=…`) so an
    /// upgraded binary's CSS/JS reaches browsers holding an immutable-cached
    /// copy of the previous build (see [`assets::Assets::fingerprint`]).
    pub asset_version: &'static str,
}

// ── AppState ──────────────────────────────────────────────────────────────────

/// Shared state handed to every admin request handler.
///
/// Cheap to clone — the database pool and the `Arc`-wrapped handles are all
/// reference-counted.  Cloned into handlers through axum's [`State`] extractor.
#[derive(Clone)]
pub struct AppState {
    /// Durable configuration store (SPEC §4).
    pub db: Db,
    /// Hot-path resolver state shared with the DNS engine (SPEC §3.1).
    pub resolver: Arc<ResolverState>,
    /// Live-log + runtime-stats sink for the dashboard and SSE log (E6.6).
    pub telemetry: Arc<TelemetrySink>,
    /// On-demand blocklist refresh trigger (E7.4).
    pub refresh: RefreshTrigger,
    /// Operational session-cookie `Secure` policy (SPEC §9, §10).
    pub cookie_policy: SessionCookieSecurePolicy,
    /// Per-process key for deriving session-bound CSRF tokens (E8.3).
    ///
    /// Random at startup; outstanding page tokens are invalidated on restart
    /// (the user simply reloads to obtain a fresh one).
    pub csrf_key: Arc<[u8; 32]>,
    /// Fast-path flag for the first-run wizard (E8.4): set once an admin user
    /// is observed, after which the wizard is permanently closed.
    pub setup_done: Arc<AtomicBool>,
    /// Hot-swappable upstream pool shared with the DNS engine (E5); rebuilt and
    /// swapped when the operator edits upstreams (E8.9).
    pub upstream_pool: Arc<SharedUpstreamPool>,
    /// The app task tracker, used to register the background drivers of a
    /// rebuilt upstream pool (E8.9).
    pub tracker: TaskTracker,
    /// Internal reverse-lookup service for client-hostname decoration (E14).
    ///
    /// Resolves client IPs to hostnames off the hot path, from a bounded cache;
    /// the live log and dashboard top-clients read cached names at render time.
    pub reverse: SharedReverseResolver,
    /// Process start instant, for the dashboard uptime figure (E15.7).
    pub started_at: std::time::Instant,
}

/// Generate a fresh random key for signing session-bound CSRF tokens.
///
/// Called once at startup; see [`AppState::csrf_key`].
pub fn random_csrf_key() -> Arc<[u8; 32]> {
    use rand::Rng;
    let mut key = [0u8; 32];
    rand::rng().fill_bytes(&mut key);
    Arc::new(key)
}

impl AppState {
    /// Read the configured UI theme, falling back to `auto` if the settings
    /// row cannot be read.
    async fn ui_theme(&self) -> String {
        match self.db.settings().get().await {
            Ok(settings) => settings.ui_theme,
            Err(e) => {
                warn!(error = %e, "failed to read ui_theme; defaulting to auto");
                "auto".to_owned()
            }
        }
    }

    /// Build the page [`Chrome`] for an authenticated, full-navigation page.
    ///
    /// Only reached from handlers gated by the [`CurrentUser`] extractor, so
    /// `authenticated` is always `true`.  The session-bound CSRF token is
    /// embedded so forms and Datastar actions on the page can authorise their
    /// mutations (E8.3).
    async fn chrome(&self, active: &'static str, user: &CurrentUser) -> Chrome {
        Chrome {
            theme: self.ui_theme().await,
            active,
            show_nav: true,
            authenticated: true,
            csrf_token: self.csrf_token(&user.session_id).into_string(),
            pause_remaining: self.pause_remaining(),
            asset_version: Assets::fingerprint(),
        }
    }

    /// Display label for a client given as an IP **string** (e.g. a persisted
    /// `query_log.client` value): `"hostname (ip)"` when a hostname is cached,
    /// otherwise the bare IP.  Unparsable values pass through verbatim.
    ///
    /// Reads only the cache (never blocks on the network) and warms a miss in
    /// the background so the next render shows the name (E14.2).
    pub(crate) async fn client_label(&self, ip: &str) -> String {
        match ip.parse::<std::net::IpAddr>() {
            Ok(addr) => self.client_label_ip(addr).await,
            Err(_) => ip.to_owned(),
        }
    }

    /// Display label for a client [`IpAddr`](std::net::IpAddr): `"hostname (ip)"`
    /// when cached, otherwise the bare IP (warming the cache for next time).
    pub(crate) async fn client_label_ip(&self, ip: std::net::IpAddr) -> String {
        use crate::web::render::DomainDisplay as _;
        match self.reverse.cached(ip).await {
            Some(name) => format!("{} ({ip})", name.to_string().display_domain()),
            None => {
                self.reverse.warm(ip);
                ip.to_string()
            }
        }
    }

    /// Seconds of blocking-pause remaining, or `None` when blocking is active.
    ///
    /// Derived from the resolver's pause deadline (E12.1); drives the countdown
    /// banner in the page chrome.
    fn pause_remaining(&self) -> Option<i64> {
        self.resolver
            .paused_until()
            .map(|deadline| (deadline - crate::time::Clock::now_secs()).max(0))
    }

    /// Build a bare [`Chrome`] (no navigation) for the login page and wizard.
    async fn bare_chrome(&self) -> Chrome {
        Chrome {
            theme: self.ui_theme().await,
            active: "",
            show_nav: false,
            authenticated: false,
            csrf_token: String::new(),
            pause_remaining: None,
            asset_version: Assets::fingerprint(),
        }
    }

    /// Assemble the admin [`Router`] with all routes and the shared state.
    fn router(self) -> Router {
        Router::new()
            .route("/", get(Self::dashboard))
            // Live query log + the shared SSE stream (log + dashboard counters).
            .route("/log", get(Self::query_log))
            .route("/log/older", get(Self::query_log_older))
            .route("/events", get(Self::events))
            // One-click block / unblock actions from the live log.
            .route("/log/block", post(Self::log_block))
            .route("/log/unblock", post(Self::log_unblock))
            // Manual list + local-record management (E8.8).
            .route("/blacklist", get(Self::blacklist_page))
            .route("/blacklist/add", post(Self::blacklist_add))
            .route("/blacklist/remove", post(Self::blacklist_remove))
            .route("/allowlist", get(Self::allowlist_page))
            .route("/allowlist/add", post(Self::allowlist_add))
            .route("/allowlist/remove", post(Self::allowlist_remove))
            .route("/local", get(Self::local_page))
            .route("/local/add", post(Self::local_add))
            .route("/local/remove", post(Self::local_remove))
            // Upstream resolvers + settings (E8.9).
            .route("/upstreams", get(Self::upstreams_page))
            .route("/upstreams/add", post(Self::upstream_add))
            .route("/upstreams/remove", post(Self::upstream_remove))
            .route("/upstreams/toggle", post(Self::upstream_toggle))
            .route("/forwarding", get(Self::forwarding_page))
            .route("/forwarding/target", post(Self::forward_zone_set_target))
            .route("/forwarding/toggle", post(Self::forward_zone_toggle))
            .route("/forwarding/apply-all", post(Self::forward_zone_apply_all))
            .route(
                "/settings",
                get(Self::settings_page).post(Self::settings_save),
            )
            .route("/settings/clear-log", post(Self::settings_clear_log))
            .route("/theme/toggle", post(Self::theme_toggle))
            // Temporarily pause / resume all blocking (E12).
            .route("/blocking/pause", post(Self::blocking_pause))
            .route("/blocking/resume", post(Self::blocking_resume))
            // Blocklist source management + manual refresh (E8.10).
            .route("/blocklists", get(Self::blocklists_page))
            .route("/blocklists/add", post(Self::blocklist_add))
            .route("/blocklists/remove", post(Self::blocklist_remove))
            .route("/blocklists/toggle", post(Self::blocklist_toggle))
            .route("/blocklists/refresh", post(Self::blocklist_refresh))
            // First-run wizard (public; gated by the wizard layer below).
            .route("/setup", get(Self::setup_form).post(Self::setup_submit))
            // Authentication (public).
            .route("/login", get(Self::login_form).post(Self::login_submit))
            .route("/logout", post(Self::logout))
            // Embedded static assets (no CDN, no Node build).
            .route("/assets/datastar.js", get(Assets::datastar_js))
            .route("/assets/pico.pumpkin.min.css", get(Assets::pico_css))
            .route("/assets/app.css", get(Assets::app_css))
            .route("/assets/icons.svg", get(Icons::sprite))
            .route("/assets/icon.png", get(Assets::icon_png))
            .route("/favicon.ico", get(Assets::icon_png))
            // CSRF protection wraps every route; it self-skips safe methods and
            // pre-auth (no-session) mutations (E8.3).
            .layer(middleware::from_fn_with_state(self.clone(), csrf::guard))
            // The wizard gate is outermost (E8.4): until the first admin exists
            // it forces all UI traffic to /setup; afterwards it closes /setup.
            .layer(middleware::from_fn_with_state(self.clone(), wizard::guard))
            .with_state(self)
    }
}

// ── AdminServer ─────────────────────────────────────────────────────────────

/// A bound-but-not-yet-serving admin HTTP server.
///
/// Mirrors the DNS listener's `bind` → `serve` split so a bad
/// `--admin-addr` surfaces as a startup error (via [`AdminServer::bind`])
/// rather than failing silently inside a spawned task.
pub struct AdminServer {
    listener: TcpListener,
    router: Router,
}

impl AdminServer {
    /// Bind the admin listener on `addr` and build the router around `state`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Bind`] if the address cannot be bound.
    pub async fn bind(addr: SocketAddr, state: AppState) -> Result<Self, Error> {
        auth::SessionCookie::warn_if_insecure(state.cookie_policy, addr);
        let listener = TcpListener::bind(addr)
            .await
            .map_err(|source| Error::Bind { addr, source })?;
        Ok(Self {
            listener,
            router: state.router(),
        })
    }

    /// The actual bound address (useful when binding an ephemeral `:0` port in
    /// tests).
    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
        self.listener.local_addr()
    }

    /// Serve requests until `token` is cancelled, then drain gracefully.
    pub async fn serve(self, token: CancellationToken) {
        let Self { listener, router } = self;
        let shutdown = async move { token.cancelled().await };
        if let Err(e) = axum::serve(listener, router)
            .with_graceful_shutdown(shutdown)
            .await
        {
            tracing::error!(error = %e, "admin server terminated with error");
        }
    }
}

// ── Test support ──────────────────────────────────────────────────────────────

#[cfg(test)]
impl AppState {
    /// Build an [`AppState`] over `db` with defaults suitable for tests: an
    /// empty upstream pool, fresh telemetry, loopback cookie policy, and the
    /// wizard gate left to the live `admin_users` count.
    pub(crate) async fn for_test(db: Db) -> AppState {
        use crate::{
            blocklist::{fetch::Fetcher, scheduler::BlocklistScheduler},
            resolver::upstream::{
                DEFAULT_FAILOVER_BUDGET, DEFAULT_QUERY_TIMEOUT, RandomSelector, UpstreamPool,
            },
            telemetry::{LiveLog, Stats},
        };

        let resolver = ResolverState::hydrate(&db).await.expect("hydrate");
        let telemetry = Arc::new(TelemetrySink::new(
            Arc::new(LiveLog::default()),
            Arc::new(Stats::new()),
        ));
        let tracker = TaskTracker::new();
        let upstream_pool = Arc::new(SharedUpstreamPool::new(
            UpstreamPool::connect(
                &[],
                &tracker,
                Arc::new(RandomSelector),
                DEFAULT_FAILOVER_BUDGET,
                DEFAULT_QUERY_TIMEOUT,
            )
            .await,
        ));
        let scheduler =
            BlocklistScheduler::new(db.blocklists(), Arc::clone(&resolver), Fetcher::new());
        let reverse = Arc::new(crate::resolver::reverse::ReverseResolver::new(
            crate::resolver::pipeline::engine::build_internal_service(
                Arc::clone(&resolver),
                Arc::clone(&upstream_pool),
            ),
        ));
        AppState {
            db,
            resolver,
            telemetry,
            refresh: scheduler.trigger(),
            cookie_policy: SessionCookieSecurePolicy::Never,
            csrf_key: random_csrf_key(),
            setup_done: Arc::new(AtomicBool::new(false)),
            upstream_pool,
            tracker,
            started_at: std::time::Instant::now(),
            reverse,
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn error_variants_display() {
        let e = Error::Internal("unexpected state".into());
        assert!(e.to_string().contains("unexpected state"));
    }

    /// Build an [`AppState`] backed by a fresh temp database for tests.
    async fn test_state() -> (TempDir, AppState) {
        let (dir, db) = crate::test_support::temp_db().await;
        let state = AppState::for_test(db).await;
        (dir, state)
    }

    /// Extract the session id (the `id` component) from a `name=id.token` cookie.
    fn session_id_of(cookie: &str) -> String {
        cookie
            .split_once('=')
            .unwrap()
            .1
            .split_once('.')
            .unwrap()
            .0
            .to_owned()
    }

    /// A bound, serving admin server with a seeded admin and an authenticated
    /// session, for the feature integration tests.
    ///
    /// Collapses the repeated bind → spawn → login → cookie/CSRF dance. Tests
    /// that exercise the auth or first-run-wizard flows themselves do **not** use
    /// this (they drive those flows manually).
    struct TestServer {
        /// A clone of the served state, for asserting on the DB / live snapshot.
        app: AppState,
        base: String,
        client: reqwest::Client,
        /// The `name=id.token` session cookie for the logged-in admin.
        cookie: String,
        /// The session-bound CSRF token for that cookie.
        csrf: String,
        cancel: CancellationToken,
        handle: tokio::task::JoinHandle<()>,
        _dir: TempDir,
    }

    impl TestServer {
        /// Spawn a server, seed an `admin`/`s3cret` account, and log in.
        async fn login() -> Self {
            use crate::{storage::admin_users::AdminUserRepository, web::auth::Password};
            use reqwest::redirect::Policy;

            let (dir, state) = test_state().await;
            state
                .db
                .admin_users()
                .create("admin", Password::hash("s3cret").unwrap().as_str())
                .await
                .unwrap();
            let app = state.clone();
            let server = AdminServer::bind("127.0.0.1:0".parse().unwrap(), state)
                .await
                .unwrap();
            let base = format!("http://{}", server.local_addr().unwrap());
            let cancel = CancellationToken::new();
            let c2 = cancel.clone();
            let handle = tokio::spawn(async move { server.serve(c2).await });

            let client = reqwest::Client::builder()
                .redirect(Policy::none())
                .build()
                .unwrap();
            let r = client
                .post(format!("{base}/login"))
                .header("content-type", "application/x-www-form-urlencoded")
                .header("origin", &base)
                .body("username=admin&password=s3cret")
                .send()
                .await
                .unwrap();
            let cookie = r
                .headers()
                .get("set-cookie")
                .unwrap()
                .to_str()
                .unwrap()
                .split(';')
                .next()
                .unwrap()
                .to_owned();
            let csrf = app.csrf_token(&session_id_of(&cookie)).into_string();

            Self {
                app,
                base,
                client,
                cookie,
                csrf,
                cancel,
                handle,
                _dir: dir,
            }
        }

        /// Absolute URL for `path` (e.g. `ts.url("/settings")`).
        fn url(&self, path: &str) -> String {
            format!("{}{}", self.base, path)
        }

        /// Cancel the server and wait for it to drain.
        async fn shutdown(self) {
            self.cancel.cancel();
            tokio::time::timeout(std::time::Duration::from_secs(5), self.handle)
                .await
                .expect("server shut down within 5s")
                .expect("server task panicked");
        }
    }

    #[tokio::test]
    async fn auth_flow_end_to_end() {
        use crate::{storage::admin_users::AdminUserRepository, web::auth::Password};
        use reqwest::redirect::Policy;

        let (_dir, state) = test_state().await;
        let pool = state.db.pool().clone();

        // Seed an admin account.
        state
            .db
            .admin_users()
            .create("admin", Password::hash("s3cret").expect("hash").as_str())
            .await
            .expect("create admin");

        // Keep a clone to derive CSRF tokens for mutating requests in the test.
        let app = state.clone();
        let server = AdminServer::bind("127.0.0.1:0".parse().unwrap(), state)
            .await
            .expect("bind");
        let base = format!("http://{}", server.local_addr().unwrap());
        let token = CancellationToken::new();
        let token2 = token.clone();
        let handle = tokio::spawn(async move { server.serve(token2).await });

        // A client that does NOT auto-follow redirects, so we can inspect them.
        let client = reqwest::Client::builder()
            .redirect(Policy::none())
            .build()
            .unwrap();

        // Unauthenticated access to a protected route redirects to /login.
        let r = client.get(format!("{base}/")).send().await.unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/login");

        // Pre-auth mutations require an origin signal.
        let r = client
            .post(format!("{base}/login"))
            .header("content-type", "application/x-www-form-urlencoded")
            .body("username=admin&password=s3cret")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403);

        // Wrong password is rejected (re-renders the form with an error).
        let r = client
            .post(format!("{base}/login"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .body("username=admin&password=wrong")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        assert!(
            r.text()
                .await
                .unwrap()
                .contains("Invalid username or password")
        );

        // Correct credentials establish a session and set the cookie.
        let r = client
            .post(format!("{base}/login"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .body("username=admin&password=s3cret")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/");
        let set_cookie = r
            .headers()
            .get("set-cookie")
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();
        assert!(set_cookie.contains("sgt_session="));
        assert!(set_cookie.contains("HttpOnly"));
        assert!(set_cookie.contains("SameSite=Strict"));
        // The cookie value to echo back on subsequent requests.
        let cookie = set_cookie.split(';').next().unwrap().to_owned();

        // The session authorizes the protected route.
        let r = client
            .get(format!("{base}/"))
            .header("cookie", &cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        let dash = r.text().await.unwrap();
        // The dashboard renders inside the base layout with the vendored assets,
        // the active nav marker, and the session-bound CSRF token.
        assert!(dash.contains("/assets/pico.pumpkin.min.css"));
        assert!(dash.contains("/assets/datastar.js"));
        assert!(dash.contains("aria-current=\"page\""));
        assert!(dash.contains(app.csrf_token(&session_id_of(&cookie)).as_str()));

        // Expire the session server-side: the same cookie no longer authorizes.
        sqlx::query("UPDATE sessions SET expires_at = 0")
            .execute(&pool)
            .await
            .unwrap();
        let r = client
            .get(format!("{base}/"))
            .header("cookie", &cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303, "expired session must redirect to login");
        assert_eq!(r.headers().get("location").unwrap(), "/login");

        // Regression: the now-expired cookie is still in the browser. A login
        // POST that carries it must NOT be CSRF-rejected — the dead session
        // binds no token, so the guard treats it as pre-auth and the handler
        // establishes a fresh session. (Previously this 403'd, locking the user
        // out until they manually cleared the cookie.)
        let r = client
            .post(format!("{base}/login"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .header("cookie", &cookie)
            .body("username=admin&password=s3cret")
            .send()
            .await
            .unwrap();
        assert_eq!(
            r.status(),
            303,
            "login with a stale session cookie must not be CSRF-rejected"
        );

        // Re-login, then logout: the cookie is cleared and the session deleted.
        let r = client
            .post(format!("{base}/login"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .body("username=admin&password=s3cret")
            .send()
            .await
            .unwrap();
        let cookie = r
            .headers()
            .get("set-cookie")
            .unwrap()
            .to_str()
            .unwrap()
            .split(';')
            .next()
            .unwrap()
            .to_owned();

        // The logout mutation requires the session-bound CSRF token. Derive it
        // from the session id (the cookie's `id` component).
        let csrf = app.csrf_token(&session_id_of(&cookie)).into_string();

        // Without the token the mutation is rejected.
        let r = client
            .post(format!("{base}/logout"))
            .header("cookie", &cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(
            r.status(),
            403,
            "logout without CSRF token must be rejected"
        );

        // A cross-origin request (mismatched Origin) is rejected even with a
        // valid token.
        let r = client
            .post(format!("{base}/logout"))
            .header("cookie", &cookie)
            .header("x-csrf-token", &csrf)
            .header("origin", "http://evil.example.com")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403, "cross-origin mutation must be rejected");

        // With the token (via the X-CSRF-Token header) it succeeds.
        let r = client
            .post(format!("{base}/logout"))
            .header("cookie", &cookie)
            .header("x-csrf-token", &csrf)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/login");
        assert!(
            r.headers()
                .get("set-cookie")
                .unwrap()
                .to_str()
                .unwrap()
                .contains("Max-Age=0"),
            "logout must clear the cookie"
        );
        // The invalidated session no longer authorizes.
        let r = client
            .get(format!("{base}/"))
            .header("cookie", &cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);

        token.cancel();
        tokio::time::timeout(std::time::Duration::from_secs(5), handle)
            .await
            .expect("shutdown")
            .expect("task");
    }

    #[tokio::test]
    async fn first_run_wizard_flow() {
        use crate::storage::admin_users::AdminUserRepository;
        use reqwest::redirect::Policy;

        // Fresh state: no admin user exists yet. Keep a DB handle alive past the
        // move into the server, to assert admin counts during the wizard flow.
        let (_dir, state) = test_state().await;
        let db = state.db.clone();
        let server = AdminServer::bind("127.0.0.1:0".parse().unwrap(), state)
            .await
            .expect("bind");
        let base = format!("http://{}", server.local_addr().unwrap());
        let token = CancellationToken::new();
        let token2 = token.clone();
        let handle = tokio::spawn(async move { server.serve(token2).await });

        let client = reqwest::Client::builder()
            .redirect(Policy::none())
            .build()
            .unwrap();

        // Any UI route redirects to the wizard while admin_users is empty.
        let r = client.get(format!("{base}/")).send().await.unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/setup");

        // Even /login bounces to /setup before an admin exists.
        let r = client.get(format!("{base}/login")).send().await.unwrap();
        assert_eq!(r.headers().get("location").unwrap(), "/setup");

        // The wizard renders.
        let r = client.get(format!("{base}/setup")).send().await.unwrap();
        assert_eq!(r.status(), 200);
        assert!(r.text().await.unwrap().contains("Welcome"));

        // Pre-auth setup also requires an origin signal.
        let r = client
            .post(format!("{base}/setup"))
            .header("content-type", "application/x-www-form-urlencoded")
            .body("username=admin&password=longenough&confirm=longenough")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403);

        // Mismatched passwords are rejected.
        let r = client
            .post(format!("{base}/setup"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .body("username=admin&password=longenough&confirm=different")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        assert!(r.text().await.unwrap().contains("do not match"));
        assert_eq!(
            db.admin_users().count().await.unwrap(),
            0,
            "no admin created on validation failure"
        );

        // A valid submission creates the admin and unlocks the UI.
        let r = client
            .post(format!("{base}/setup"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .body("username=admin&password=longenough&confirm=longenough")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/login");
        assert_eq!(db.admin_users().count().await.unwrap(), 1);

        // The wizard is now closed.
        let r = client.get(format!("{base}/setup")).send().await.unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/login");

        // And the freshly created admin can log in.
        let r = client
            .post(format!("{base}/login"))
            .header("content-type", "application/x-www-form-urlencoded")
            .header("origin", &base)
            .body("username=admin&password=longenough")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/");

        token.cancel();
        tokio::time::timeout(std::time::Duration::from_secs(5), handle)
            .await
            .expect("shutdown")
            .expect("task");
    }

    #[tokio::test]
    async fn live_query_log_streams_over_sse() {
        use crate::{
            codec::{message::Qtype, name::Name},
            resolver::pipeline::Outcome,
            telemetry::QueryEvent,
        };
        use std::time::Duration;

        let ts = TestServer::login().await;

        // The log page renders, seeded and wired for the SSE stream.
        let log = ts
            .client
            .get(ts.url("/log"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(log.contains("Query log"));
        assert!(log.contains("id=\"log-body\""));
        // The page opens the SSE stream on load via Datastar's data-init.
        assert!(log.contains("data-init=\"@get('/events')\""));

        // Open the SSE stream.
        let mut resp = ts
            .client
            .get(ts.url("/events"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        assert!(
            resp.headers()
                .get("content-type")
                .unwrap()
                .to_str()
                .unwrap()
                .contains("text/event-stream")
        );

        // Helper: read chunks until `needle` appears (bounded by a timeout).
        async fn read_until(resp: &mut reqwest::Response, needle: &str) -> String {
            let mut buf = String::new();
            loop {
                let chunk = tokio::time::timeout(Duration::from_secs(5), resp.chunk())
                    .await
                    .expect("sse read timed out")
                    .expect("chunk error");
                match chunk {
                    Some(bytes) => {
                        buf.push_str(&String::from_utf8_lossy(&bytes));
                        if buf.contains(needle) {
                            return buf;
                        }
                    }
                    None => return buf,
                }
            }
        }

        // The stream opens with the dashboard counter signals.
        let head = read_until(&mut resp, "queries").await;
        assert!(head.contains("datastar-patch-signals"));

        // Publish a live query; it must arrive as a prepended log row.
        ts.app.telemetry.record(
            QueryEvent::new(
                "10.1.2.3:4000".parse().unwrap(),
                "sse-row.example.com".parse::<Name>().unwrap(),
                Qtype::A,
                Outcome::BlockedByBlocklist,
            )
            .with_latency(Duration::from_millis(3)),
        );
        let body = read_until(&mut resp, "sse-row.example.com").await;
        assert!(body.contains("datastar-patch-elements"));
        assert!(body.contains("log-body"));
        assert!(body.contains("sgt-badge--blocked"));

        drop(resp);
        ts.shutdown().await;
    }

    #[tokio::test]
    async fn dashboard_shows_persisted_window_excluding_old_rows() {
        use crate::{
            resolver::pipeline::Outcome,
            storage::query_log::{QueryLogRecord, QueryLogRepository},
            time::Clock,
        };

        let ts = TestServer::login().await;

        let now = Clock::now_millis();
        let row = |ts: i64, name: &str, outcome: Outcome| QueryLogRecord {
            id: 0,
            ts,
            client: "10.0.0.5".to_owned(),
            qname: name.to_owned(),
            qtype: "A".to_owned(),
            outcome,
            rcode: Some(0),
            upstream: None,
            latency_ms: 1,
            blocklist_id: None,
        };
        // In-window rows plus one well outside the 24h window.
        ts.app
            .db
            .query_log()
            .insert_batch(&[
                row(now - 1_000, "inwin.test.", Outcome::Forwarded),
                row(now - 2_000, "inwin.test.", Outcome::Forwarded),
                row(now - 3_000, "blocked.test.", Outcome::BlockedByAdmin),
                row(now - 48 * 3_600 * 1_000, "old.test.", Outcome::Forwarded),
            ])
            .await
            .unwrap();

        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();

        assert!(page.contains("Last 24 hours (persisted)"));
        // In-window domains/clients are surfaced; the out-of-window row is not.
        assert!(page.contains("inwin.test"));
        assert!(page.contains("blocked.test"));
        assert!(
            !page.contains("old.test"),
            "rows older than 24h are excluded"
        );

        ts.shutdown().await;
    }

    /// E14.2: the live log decorates a client IP with its cached hostname
    /// (`hostname (ip)`), and falls back to the bare IP when none is cached.
    #[tokio::test]
    async fn live_log_decorates_client_with_hostname() {
        use crate::{
            resolver::local::{LocalRecords, RecordData},
            resolver::pipeline::Outcome,
            storage::query_log::{QueryLogRecord, QueryLogRepository},
        };

        let ts = TestServer::login().await;

        // A local A record gives the reverse index (E13.2) a hostname for the
        // private client IP; the reverse resolver shares this resolver state.
        let mut b = LocalRecords::builder();
        b.add(
            "desktop.home.lan",
            RecordData::A("192.168.1.50".parse().unwrap()),
            300,
        )
        .unwrap();
        ts.app.resolver.local().store(b.build());

        // Warm the reverse cache synchronously so the render finds the name
        // (rendering itself only reads the cache, never blocks on a lookup).
        let resolved = ts.app.reverse.lookup("192.168.1.50".parse().unwrap()).await;
        assert_eq!(
            resolved.map(|n| n.to_string()),
            Some("desktop.home.lan.".to_owned())
        );

        let row = |row_ts: i64, client: &str, name: &str| QueryLogRecord {
            id: 0,
            ts: row_ts,
            client: client.to_owned(),
            qname: name.to_owned(),
            qtype: "A".to_owned(),
            outcome: Outcome::Forwarded,
            rcode: Some(0),
            upstream: None,
            latency_ms: 1,
            blocklist_id: None,
        };
        ts.app
            .db
            .query_log()
            .insert_batch(&[
                row(2, "192.168.1.50", "known.test."),
                // A client we hold no hostname for renders the bare IP.
                row(1, "203.0.113.9", "unknown.test."),
            ])
            .await
            .unwrap();

        let page = ts
            .client
            .get(ts.url("/log"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();

        assert!(
            page.contains("desktop.home.lan (192.168.1.50)"),
            "cached hostname must render as 'hostname (ip)'"
        );
        assert!(page.contains("203.0.113.9"), "uncached client shows the IP");
        assert!(
            !page.contains("203.0.113.9 ("),
            "uncached client must not be decorated"
        );

        ts.shutdown().await;
    }

    /// E14: adding a local record through the admin handler invalidates the
    /// reverse-lookup cache, so a client that was previously bare (its negative
    /// lookup cached) decorates on the next render — no restart needed.
    #[tokio::test]
    async fn editing_local_records_refreshes_hostname_decoration() {
        use crate::resolver::pipeline::Outcome;
        use crate::storage::query_log::{QueryLogRecord, QueryLogRepository};
        use std::net::IpAddr;

        let ts = TestServer::login().await;
        let ip: IpAddr = "192.168.1.60".parse().unwrap();

        // No record yet → a lookup negatively caches "no hostname" for this IP.
        assert!(ts.app.reverse.lookup(ip).await.is_none());

        // Add the matching record through the real handler. Without the cache
        // invalidation it wires in, the sticky negative entry would keep the
        // client bare until the TTL elapses or the server restarts.
        let r = ts
            .client
            .post(ts.url("/local/add"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!(
                "csrf_token={}&name=nas.home.lan&type=A&value=192.168.1.60&ttl=300",
                ts.csrf
            ))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);

        // The reverse cache was cleared, so a fresh lookup now resolves.
        assert_eq!(
            ts.app.reverse.lookup(ip).await.map(|n| n.to_string()),
            Some("nas.home.lan.".to_owned()),
            "local-record edit must invalidate the stale negative reverse-cache entry"
        );

        // And the client renders decorated in the live log.
        ts.app
            .db
            .query_log()
            .insert_batch(&[QueryLogRecord {
                id: 0,
                ts: 1,
                client: "192.168.1.60".to_owned(),
                qname: "x.test.".to_owned(),
                qtype: "A".to_owned(),
                outcome: Outcome::Forwarded,
                rcode: Some(0),
                upstream: None,
                latency_ms: 1,
                blocklist_id: None,
            }])
            .await
            .unwrap();
        let page = ts
            .client
            .get(ts.url("/log"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("nas.home.lan (192.168.1.60)"));

        ts.shutdown().await;
    }

    /// E14.2: the dashboard top-clients table decorates IPs with hostnames,
    /// while aggregation stays keyed by IP (two names for one IP don't split
    /// the count — the hostname is display-only).
    #[tokio::test]
    async fn dashboard_top_clients_show_hostnames_grouped_by_ip() {
        use crate::{
            resolver::local::{LocalRecords, RecordData},
            resolver::pipeline::Outcome,
            storage::query_log::{QueryLogRecord, QueryLogRepository},
            time::Clock,
        };

        let ts = TestServer::login().await;

        let mut b = LocalRecords::builder();
        b.add(
            "phone.home.lan",
            RecordData::A("192.168.1.77".parse().unwrap()),
            300,
        )
        .unwrap();
        ts.app.resolver.local().store(b.build());
        ts.app
            .reverse
            .lookup("192.168.1.77".parse().unwrap())
            .await
            .expect("warm reverse cache");

        // Three in-window queries from one IP under two different domains: the
        // top-clients table must show a single grouped row for that IP.
        let now = Clock::now_millis();
        let row = |name: &str| QueryLogRecord {
            id: 0,
            ts: now - 1_000,
            client: "192.168.1.77".to_owned(),
            qname: name.to_owned(),
            qtype: "A".to_owned(),
            outcome: Outcome::Forwarded,
            rcode: Some(0),
            upstream: None,
            latency_ms: 1,
            blocklist_id: None,
        };
        ts.app
            .db
            .query_log()
            .insert_batch(&[row("a.test."), row("a.test."), row("b.test.")])
            .await
            .unwrap();

        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();

        assert!(
            page.contains("phone.home.lan (192.168.1.77)"),
            "top-client IP must be decorated with its hostname"
        );
        // Aggregation is keyed by IP: a single grouped count of 3, not split.
        let label_pos = page
            .find("phone.home.lan (192.168.1.77)")
            .expect("decorated client present");
        assert!(
            page[label_pos..].contains('3'),
            "the three queries for the IP must aggregate into one count"
        );

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn query_log_history_seeds_from_db_and_scrolls_back() {
        use crate::{
            resolver::pipeline::Outcome,
            storage::query_log::{QueryLogRecord, QueryLogRepository},
        };

        let ts = TestServer::login().await;

        // Seed three persisted rows; ascending ts → ascending ids (1, 2, 3).
        let repo = ts.app.db.query_log();
        for (row_ts, name) in [(1, "a.test."), (2, "b.test."), (3, "c.test.")] {
            repo.insert_batch(&[QueryLogRecord {
                id: 0,
                ts: row_ts,
                client: "10.0.0.9".to_owned(),
                qname: name.to_owned(),
                qtype: "A".to_owned(),
                outcome: Outcome::Forwarded,
                rcode: Some(0),
                upstream: None,
                latency_ms: 1,
                blocklist_id: None,
            }])
            .await
            .unwrap();
        }

        // The initial page renders all three rows from the DB, newest-first, and
        // seeds the scroll-back cursor with the smallest id (1).
        let page = ts
            .client
            .get(ts.url("/log"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("a.test"));
        assert!(page.contains("c.test"));
        let c_pos = page.find("c.test").unwrap();
        let a_pos = page.find("a.test").unwrap();
        assert!(c_pos < a_pos, "newest (c) must render before oldest (a)");
        assert!(page.contains("oldest: 1"), "cursor seeded to smallest id");
        assert!(page.contains("Load older"));

        // Scroll back from id 2 → only the older row (id 1, a.test) appended.
        let older = ts
            .client
            .get(ts.url("/log/older?before=2"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(older.contains("datastar-patch-elements"));
        assert!(older.contains("log-body"));
        assert!(older.contains("a.test"));
        assert!(!older.contains("b.test"), "no overlap with the seen page");
        assert!(!older.contains("c.test"));
        assert!(older.contains(r#""oldest":1"#), "cursor advances to id 1");

        // Past the start: nothing to append, cursor resets to 0 (hides control).
        let empty = ts
            .client
            .get(ts.url("/log/older?before=1"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(empty.contains(r#""oldest":0"#));
        assert!(!empty.contains("datastar-patch-elements"));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn one_click_whitelist_persists_and_swaps() {
        use crate::{codec::name::Name, storage::lists::AllowlistRepository};

        let ts = TestServer::login().await;

        let dom: Name = "ads.example.com".parse().unwrap();
        assert!(!ts.app.resolver.allowlist().contains(&dom));

        // Without the CSRF token the mutation is rejected.
        let r = ts
            .client
            .post(ts.url("/log/unblock?domain=ads.example.com"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403);

        // With the token it succeeds and returns a Datastar toast patch. The
        // domain is not admin-blacklisted, so Unblock allowlists it.
        let r = ts
            .client
            .post(ts.url("/log/unblock?domain=ads.example.com"))
            .header("cookie", &ts.cookie)
            .header("x-csrf-token", &ts.csrf)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        let body = r.text().await.unwrap();
        assert!(body.contains("datastar-patch-elements"));
        assert!(body.contains("Unblocked"));

        // Persisted to the DB and swapped into the live set.
        assert!(ts.app.resolver.allowlist().contains(&dom));
        let names = ts.app.db.allowlist().load_all().await.unwrap();
        assert!(names.contains(&dom));

        // The real Datastar path: token in the JSON signal body (no header).
        // Block adds the resolved domain to the blacklist; the response is just
        // the toast — the button is not toggled.
        let dom2: Name = "ads2.example.com".parse().unwrap();
        let r = ts
            .client
            .post(ts.url("/log/block?domain=ads2.example.com"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/json")
            .body(format!("{{\"csrf\":\"{}\",\"f_text\":\"\"}}", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        let body = r.text().await.unwrap();
        assert!(body.contains("Blocked"));
        assert!(!body.contains("act-"), "button must not be toggled");
        assert!(ts.app.resolver.blacklist().contains(&dom2));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn management_blacklist_form_roundtrip() {
        use crate::codec::name::Name;

        let ts = TestServer::login().await;
        let dom: Name = "ads.example.com".parse().unwrap();

        // Add via the management form (CSRF token travels as a form field).
        let r = ts
            .client
            .post(ts.url("/blacklist/add"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!("csrf_token={}&domain=ads.example.com", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/blacklist");
        assert!(ts.app.resolver.blacklist().contains(&dom));

        // The page lists the entry, shown without the canonical trailing dot.
        let page = ts
            .client
            .get(ts.url("/blacklist"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("ads.example.com"));
        assert!(!page.contains("ads.example.com."));

        // A form missing the CSRF token is rejected.
        let r = ts
            .client
            .post(ts.url("/blacklist/add"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body("domain=evil.example.com")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403);

        // Remove round-trips the in-memory set too.
        let r = ts
            .client
            .post(ts.url("/blacklist/remove"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!("csrf_token={}&domain=ads.example.com", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert!(!ts.app.resolver.blacklist().contains(&dom));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn settings_form_saves_over_http() {
        use crate::codec::synth::BlockMode;

        let ts = TestServer::login().await;

        // Seed defaults use null-ip; switch to nxdomain over the form.
        assert_eq!(ts.app.resolver.settings().block_mode, BlockMode::null_ip());
        let body = format!(
            "csrf_token={}&cache_min_ttl=10&cache_max_ttl=3600&cache_negative_ttl_cap=300\
             &cache_capacity=50000&blocking_mode=nxdomain&custom_block_ipv4=&custom_block_ipv6=\
             &blocklist_refresh_interval=7200&ui_theme=dark\
             &query_log_enabled=1&query_log_retention_days=30\
             &upstream_selection_strategy=random&upstream_parallel_fanout=2",
            ts.csrf
        );
        let r = ts
            .client
            .post(ts.url("/settings"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(body)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        assert!(r.text().await.unwrap().contains("Settings saved"));

        // The live runtime snapshot reflects the change immediately.
        assert_eq!(ts.app.resolver.settings().block_mode, BlockMode::NxDomain);
        assert_eq!(ts.app.resolver.settings().cache_max_ttl, 3600);

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn query_log_controls_render_and_clear_over_http() {
        use crate::{
            resolver::pipeline::Outcome,
            storage::query_log::{QueryLogRecord, QueryLogRepository},
        };

        let ts = TestServer::login().await;

        // The settings page renders the query-log toggle and retention input.
        let page = ts
            .client
            .get(ts.url("/settings"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("name=\"query_log_enabled\""));
        assert!(page.contains("name=\"query_log_retention_days\""));
        assert!(page.contains("/settings/clear-log"));

        // Seed a query-log row to be cleared.
        ts.app
            .db
            .query_log()
            .insert_batch(&[QueryLogRecord {
                id: 0,
                ts: 1,
                client: "10.0.0.1".to_owned(),
                qname: "x.test.".to_owned(),
                qtype: "A".to_owned(),
                outcome: Outcome::Forwarded,
                rcode: Some(0),
                upstream: None,
                latency_ms: 1,
                blocklist_id: None,
            }])
            .await
            .unwrap();

        // Without the CSRF token the clear action is rejected.
        let r = ts
            .client
            .post(ts.url("/settings/clear-log"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403, "clear-log without CSRF must be rejected");

        // With the token it succeeds and empties the log.
        let r = ts
            .client
            .post(ts.url("/settings/clear-log"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!("csrf_token={}", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        assert!(r.text().await.unwrap().contains("Query log cleared"));

        let remaining = ts.app.db.query_log().page(None, 10).await.unwrap();
        assert!(remaining.is_empty(), "clear-log must empty the table");

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn blocklist_sources_manage_over_http() {
        use crate::storage::blocklists::BlocklistRepository;

        let ts = TestServer::login().await;

        // Add a source via the form.
        let r = ts
            .client
            .post(ts.url("/blocklists/add"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!(
                "csrf_token={}&url=https://example.com/hosts.txt&format=hosts",
                ts.csrf
            ))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        let sources = ts.app.db.blocklists().list().await.unwrap();
        assert_eq!(sources.len(), 1);

        // The page lists it.
        let page = ts
            .client
            .get(ts.url("/blocklists"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("https://example.com/hosts.txt"));

        // The "Refresh now" button fires the trigger and reports it.
        let r = ts
            .client
            .post(ts.url("/blocklists/refresh"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!("csrf_token={}", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 200);
        assert!(r.text().await.unwrap().contains("Refresh started"));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn pause_and_resume_blocking_over_http() {
        let ts = TestServer::login().await;

        assert!(!ts.app.resolver.blocking_paused());

        // Without the CSRF token the pause mutation is rejected.
        let r = ts
            .client
            .post(ts.url("/blocking/pause"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body("minutes=5")
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 403, "pause without CSRF must be rejected");
        assert!(!ts.app.resolver.blocking_paused());

        // With the token it pauses and redirects to the dashboard.
        let r = ts
            .client
            .post(ts.url("/blocking/pause"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!("csrf_token={}&minutes=5", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert_eq!(r.headers().get("location").unwrap(), "/");
        assert!(ts.app.resolver.blocking_paused());

        // Every page now renders the countdown banner and the pause control.
        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("Blocking paused"));
        assert!(page.contains("data-on-interval"));
        assert!(page.contains("Pause for 5 min"));
        assert!(page.contains("/blocking/resume"));

        // Resume clears the pause.
        let r = ts
            .client
            .post(ts.url("/blocking/resume"))
            .header("cookie", &ts.cookie)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!("csrf_token={}", ts.csrf))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 303);
        assert!(!ts.app.resolver.blocking_paused());

        // With blocking active again, the banner is gone.
        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(!page.contains("Blocking paused"));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn navbar_renders_responsive_hamburger_and_icon_sprite() {
        let ts = TestServer::login().await;

        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();

        // The hamburger toggle drives a Datastar `navOpen` signal, and the
        // link row / actions collapse via the shared `sgt-collapse--open` class.
        // Asset URLs carry a cache-busting ?v= token so an upgraded binary's
        // CSS/JS reaches browsers holding an immutable-cached previous build.
        assert!(page.contains("/assets/app.css?v="));
        assert!(page.contains("/assets/datastar.js?v="));
        // Icons declare an intrinsic 1em size, so a missing/stale stylesheet can
        // never blow them up to the SVG default 300x150.
        assert!(page.contains("<svg class=\"sgt-icon\" width=\"1em\" height=\"1em\""));

        assert!(page.contains("data-signals=\"{navOpen: false}\""));
        assert!(page.contains("class=\"sgt-hamburger\""));
        assert!(page.contains("data-on:click=\"$navOpen = !$navOpen\""));
        assert!(page.contains("data-class=\"{'sgt-collapse--open': $navOpen}\""));
        // The hamburger renders icons from the embedded sprite via <use>.
        assert!(page.contains("/assets/icons.svg#menu"));
        assert!(page.contains("/assets/icons.svg#close"));
        // Each nav section and the authenticated controls carry their icon.
        for id in [
            "dashboard",
            "log",
            "blacklist",
            "allowlist",
            "local",
            "blocklists",
            "upstreams",
            "forwarding",
            "settings",
            "pause",
            "logout",
        ] {
            assert!(
                page.contains(&format!("/assets/icons.svg#{id}")),
                "nav missing icon {id}"
            );
        }

        // The sprite itself is served as SVG and carries the referenced symbols.
        let sprite = ts
            .client
            .get(ts.url("/assets/icons.svg"))
            .send()
            .await
            .unwrap();
        assert_eq!(sprite.status(), 200);
        assert!(
            sprite
                .headers()
                .get("content-type")
                .unwrap()
                .to_str()
                .unwrap()
                .contains("image/svg+xml")
        );
        let body = sprite.text().await.unwrap();
        assert!(body.contains("<symbol id=\"menu\""));
        assert!(body.contains("<symbol id=\"dashboard\""));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn dashboard_decorates_sections_and_cards_with_icons() {
        let ts = TestServer::login().await;

        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();

        // Section headings and a representative spread of stat-card metrics
        // render their icons from the embedded sprite.
        for id in [
            "live", "system", "history", "health", "talkers", // section headings
            "queries", "blocked", "ratio", "uptime", "qps", "memory", // cards
        ] {
            assert!(
                page.contains(&format!("/assets/icons.svg#{id}")),
                "dashboard missing icon {id}"
            );
        }

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn management_pages_carry_heading_and_action_icons() {
        let ts = TestServer::login().await;

        // Page heading icon + the "add" action icon on each management page.
        for (path, heading) in [
            ("/upstreams", "upstreams"),
            ("/local", "local"),
            ("/blocklists", "blocklists"),
            ("/settings", "settings"),
            ("/blacklist", "blacklist"),
        ] {
            let page = ts
                .client
                .get(ts.url(path))
                .header("cookie", &ts.cookie)
                .send()
                .await
                .unwrap()
                .text()
                .await
                .unwrap();
            assert!(
                page.contains(&format!("/assets/icons.svg#{heading}")),
                "{path} missing heading icon {heading}"
            );
        }

        // The live-log "load older" button uses the colon event binding (the
        // hyphen form registers no handler in this Datastar build).
        let log = ts
            .client
            .get(ts.url("/log"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(log.contains("data-on:click=\"@get('/log/older?before=' + $oldest)\""));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn topbar_theme_toggle_flips_light_and_dark() {
        let ts = TestServer::login().await;

        // Fresh install defaults to `auto`; the topbar button offers "go dark".
        let page = ts
            .client
            .get(ts.url("/"))
            .header("cookie", &ts.cookie)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(page.contains("data-theme=\"auto\""));
        assert!(page.contains("action=\"/theme/toggle\""));
        assert!(page.contains("/assets/icons.svg#moon"));

        let toggle = |to_check: &'static str| {
            let ts = &ts;
            async move {
                let r = ts
                    .client
                    .post(ts.url("/theme/toggle"))
                    .header("cookie", &ts.cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(format!("csrf_token={}", ts.csrf))
                    .send()
                    .await
                    .unwrap();
                assert!(r.status().is_redirection(), "toggle should PRG-redirect");
                let page = ts
                    .client
                    .get(ts.url("/"))
                    .header("cookie", &ts.cookie)
                    .send()
                    .await
                    .unwrap()
                    .text()
                    .await
                    .unwrap();
                assert!(
                    page.contains(&format!("data-theme=\"{to_check}\"")),
                    "expected theme {to_check}"
                );
                page
            }
        };

        // auto → dark: the page renders dark and the button now offers "go light".
        let dark = toggle("dark").await;
        assert!(dark.contains("/assets/icons.svg#sun"));

        // dark → light.
        let light = toggle("light").await;
        assert!(light.contains("/assets/icons.svg#moon"));

        ts.shutdown().await;
    }

    #[tokio::test]
    async fn bind_serves_and_shuts_down_cleanly() {
        let (_dir, state) = test_state().await;
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let server = AdminServer::bind(addr, state).await.expect("bind");
        let bound = server.local_addr().expect("local addr");

        let token = CancellationToken::new();
        let token2 = token.clone();
        let handle = tokio::spawn(async move { server.serve(token2).await });

        // The index page is served from the embedded assets (no network fetch).
        let body = reqwest::get(format!("http://{bound}/"))
            .await
            .expect("request index")
            .text()
            .await
            .expect("body");
        assert!(body.contains("sagittarius"));

        // Assets are served from the binary.
        let css = reqwest::get(format!("http://{bound}/assets/app.css"))
            .await
            .expect("request css");
        assert_eq!(css.status(), 200);

        // Cancellation drains the server promptly.
        token.cancel();
        tokio::time::timeout(std::time::Duration::from_secs(5), handle)
            .await
            .expect("server did not shut down in time")
            .expect("server task panicked");
    }
}