runbound 0.4.4

RFC-compliant DNS resolver — drop-in Unbound with REST API, ACME auto-TLS, HMAC audit log, and master/slave HA
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 RedLemonBe — https://github.com/redlemonbe/Runbound
// Runbound REST API — full DNS management + feeds + DoT/DoH status

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use std::net::IpAddr;

use dashmap::DashMap;

use std::convert::Infallible;
use std::time::Duration;

use axum::{
    extract::{Path, Query, State, rejection::QueryRejection},
    http::{HeaderValue, Request, StatusCode},
    middleware::{self, Next},
    response::{IntoResponse, Response},
    response::sse::{Event, KeepAlive, Sse},
    Json as JsonExtract,
    Router,
    routing::{delete, get, post},
};
use arc_swap::ArcSwap;
use futures_util::stream;
use serde::Deserialize;
use tokio::sync::Mutex;
use tracing::{error, info, warn};

use crate::dns::{BlacklistAction, ZoneAction, local::{LocalZoneSet, parse_local_data}};
use crate::feeds::{self, FeedFormat, add_feed, builtin_presets, remove_feed, update_all_feeds, update_one_feed};
use crate::logbuffer::{LogAction, LogQuery, SharedLogBuffer};
use crate::store::{self, DnsEntry, DnsType, BlacklistEntry};
use crate::config::parser::{TlsConfig, UnboundConfig};
use crate::stats::Stats;
use crate::audit::{AuditEvent, AuditLogger};
use crate::sync::{SyncJournal, SyncOp};
use crate::upstreams::SharedUpstreams;

/// Max TTL for API-created DNS entries (86400 s = 24 h).
/// Prevents TTL-based cache persistence attacks and operator mistakes.
const MAX_API_TTL: u32 = 86_400;

// ── Custom JSON body extractor ─────────────────────────────────────────────
// axum's default Json<T> extractor returns a plain-text 422/400 body on
// deserialization failure (Q-01, Q-02, Q-03). ApiJson<T> wraps it and always
// returns a structured JSON error body so clients can parse the failure
// programmatically.

struct ApiJson<T>(T);

#[axum::async_trait]
impl<T, S> axum::extract::FromRequest<S> for ApiJson<T>
where
    T: serde::de::DeserializeOwned,
    S: Send + Sync,
{
    type Rejection = (StatusCode, axum::Json<serde_json::Value>);

    async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
        match axum::Json::<T>::from_request(req, state).await {
            Ok(axum::Json(val)) => Ok(ApiJson(val)),
            Err(rejection) => {
                use axum::extract::rejection::JsonRejection;
                let (status, msg) = match rejection {
                    JsonRejection::JsonDataError(e)        => (StatusCode::UNPROCESSABLE_ENTITY, e.to_string()),
                    JsonRejection::JsonSyntaxError(e)      => (StatusCode::BAD_REQUEST,          e.to_string()),
                    JsonRejection::MissingJsonContentType(e) => (StatusCode::UNSUPPORTED_MEDIA_TYPE, e.to_string()),
                    e                                      => (StatusCode::BAD_REQUEST,          e.to_string()),
                };
                Err((status, axum::Json(serde_json::json!({
                    "error":   "INVALID_REQUEST",
                    "details": msg
                }))))
            }
        }
    }
}

// ── API security constants ─────────────────────────────────────────────────

/// API key — stored in an ArcSwap so it can be rotated live via POST /rotate-key.
static API_KEY: std::sync::OnceLock<ArcSwap<String>> = std::sync::OnceLock::new();

/// Global authentication failure counter (reset on every successful auth).
/// Used to detect and slow brute-force attempts without per-IP state.
static AUTH_FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Max JSON body size (64 KiB) — prevents OOM via huge payloads.
const MAX_BODY_BYTES: usize = 65_536;

/// API rate limit: max requests per IP per second.
const API_RATE_LIMIT_RPS: u64 = 30;
const API_RATE_BURST: u64 = 60;

/// Hard cap on persisted DNS entries — prevents authenticated DoS / OOM.
const MAX_DNS_ENTRIES: usize = 10_000;
/// Hard cap on blacklist entries (feeds can add millions; the API is manual).
const MAX_BLACKLIST_ENTRIES: usize = 100_000;
/// Hard cap on feed subscriptions. Each feed can download up to 100 MiB;
/// without this limit an authenticated client could trigger unbounded I/O.
const MAX_FEEDS: usize = 100;

/// Priority: HSM > RUNBOUND_API_KEY env var > api-key in unbound.conf > auto-generate.
/// Auto-generated keys are 256-bit CSPRNG (2× UUID v4, backed by getrandom).
pub fn init_api_key(config_key: Option<String>) -> String {
    let key = crate::hsm::api_key().map(|k| k.to_string())
        .or_else(|| std::env::var("RUNBOUND_API_KEY").ok())
        .or(config_key)
        .unwrap_or_else(|| {
            // 256 bits from OS CSPRNG — two UUID v4s = 64 hex chars.
            // Previous implementation used PID+timestamp (deterministic → weak).
            format!("{}{}",
                uuid::Uuid::new_v4().simple(),
                uuid::Uuid::new_v4().simple())
        });
    API_KEY.get_or_init(|| ArcSwap::from(Arc::new(key.clone())));
    key
}

/// Returns the current API key as an owned Arc — zero-copy for the common read path.
pub fn get_api_key() -> Arc<String> {
    API_KEY.get()
        .map(|s| s.load_full())
        .unwrap_or_else(|| Arc::new(String::new()))
}

/// Atomically replaces the active API key. The old key is invalidated immediately.
pub fn rotate_api_key(new_key: String) {
    if let Some(swap) = API_KEY.get() {
        swap.store(Arc::new(new_key));
    }
}

// ── API rate limiter ───────────────────────────────────────────────────────

struct ApiBucket { tokens: u64, last: Instant }

// DashMap: each shard has its own RwLock — no global lock, parallel IPs don't
// contend. check() is sync (no .await), keeping the hot middleware path lean.
// AHash: faster than SipHash for IpAddr keys (same HashDoS resistance, v0.8+).
#[derive(Clone)]
pub struct ApiRateLimiter(Arc<DashMap<IpAddr, ApiBucket, ahash::RandomState>>);

impl ApiRateLimiter {
    fn new() -> Self {
        Self(Arc::new(DashMap::with_hasher(ahash::RandomState::default())))
    }
    pub fn new_public() -> Self { Self::new() }
    #[inline]
    fn check(&self, ip: IpAddr) -> bool {
        let now = Instant::now();
        let mut b = self.0.entry(ip).or_insert(ApiBucket { tokens: API_RATE_BURST, last: now });
        let elapsed_ms = now.duration_since(b.last).as_millis() as u64;
        if elapsed_ms >= 1000 {
            b.tokens = API_RATE_BURST; b.last = now;
        } else {
            let new = (API_RATE_LIMIT_RPS * elapsed_ms) / 1000;
            if new > 0 { b.tokens = (b.tokens + new).min(API_RATE_BURST); b.last = now; }
        }
        if b.tokens > 0 { b.tokens -= 1; true } else { false }
    }
}

// ── Shared state ───────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct AppState {
    pub zones:        Arc<ArcSwap<LocalZoneSet>>,
    // Serialises concurrent API writes: load-clone-modify-store is not atomic,
    // so two simultaneous POST /dns would race without this guard.
    // DNS reads (every query) never touch this mutex — zero read overhead.
    pub zones_mutex:  Arc<Mutex<()>>,
    pub tls_cfg:      Arc<TlsConfig>,
    pub rate_limiter: ApiRateLimiter,
    pub stats:        Arc<Stats>,
    pub cfg:          Arc<UnboundConfig>,
    pub cfg_path:     String,
    pub log_buffer:   SharedLogBuffer,
    pub upstreams:    SharedUpstreams,
    /// Master: Some(journal) to record write events for slave replication.
    /// Slave / standalone: None.
    pub sync_journal: Option<Arc<SyncJournal>>,
    /// True when running as slave — all write operations are blocked (503).
    pub slave_mode:   bool,
    /// Directory where runtime files (api.key, dns_entries.json, …) are stored.
    pub base_dir:     Arc<PathBuf>,
    /// Immutable audit log sender. No-op when audit is disabled.
    pub audit:        AuditLogger,
}

// ── Request types ──────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
pub struct AddDnsRequest {
    pub name: String,
    #[serde(rename = "type")]
    pub entry_type: DnsType,
    // i64 so serde accepts negative values and we can return a uniform JSON 422
    // instead of axum's default plain-text deserialization error.
    #[serde(default = "default_ttl_i64")]
    pub ttl: i64,
    // simple types
    pub value: Option<String>,
    // MX / SRV priority
    pub priority: Option<u16>,
    // SRV
    pub weight: Option<u16>,
    pub port: Option<u16>,
    // CAA
    pub flags: Option<u8>,
    pub tag: Option<String>,
    // NAPTR
    pub order: Option<u16>,
    pub preference_naptr: Option<u16>,
    pub flags_naptr: Option<String>,
    pub services: Option<String>,
    pub regexp: Option<String>,
    pub replacement: Option<String>,
    // SSHFP
    pub algorithm: Option<u8>,
    pub fp_type: Option<u8>,
    pub fingerprint: Option<String>,
    // TLSA
    pub cert_usage: Option<u8>,
    pub selector: Option<u8>,
    pub matching_type: Option<u8>,
    pub cert_data: Option<String>,
    pub description: Option<String>,
}

fn default_ttl_i64() -> i64 { 3600 }

#[derive(Debug, Deserialize)]
pub struct AddFeedRequest {
    pub name: String,
    pub url: String,
    #[serde(default)]
    pub format: FeedFormat,
    #[serde(default)]
    pub action: BlacklistAction,
    pub description: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct AddBlacklistRequest {
    pub domain: String,
    #[serde(default)]
    pub action: BlacklistAction,
    pub description: Option<String>,
}

// ── Security middleware ────────────────────────────────────────────────────

async fn security_middleware(
    State(state): State<AppState>,
    req: Request<axum::body::Body>,
    next: Next,
) -> Response {
    // ── 0. Body size pre-check (S-11) ────────────────────────────────
    // DefaultBodyLimit fires at extraction time inside the handler, not here.
    // A large body would therefore hit the rate limiter first and return 429
    // instead of 413. Checking Content-Length early produces the correct 413
    // for over-sized requests before the rate limit token is consumed.
    if let Some(cl) = req.headers().get(axum::http::header::CONTENT_LENGTH) {
        let len: usize = cl.to_str().unwrap_or("0").parse().unwrap_or(0);
        if len > MAX_BODY_BYTES {
            return (StatusCode::PAYLOAD_TOO_LARGE, axum::Json(serde_json::json!({
                "error": "REQUEST_TOO_LARGE",
                "details": format!("Body exceeds {} bytes", MAX_BODY_BYTES)
            }))).into_response();
        }
    }

    // ── 1. Rate limiting ──────────────────────────────────────────────
    // VUL-04: Never trust X-Forwarded-For. The API is bound exclusively to
    // 127.0.0.1 so the real peer is always localhost. Accepting XFF would let
    // any caller spoof an arbitrary IP to bypass per-IP rate limiting.
    let client_ip: IpAddr = IpAddr::from([127, 0, 0, 1]);

    if !state.rate_limiter.check(client_ip) {
        warn!(%client_ip, "API rate limited");
        return (StatusCode::TOO_MANY_REQUESTS,
            [(axum::http::header::RETRY_AFTER, "1")],
            "Rate limit exceeded").into_response();
    }

    // ── 2. API key authentication (Bearer token) ──────────────────────
    // ALL endpoints require authentication — including /help.
    // Exposing version, endpoint list, or RFCs without auth enables
    // fingerprinting and targeted exploitation (AUDIT-HIGH-02).
    let path = req.uri().path();
    {
        let auth = req.headers()
            .get(axum::http::header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        let key = get_api_key();
        let expected = format!("Bearer {}", key.as_str());
        if !constant_time_eq(auth.as_bytes(), expected.as_bytes()) {
            // Increment global auth-failure counter (localhost-only API,
            // so per-IP tracking adds nothing; we track globally).
            let failures = AUTH_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
            state.audit.send(AuditEvent::AuthFailure { path: path.to_string() });
            if failures.is_multiple_of(10) {
                warn!(failures, %path, "Repeated API authentication failures — check RUNBOUND_API_KEY");
            }
            // Threshold 50 is reachable within one rate-limiter burst window (burst=60).
            // At 100 the rate limiter would pre-empt most rapid attacks before the
            // counter could accumulate, making the lockout unobservable.
            if failures >= 50 {
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }
            return (StatusCode::UNAUTHORIZED,
                [(axum::http::header::WWW_AUTHENTICATE, "Bearer realm=\"runbound\"")],
                "Unauthorized").into_response();
        }
        // Successful auth resets the failure counter.
        AUTH_FAILURES.store(0, std::sync::atomic::Ordering::Relaxed);
    }

    // ── 3. Security response headers ──────────────────────────────────
    let mut response = next.run(req).await;
    let headers = response.headers_mut();
    headers.insert("x-content-type-options",    HeaderValue::from_static("nosniff"));
    headers.insert("x-frame-options",           HeaderValue::from_static("DENY"));
    headers.insert("x-xss-protection",          HeaderValue::from_static("1; mode=block"));
    headers.insert("referrer-policy",           HeaderValue::from_static("no-referrer"));
    headers.insert("content-security-policy",   HeaderValue::from_static("default-src 'none'"));
    headers.insert("cache-control",             HeaderValue::from_static("no-store"));
    // Disable nginx response buffering so SSE events reach the client immediately.
    headers.insert("x-accel-buffering",         HeaderValue::from_static("no"));
    response
}

/// Constant-time byte-slice comparison.
/// VUL-01 fix: the previous implementation had an early-exit on length mismatch,
/// leaking whether the submitted token had the correct length (timing oracle).
/// This version encodes the length mismatch as a byte difference and always
/// iterates b.len() bytes — timing depends only on key length, never on content.
#[inline(always)]
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    use subtle::ConstantTimeEq;
    // Fold length mismatch into the accumulator as a non-zero seed.
    // Then XOR every byte of b against the corresponding byte of a
    // (using 0x00 padding when a is shorter). No early exit anywhere.
    let len_mismatch = u8::from(a.len() != b.len());
    let diff: u8 = b.iter().enumerate()
        .fold(len_mismatch, |acc, (i, &bi)| {
            acc | (a.get(i).copied().unwrap_or(0) ^ bi)
        });
    diff.ct_eq(&0u8).into()
}

// ── Slave write guard ──────────────────────────────────────────────────────

async fn slave_guard_middleware(
    State(state): State<AppState>,
    req: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if state.slave_mode && req.method() != axum::http::Method::GET {
        return (StatusCode::SERVICE_UNAVAILABLE, JsonExtract(serde_json::json!({
            "error":   "READ_ONLY",
            "details": "This node is a slave replica — write operations are disabled",
        }))).into_response();
    }
    next.run(req).await
}

// ── Router ─────────────────────────────────────────────────────────────────

pub fn router(state: AppState) -> Router {
    Router::new()
        // Info
        .route("/help",              get(help_handler))
        // Operations
        .route("/health",            get(health_handler))
        .route("/stats",             get(stats_handler))
        .route("/stats/stream",      get(stats_stream_handler))
        .route("/config",            get(config_handler))
        .route("/reload",            post(reload_handler))
        // DNS CRUD
        .route("/dns",               get(list_dns_handler).post(add_dns_handler))
        .route("/dns/:id",           delete(delete_dns_handler))
        // Blacklist
        .route("/blacklist",         get(list_blacklist_handler).post(add_blacklist_handler))
        .route("/blacklist/:id",     delete(delete_blacklist_handler))
        // Feeds
        .route("/feeds",             get(get_feeds_handler).post(add_feed_handler))
        .route("/feeds/presets",     get(feed_presets_handler))
        .route("/feeds/update",      post(update_feeds_handler))
        .route("/feeds/:id",         delete(delete_feed_handler))
        .route("/feeds/:id/update",  post(update_one_feed_handler))
        // TLS / Protocol status
        .route("/tls",               get(tls_status_handler))
        // Monitoring
        .route("/upstreams",         get(upstreams_handler))
        .route("/logs",              get(logs_handler).delete(clear_logs_handler))
        .route("/audit/tail",        get(audit_tail_handler))
        .route("/metrics",           get(metrics_handler))
        // Administration
        .route("/rotate-key",        post(rotate_key_handler))
        .layer(middleware::from_fn_with_state(state.clone(), slave_guard_middleware))
        .layer(middleware::from_fn_with_state(state.clone(), security_middleware))
        // axum DefaultBodyLimit returns HTTP 413 before reading the body into RAM,
        // regardless of payload size. tower_http::RequestBodyLimitLayer drops the
        // TCP connection for very large payloads (> ~512 KB) instead of 413.
        .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
        .with_state(state)
}

// ── GET /help ──────────────────────────────────────────────────────────────

async fn help_handler() -> impl IntoResponse {
    JsonExtract(serde_json::json!({
        "service": "Runbound DNS",
        "version": env!("CARGO_PKG_VERSION"),
        "protocols": ["DNS/UDP:53","DNS/TCP:53","DoT:853","DoH:443","DoQ:853/UDP"],
        "rfcs": ["RFC1034","RFC1035","RFC2782","RFC4033","RFC4034","RFC4035","RFC6698","RFC6891","RFC7858","RFC8484","RFC9250"],
        "endpoints": [
            {"method":"GET",    "path":"/help",             "description":"API documentation"},
            {"method":"GET",    "path":"/health",           "description":"Liveness check"},
            {"method":"GET",    "path":"/stats",            "description":"Query statistics snapshot"},
            {"method":"GET",    "path":"/stats/stream",     "description":"Live stats as Server-Sent Events (1-second interval)"},
            {"method":"GET",    "path":"/config",           "description":"Running configuration"},
            {"method":"POST",   "path":"/reload",           "description":"Hot-reload zones and blacklist from disk"},
            {"method":"GET",    "path":"/dns",              "description":"List all local DNS entries"},
            {"method":"POST",   "path":"/dns",              "description":"Add a local DNS entry (A/AAAA/CNAME/TXT/MX/SRV/CAA/PTR/NAPTR/SSHFP/TLSA/NS)"},
            {"method":"DELETE", "path":"/dns/:id",          "description":"Remove a DNS entry by UUID"},
            {"method":"GET",    "path":"/blacklist",        "description":"List blacklist entries"},
            {"method":"POST",   "path":"/blacklist",        "description":"Add a domain to the blacklist (refuse/nxdomain)"},
            {"method":"DELETE", "path":"/blacklist/:id",    "description":"Remove a blacklist entry"},
            {"method":"GET",    "path":"/feeds",            "description":"List feed subscriptions"},
            {"method":"POST",   "path":"/feeds",            "description":"Subscribe to a remote blocklist"},
            {"method":"DELETE", "path":"/feeds/:id",        "description":"Remove a feed subscription"},
            {"method":"POST",   "path":"/feeds/update",     "description":"Refresh all feeds"},
            {"method":"POST",   "path":"/feeds/:id/update", "description":"Refresh one feed"},
            {"method":"GET",    "path":"/feeds/presets",    "description":"List pre-configured blocklists"},
            {"method":"GET",    "path":"/tls",              "description":"DoT/DoH/DoQ TLS status"},
            {"method":"GET",    "path":"/upstreams",        "description":"Upstream DNS resolver health"},
            {"method":"GET",    "path":"/logs",             "description":"Recent query log (newest first) — ?limit=100&page=0&action=blocked&client=1.2.3.4&since=<unix>"},
            {"method":"DELETE", "path":"/logs",             "description":"Clear the in-memory query log ring buffer (GDPR right-to-erasure)"},
            {"method":"GET",    "path":"/audit/tail",       "description":"Last N audit log entries — ?n=100"},
            {"method":"GET",    "path":"/metrics",          "description":"Prometheus/OpenMetrics exposition (text/plain; version=0.0.4)"},
            {"method":"POST",   "path":"/rotate-key",       "description":"Atomically rotate API key — reads new key from RUNBOUND_API_KEY env var"},
        ]
    }))
}

// ── GET /health ────────────────────────────────────────────────────────────

async fn health_handler(State(s): State<AppState>) -> impl IntoResponse {
    let snap = s.stats.snapshot();
    JsonExtract(serde_json::json!({
        "status":      "ok",
        "uptime_secs": snap.uptime_secs,
        "queries":     snap.total,
        "hsm":         crate::hsm::is_active(),
    }))
}

// ── GET /stats ─────────────────────────────────────────────────────────────

async fn stats_handler(State(s): State<AppState>) -> impl IntoResponse {
    JsonExtract(stats_json(&s.stats.snapshot()))
}

fn stats_json(snap: &crate::stats::StatsSnapshot) -> serde_json::Value {
    let pct_blocked = if snap.total > 0 {
        (snap.blocked as f64 / snap.total as f64 * 1000.0).round() / 10.0
    } else { 0.0 };
    serde_json::json!({
        "total":            snap.total,
        "blocked":          snap.blocked,
        "forwarded":        snap.forwarded,
        "nxdomain":         snap.nxdomain,
        "refused":          snap.refused,
        "servfail":         snap.servfail,
        "local_hits":       snap.local_hits,
        "blocked_percent":  pct_blocked,
        "uptime_secs":      snap.uptime_secs,
        "qps_1m":           snap.qps_1m,
        "qps_5m":           snap.qps_5m,
        "qps_peak":         snap.qps_peak,
        "latency_p50_ms":   snap.latency_p50_ms,
        "latency_p95_ms":   snap.latency_p95_ms,
        "latency_p99_ms":   snap.latency_p99_ms,
        "cache_hit_rate":   snap.cache_hit_rate,
        "cache_entries":    snap.cache_entries,
        "dnssec": {
            "secure":   snap.dnssec_secure,
            "bogus":    snap.dnssec_bogus,
            "insecure": snap.dnssec_insecure,
        },
    })
}

// ── GET /stats/stream ──────────────────────────────────────────────────────

async fn stats_stream_handler(
    State(s): State<AppState>,
) -> Sse<impl stream::Stream<Item = Result<Event, Infallible>>> {
    let sse_stream = stream::unfold(s.stats, |stats| async move {
        tokio::time::sleep(Duration::from_secs(1)).await;
        let data = stats_json(&stats.snapshot()).to_string();
        let event = Event::default().data(data);
        Some((Ok::<Event, Infallible>(event), stats))
    });
    Sse::new(sse_stream).keep_alive(KeepAlive::default())
}

// ── GET /config ────────────────────────────────────────────────────────────

async fn config_handler(State(s): State<AppState>) -> impl IntoResponse {
    let cfg = s.cfg.as_ref();
    // Live counts include both config-file entries and API-managed entries.
    let api_dns   = store::load().map(|st| st.entries.len()).unwrap_or(0);
    let api_bl    = store::load_blacklist().map(|bl| bl.entries.len()).unwrap_or(0);
    let api_feeds = crate::feeds::load_feeds().map(|f| f.feeds.len()).unwrap_or(0);
    JsonExtract(serde_json::json!({
        "port":              cfg.port,
        "interfaces":        cfg.interfaces,
        "forward_zones":     cfg.forward_zones.iter().map(|fz| serde_json::json!({
            "name":  fz.name,
            "addrs": fz.addrs,
            "tls":   fz.tls,
        })).collect::<Vec<_>>(),
        // file_* = entries from runbound.conf; api_* = entries added via REST API
        "file_local_zones":  cfg.local_zones.len(),
        "file_local_data":   cfg.local_data.len(),
        "api_dns_entries":   api_dns,
        "api_blacklist":     api_bl,
        "api_feeds":         api_feeds,
        "access_control":    cfg.access_control,
        "private_addresses": cfg.private_addresses,
        "rate_limit":        cfg.rate_limit,
        "cache_max_ttl":     cfg.cache_max_ttl,
        "dnssec_validation": cfg.dnssec_validation,
        "log_retention":     cfg.log_retention,
        "log_client_ip":     cfg.log_client_ip,
        "api_port":          cfg.api_port,
        // api_key intentionally omitted — secret
        "logfile":           cfg.logfile,
        // HSM config — pin masked
        "hsm": serde_json::json!({
            "active":            crate::hsm::is_active(),
            "pkcs11_lib":        cfg.hsm_pkcs11_lib,
            "slot":              cfg.hsm_slot,
            "pin":               cfg.hsm_pin.as_ref().map(|_| "***"),
            "api_key_label":     cfg.hsm_api_key_label,
            "store_key_label":   cfg.hsm_store_key_label,
        }),
    }))
}

// ── POST /reload ────────────────────────────────────────────────────────────

async fn reload_handler(State(s): State<AppState>) -> impl IntoResponse {
    match crate::config::load(&s.cfg_path) {
        Ok(new_cfg) => {
            let new_zones = crate::build_zone_set(&new_cfg);
            s.zones.store(std::sync::Arc::new(new_zones));
            info!(cfg_path = %s.cfg_path, "API hot-reload complete");
            s.audit.send(AuditEvent::ConfigReload);
            (StatusCode::OK, JsonExtract(serde_json::json!({
                "status":      "ok",
                "cfg_path":    s.cfg_path,
                "local_zones": new_cfg.local_zones.len(),
                "local_data":  new_cfg.local_data.len(),
            })))
        }
        Err(e) => {
            warn!(err = %e, "API reload failed — keeping current zones");
            (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
                "error":   "RELOAD_FAILED",
                "details": e.to_string(),
            })))
        }
    }
}

// ── DNS CRUD ───────────────────────────────────────────────────────────────

async fn list_dns_handler(State(_s): State<AppState>) -> impl IntoResponse {
    match store::load() {
        Ok(st) => (StatusCode::OK, JsonExtract(serde_json::json!({
            "entries": st.entries,
            "total": st.entries.len()
        }))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
            "error": e.to_string()
        }))),
    }
}

async fn add_dns_handler(
    State(s): State<AppState>,
    ApiJson(req): ApiJson<AddDnsRequest>,
) -> impl IntoResponse {
    // VUL-05: Reject malformed or dangerous names before any parsing.
    if let Err(e) = validate_dns_name(&req.name) {
        return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error": "INVALID_NAME", "details": e
        })));
    }
    // Reject control characters in free-text fields (CRLF injection prevention).
    for (field, val) in [
        ("value",       req.value.as_deref().unwrap_or("")),
        ("tag",         req.tag.as_deref().unwrap_or("")),
        ("description", req.description.as_deref().unwrap_or("")),
        ("fingerprint", req.fingerprint.as_deref().unwrap_or("")),
        ("cert_data",   req.cert_data.as_deref().unwrap_or("")),
        ("services",    req.services.as_deref().unwrap_or("")),
        ("regexp",      req.regexp.as_deref().unwrap_or("")),
        ("replacement", req.replacement.as_deref().unwrap_or("")),
        ("flags_naptr", req.flags_naptr.as_deref().unwrap_or("")),
    ] {
        if let Err(e) = validate_no_control_chars(val, field) {
            return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
                "error": "INVALID_FIELD", "details": e
            })));
        }
    }
    // S-10: for record types where value is a domain name, validate it as such.
    // validate_no_control_chars is not enough — it would accept a 300-char CNAME target.
    match req.entry_type {
        DnsType::CNAME | DnsType::NS | DnsType::PTR | DnsType::MX | DnsType::SRV => {
            if let Some(ref v) = req.value {
                if let Err(e) = validate_dns_name(v) {
                    return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
                        "error": "INVALID_VALUE", "details": e
                    })));
                }
            }
        }
        DnsType::NAPTR => {
            // replacement may be "." (no-replacement special case — RFC 2915 §2)
            if let Some(ref r) = req.replacement {
                if r != "." {
                    if let Err(e) = validate_dns_name(r) {
                        return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
                            "error": "INVALID_REPLACEMENT", "details": e
                        })));
                    }
                }
            }
        }
        _ => {}
    }

    // RFC 2181 §8: TTL is a non-negative 32-bit integer; values outside
    // [0, 2^31-1] must be rejected with a uniform JSON error.
    const RFC2181_MAX_TTL: i64 = 2_147_483_647;
    if req.ttl < 0 || req.ttl > RFC2181_MAX_TTL {
        return (StatusCode::UNPROCESSABLE_ENTITY, JsonExtract(serde_json::json!({
            "error": "INVALID_TTL",
            "details": "TTL must be between 0 and 2147483647"
        })));
    }
    let ttl = req.ttl as u32;
    let entry = DnsEntry {
        id:               DnsEntry::new_id(),
        name:             ensure_dot(&req.name),
        entry_type:       req.entry_type,
        ttl:              ttl.min(MAX_API_TTL),
        value:            req.value,
        priority:         req.priority,
        weight:           req.weight,
        port:             req.port,
        flags:            req.flags,
        tag:              req.tag,
        order:            req.order,
        preference_naptr: req.preference_naptr,
        flags_naptr:      req.flags_naptr,
        services:         req.services,
        regexp:           req.regexp,
        replacement:      req.replacement,
        algorithm:        req.algorithm,
        fp_type:          req.fp_type,
        fingerprint:      req.fingerprint,
        cert_usage:       req.cert_usage,
        selector:         req.selector,
        matching_type:    req.matching_type,
        cert_data:        req.cert_data,
        description:      req.description,
    };

    // Validate by converting to RR string and parsing
    let rr = match entry.to_rr_string() {
        Some(r) => r,
        None => return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error": "INVALID_ENTRY",
            "details": "Missing required fields for this record type"
        }))),
    };

    let record = match parse_local_data(&rr) {
        Some(r) => r,
        None => return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error": "PARSE_FAILED",
            "details": format!("Could not parse RR: {rr}")
        }))),
    };

    // Persist + inject atomically under zones_mutex.
    // VUL-FIX: store load/save MUST be inside the mutex.  Without this,
    // two concurrent POST /dns both load the same snapshot, each append
    // their entry, and the last writer wins — the other entry is silently
    // lost from the on-disk store (in-memory zones get both, but a restart
    // would only restore one).
    {
        let _guard = s.zones_mutex.lock().await;

        let mut st = store::load().unwrap_or_default();
        if st.entries.len() >= MAX_DNS_ENTRIES {
            return (StatusCode::UNPROCESSABLE_ENTITY, JsonExtract(serde_json::json!({
                "error": "LIMIT_EXCEEDED",
                "details": format!("Maximum {} DNS entries reached", MAX_DNS_ENTRIES)
            })));
        }
        st.entries.push(entry.clone());
        if let Err(e) = store::save(&st) {
            return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
                "error": e.to_string()
            })));
        }

        let current = s.zones.load_full();
        let mut new_zones = (*current).clone();
        let name = record.name.clone();
        new_zones.zones.entry(name.clone()).or_insert(ZoneAction::Static);
        new_zones.records.entry(name).or_default().push(record);
        s.zones.store(Arc::new(new_zones));
    }

    info!(id=%entry.id, name=%entry.name, r#type=?entry.entry_type, "DNS entry added");
    s.audit.send(AuditEvent::DnsAdd {
        name:  entry.name.clone(),
        rtype: format!("{:?}", entry.entry_type),
        value: entry.value.clone().unwrap_or_default(),
    });
    if let Some(ref j) = s.sync_journal {
        j.push(SyncOp::AddDns { entry: entry.clone() });
    }
    (StatusCode::CREATED, JsonExtract(serde_json::json!({
        "status": "ok",
        "entry": entry,
        "rr": rr
    })))
}

async fn delete_dns_handler(
    State(s): State<AppState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let _guard = s.zones_mutex.lock().await;

    let mut st = match store::load() {
        Ok(s) => s,
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({"error": e.to_string()}))),
    };

    let pos = st.entries.iter().position(|e| e.id == id);
    let Some(pos) = pos else {
        return (StatusCode::NOT_FOUND, JsonExtract(serde_json::json!({"error":"NOT_FOUND","id":id})));
    };

    let entry = st.entries.remove(pos);
    if let Err(e) = store::save(&st) {
        return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({"error": e.to_string()})));
    }

    // Remove from live zone set — ArcSwap write
    if let Some(rr) = entry.to_rr_string() {
        if let Some(record) = parse_local_data(&rr) {
            let current = s.zones.load_full();
            let mut new_zones = (*current).clone();
            let name = record.name.clone();
            if let Some(recs) = new_zones.records.get_mut(&name) {
                // VUL-08: match on the full Record (name + type + rdata + TTL),
                // not just the type. The old code removed ALL records of the
                // same type for the given name — e.g. deleting one A record
                // would silently wipe every A record for that name.
                let mut removed = false;
                recs.retain(|r| {
                    if !removed && r == &record {
                        removed = true;
                        false
                    } else {
                        true
                    }
                });
                if recs.is_empty() {
                    new_zones.records.remove(&name);
                    new_zones.zones.remove(&name);
                }
            }
            s.zones.store(Arc::new(new_zones));
        }
    }

    info!(id=%id, "DNS entry deleted");
    s.audit.send(AuditEvent::DnsDelete { id: id.clone() });
    if let Some(ref j) = s.sync_journal {
        j.push(SyncOp::DeleteDns { id: id.clone() });
    }
    (StatusCode::OK, JsonExtract(serde_json::json!({"status":"ok","deleted_id":id})))
}

// ── Blacklist ──────────────────────────────────────────────────────────────

async fn list_blacklist_handler(State(_s): State<AppState>) -> impl IntoResponse {
    match store::load_blacklist() {
        Ok(bl) => (StatusCode::OK, JsonExtract(serde_json::json!({
            "blacklist": bl.entries,
            "total": bl.entries.len()
        }))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
            "error": e.to_string()
        }))),
    }
}

async fn add_blacklist_handler(
    State(s): State<AppState>,
    ApiJson(req): ApiJson<AddBlacklistRequest>,
) -> impl IntoResponse {
    // VUL-05: Reject invalid domain names (empty, root zone, Unicode, etc.)
    if let Err(e) = validate_dns_name(&req.domain) {
        return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error": "INVALID_NAME", "details": e
        })));
    }
    if let Some(ref desc) = req.description {
        if let Err(e) = validate_no_control_chars(desc, "description") {
            return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
                "error": "INVALID_FIELD", "details": e
            })));
        }
    }
    // Persist + inject atomically under zones_mutex (same race-fix as add_dns).
    let entry = {
        let _guard = s.zones_mutex.lock().await;

        let mut bl = store::load_blacklist().unwrap_or_default();
        if bl.entries.len() >= MAX_BLACKLIST_ENTRIES {
            return (StatusCode::UNPROCESSABLE_ENTITY, JsonExtract(serde_json::json!({
                "error": "LIMIT_EXCEEDED",
                "details": format!("Maximum {} blacklist entries reached", MAX_BLACKLIST_ENTRIES)
            })));
        }
        let entry = BlacklistEntry {
            id:          uuid::Uuid::new_v4().to_string(),
            domain:      req.domain.clone(),
            action:      req.action.clone(),
            description: req.description.clone(),
        };
        bl.entries.push(entry.clone());
        if let Err(e) = store::save_blacklist(&bl) {
            return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
                "error": e.to_string()
            })));
        }

        let current = s.zones.load_full();
        let mut new_zones = (*current).clone();
        // VUL-09: override_zone so the blacklist entry always takes precedence
        // over any static zone with the same name defined in unbound.conf.
        new_zones.override_zone(&req.domain, ZoneAction::from(&req.action));
        s.zones.store(Arc::new(new_zones));

        entry
    };

    info!(domain=%req.domain, action=?req.action, "Blacklist entry added");
    s.audit.send(AuditEvent::BlacklistAdd { domain: entry.domain.clone() });
    if let Some(ref j) = s.sync_journal {
        j.push(SyncOp::AddBlacklist { entry: entry.clone() });
    }
    (StatusCode::CREATED, JsonExtract(serde_json::json!({
        "status": "ok",
        "entry": entry
    })))
}

async fn delete_blacklist_handler(
    State(s): State<AppState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let _guard = s.zones_mutex.lock().await;

    let mut bl = match store::load_blacklist() {
        Ok(b) => b,
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({"error": e.to_string()}))),
    };
    let pos = bl.entries.iter().position(|e| e.id == id);
    let Some(pos) = pos else {
        return (StatusCode::NOT_FOUND, JsonExtract(serde_json::json!({"error":"NOT_FOUND","id":id})));
    };
    let removed = bl.entries.remove(pos);
    if let Err(e) = store::save_blacklist(&bl) {
        return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({"error": e.to_string()})));
    }

    let current = s.zones.load_full();
    let mut new_zones = (*current).clone();
    new_zones.remove_zone(&removed.domain);
    s.zones.store(Arc::new(new_zones));

    info!(id=%id, domain=%removed.domain, "Blacklist entry deleted");
    s.audit.send(AuditEvent::BlacklistDelete { id: id.clone() });
    if let Some(ref j) = s.sync_journal {
        j.push(SyncOp::DeleteBlacklist { id: id.clone() });
    }
    (StatusCode::OK, JsonExtract(serde_json::json!({"status":"ok","deleted_id":id,"domain":removed.domain})))
}

// ── Feeds ──────────────────────────────────────────────────────────────────

async fn get_feeds_handler(State(_s): State<AppState>) -> impl IntoResponse {
    let config = feeds::load_feeds().unwrap_or_default();
    (StatusCode::OK, JsonExtract(serde_json::json!({"feeds": config.feeds, "total": config.feeds.len()})))
}

async fn add_feed_handler(
    State(s): State<AppState>,
    JsonExtract(p): JsonExtract<AddFeedRequest>,
) -> impl IntoResponse {
    // Enforce subscription cap before attempting download/validation.
    let current = feeds::load_feeds().unwrap_or_default();
    if current.feeds.len() >= MAX_FEEDS {
        return (StatusCode::UNPROCESSABLE_ENTITY, JsonExtract(serde_json::json!({
            "error": "LIMIT_EXCEEDED",
            "details": format!("Maximum {} feed subscriptions reached", MAX_FEEDS)
        })));
    }
    match add_feed(p.name, p.url, p.format, p.action, p.description).await {
        Ok(feed) => {
            info!("Feed added: {} ({})", feed.name, feed.url);
            s.audit.send(AuditEvent::FeedAdd {
                id:   feed.id.clone(),
                name: feed.name.clone(),
                url:  feed.url.clone(),
            });
            if let Some(ref j) = s.sync_journal {
                j.push(SyncOp::AddFeed { feed: feed.clone() });
            }
            (StatusCode::CREATED, JsonExtract(serde_json::json!({
                "status": "ok", "feed": feed,
                "message": "Run POST /feeds/:id/update to fetch domains."
            })))
        }
        Err(e) => {
            let code = StatusCode::from_u16(e.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            (code, JsonExtract(serde_json::json!({
                "error": "FEED_ERROR", "details": e.to_string()
            })))
        }
    }
}

async fn delete_feed_handler(
    State(s): State<AppState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match remove_feed(&id) {
        Ok(()) => {
            s.audit.send(AuditEvent::FeedDelete { id: id.clone() });
            if let Some(ref j) = s.sync_journal {
                j.push(SyncOp::DeleteFeed { id: id.clone() });
            }
            (StatusCode::OK, JsonExtract(serde_json::json!({"status":"ok","deleted_id":id})))
        }
        Err(crate::error::AppError::BadRequest(msg)) => (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({"error":"BAD_REQUEST","details":msg}))),
        Err(e) => (StatusCode::NOT_FOUND, JsonExtract(serde_json::json!({"error":"FEED_NOT_FOUND","details":e.to_string()}))),
    }
}

async fn update_feeds_handler(State(s): State<AppState>) -> impl IntoResponse {
    match update_all_feeds().await {
        Ok(results) => {
            let updated = results.iter().filter(|r| r.status == "updated").count();
            let errors  = results.iter().filter(|r| r.status == "error").count();
            // Rebuild zone set so newly downloaded feed domains are immediately active.
            let new_zones = crate::build_zone_set(&s.cfg);
            s.zones.store(std::sync::Arc::new(new_zones));
            info!(updated, errors, "Feed update complete — zones rebuilt");
            (StatusCode::OK, JsonExtract(serde_json::json!({
                "status": "ok", "results": results,
                "summary": {"updated": updated, "errors": errors}
            })))
        }
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({"error":e.to_string()}))),
    }
}

async fn update_one_feed_handler(
    State(s): State<AppState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    // Look up URL before updating (for journal event)
    let feed_url = feeds::load_feeds()
        .ok()
        .and_then(|cfg| cfg.feeds.into_iter().find(|f| f.id == id))
        .map(|f| f.url);

    match update_one_feed(&id).await {
        Ok(result) => {
            // Rebuild zone set immediately so the refreshed feed is active without a reload.
            let new_zones = crate::build_zone_set(&s.cfg);
            s.zones.store(std::sync::Arc::new(new_zones));
            if result.error.is_none() {
                if let (Some(j), Some(url)) = (s.sync_journal.as_ref(), feed_url) {
                    j.push(SyncOp::UpdateFeed { id: id.clone(), url });
                }
            }
            let code = if result.error.is_some() { StatusCode::INTERNAL_SERVER_ERROR } else { StatusCode::OK };
            (code, JsonExtract(serde_json::json!({"result": result})))
        }
        Err(crate::error::AppError::BadRequest(msg)) => (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({"error":"BAD_REQUEST","details":msg}))),
        Err(e) => (StatusCode::NOT_FOUND, JsonExtract(serde_json::json!({"error":e.to_string()}))),
    }
}

async fn feed_presets_handler() -> impl IntoResponse {
    let presets = builtin_presets();
    JsonExtract(serde_json::json!({"presets": presets, "total": presets.len()}))
}

// ── GET /upstreams ─────────────────────────────────────────────────────────

async fn upstreams_handler(State(s): State<AppState>) -> impl IntoResponse {
    let statuses = match s.upstreams.read() {
        Ok(g)  => g.clone(),
        Err(e) => {
            error!(err = %e, "upstreams RwLock poisoned");
            return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
                "error": "INTERNAL", "details": "upstream state unavailable"
            }))).into_response();
        }
    };
    let total   = statuses.len();
    let healthy = statuses.iter().filter(|u| u.healthy).count();
    (StatusCode::OK, JsonExtract(serde_json::json!({
        "upstreams": statuses,
        "total":     total,
        "healthy":   healthy,
    }))).into_response()
}

// ── GET /logs ──────────────────────────────────────────────────────────────

const LOG_LIMIT_MAX: usize = 1_000;
const LOG_LIMIT_DEFAULT: usize = 100;

#[derive(Deserialize)]
struct LogsParams {
    #[serde(default = "default_log_limit")]
    limit:  usize,
    #[serde(default)]
    page:   usize,
    action: Option<String>,
    client: Option<String>,
    since:  Option<u64>,
}

fn default_log_limit() -> usize { LOG_LIMIT_DEFAULT }

async fn logs_handler(
    State(s):      State<AppState>,
    params_result: Result<Query<LogsParams>, QueryRejection>,
) -> Response {
    let Query(params) = match params_result {
        Ok(q) => q,
        Err(e) => return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error":   "INVALID_PARAM",
            "details": e.to_string()
        }))).into_response(),
    };

    if params.limit > LOG_LIMIT_MAX {
        return (StatusCode::UNPROCESSABLE_ENTITY, JsonExtract(serde_json::json!({
            "error":   "INVALID_PARAM",
            "details": format!("limit must be ≤ {}", LOG_LIMIT_MAX),
        }))).into_response();
    }

    let action = match params.action.as_deref() {
        Some(s) => match LogAction::from_str(s) {
            Some(a) => Some(a),
            None => return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
                "error":   "INVALID_PARAM",
                "details": format!("action '{}' is not valid — expected one of: forwarded, cached, local, blocked, nxdomain, refused, servfail", s),
            }))).into_response(),
        },
        None => None,
    };

    let client = match params.client.as_deref() {
        Some(s) => match s.parse::<std::net::IpAddr>() {
            Ok(ip) => Some(ip),
            Err(_) => return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
                "error":   "INVALID_PARAM",
                "details": format!("client '{}' is not a valid IP address", s),
            }))).into_response(),
        },
        None => None,
    };

    let q = LogQuery {
        limit:      params.limit,
        page:       params.page,
        action,
        client,
        since_secs: params.since,
    };

    let (entries, total) = match s.log_buffer.lock() {
        Ok(buf) => buf.query(&q),
        Err(e) => {
            error!(err = %e, "log_buffer Mutex poisoned");
            return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
                "error": "INTERNAL", "details": "log buffer unavailable"
            }))).into_response();
        }
    };
    JsonExtract(serde_json::json!({
        "entries": entries,
        "total":   total,
        "page":    params.page,
        "limit":   params.limit,
    })).into_response()
}

// ── DELETE /logs ───────────────────────────────────────────────────────────

async fn clear_logs_handler(
    State(s): State<AppState>,
) -> impl IntoResponse {
    let deleted = match s.log_buffer.lock() {
        Ok(mut buf) => buf.clear(),
        Err(e) => {
            error!(err = %e, "log_buffer Mutex poisoned");
            return (StatusCode::INTERNAL_SERVER_ERROR, JsonExtract(serde_json::json!({
                "error": "INTERNAL", "details": "log buffer unavailable"
            }))).into_response();
        }
    };
    s.audit.send(AuditEvent::LogsClear { count: deleted });
    info!(entries_deleted = deleted, "log buffer cleared via DELETE /logs");
    JsonExtract(serde_json::json!({
        "message":         "log buffer cleared",
        "entries_deleted": deleted,
    })).into_response()
}

// ── TLS status ─────────────────────────────────────────────────────────────

async fn tls_status_handler(State(s): State<AppState>) -> impl IntoResponse {
    let tls = s.tls_cfg.as_ref();
    JsonExtract(serde_json::json!({
        "dot": {
            "enabled": tls.cert_path.is_some() && tls.key_path.is_some(),
            "port": tls.dot_port.unwrap_or(853),
            "rfc": "RFC 7858"
        },
        "doh": {
            "enabled": tls.cert_path.is_some() && tls.key_path.is_some(),
            "port": tls.doh_port.unwrap_or(443),
            "rfc": "RFC 8484"
        },
        "doq": {
            "enabled": tls.cert_path.is_some() && tls.key_path.is_some(),
            "port": tls.doq_port.unwrap_or(853),
            "rfc": "RFC 9250"
        },
        "cert": tls.cert_path.as_deref().unwrap_or("not configured"),
        "hostname": tls.hostname.as_deref().unwrap_or("runbound.local")
    }))
}

// ── GET /audit/tail ────────────────────────────────────────────────────────

#[derive(Deserialize)]
struct AuditTailQuery { n: Option<usize> }

async fn audit_tail_handler(
    State(s): State<AppState>,
    Query(q): Query<AuditTailQuery>,
) -> impl IntoResponse {
    let n = q.n.unwrap_or(100).min(1000);
    let log_path = s.base_dir.join("audit.log");
    match crate::audit::tail_audit_log(&log_path, n) {
        Ok(lines) => (StatusCode::OK, JsonExtract(serde_json::json!({
            "lines": lines,
            "count": lines.len(),
        }))),
        Err(e) => (StatusCode::NOT_FOUND, JsonExtract(serde_json::json!({
            "error": "AUDIT_LOG_UNAVAILABLE",
            "details": e,
        }))),
    }
}

// ── GET /metrics ───────────────────────────────────────────────────────────

async fn metrics_handler(State(s): State<AppState>) -> impl IntoResponse {
    let snap = s.stats.snapshot();
    let body = format!(
        "# HELP runbound_queries_total Total DNS queries received
\
         # TYPE runbound_queries_total counter
\
         runbound_queries_total {total}
\
         # HELP runbound_blocked_total Queries answered with REFUSED (blacklist/feeds)
\
         # TYPE runbound_blocked_total counter
\
         runbound_blocked_total {blocked}
\
         # HELP runbound_nxdomain_total Queries answered with NXDOMAIN
\
         # TYPE runbound_nxdomain_total counter
\
         runbound_nxdomain_total {nxdomain}
\
         # HELP runbound_refused_total Queries answered with REFUSED (ACL/rate limit)
\
         # TYPE runbound_refused_total counter
\
         runbound_refused_total {refused}
\
         # HELP runbound_servfail_total Queries answered with SERVFAIL
\
         # TYPE runbound_servfail_total counter
\
         runbound_servfail_total {servfail}
\
         # HELP runbound_forwarded_total Queries forwarded to upstream resolvers
\
         # TYPE runbound_forwarded_total counter
\
         runbound_forwarded_total {forwarded}
\
         # HELP runbound_local_hits_total Queries answered from local zone data
\
         # TYPE runbound_local_hits_total counter
\
         runbound_local_hits_total {local_hits}
\
         # HELP runbound_uptime_seconds Process uptime in seconds
\
         # TYPE runbound_uptime_seconds gauge
\
         runbound_uptime_seconds {uptime}
\
         # HELP runbound_qps Queries per second
\
         # TYPE runbound_qps gauge
\
         runbound_qps{{window=\"1m\"}} {qps_1m}
\
         runbound_qps{{window=\"5m\"}} {qps_5m}
\
         runbound_qps{{window=\"peak\"}} {qps_peak}
\
         # HELP runbound_latency_ms DNS query latency percentiles in milliseconds
\
         # TYPE runbound_latency_ms gauge
\
         runbound_latency_ms{{quantile=\"0.5\"}} {p50}
\
         runbound_latency_ms{{quantile=\"0.95\"}} {p95}
\
         runbound_latency_ms{{quantile=\"0.99\"}} {p99}
\
         # HELP runbound_cache_hit_rate Cache hit rate percentage (0–100)
\
         # TYPE runbound_cache_hit_rate gauge
\
         runbound_cache_hit_rate {cache_hit_rate}
\
         # HELP runbound_cache_entries Approximate cached DNS entries
\
         # TYPE runbound_cache_entries gauge
\
         runbound_cache_entries {cache_entries}
\
         # HELP runbound_dnssec_total DNSSEC validation results
\
         # TYPE runbound_dnssec_total counter
\
         runbound_dnssec_total{{status=\"secure\"}} {dnssec_secure}
\
         runbound_dnssec_total{{status=\"bogus\"}} {dnssec_bogus}
\
         runbound_dnssec_total{{status=\"insecure\"}} {dnssec_insecure}
",
        total        = snap.total,
        blocked      = snap.blocked,
        nxdomain     = snap.nxdomain,
        refused      = snap.refused,
        servfail     = snap.servfail,
        forwarded    = snap.forwarded,
        local_hits   = snap.local_hits,
        uptime       = snap.uptime_secs,
        qps_1m       = snap.qps_1m,
        qps_5m       = snap.qps_5m,
        qps_peak     = snap.qps_peak,
        p50          = snap.latency_p50_ms,
        p95          = snap.latency_p95_ms,
        p99          = snap.latency_p99_ms,
        cache_hit_rate  = snap.cache_hit_rate,
        cache_entries   = snap.cache_entries,
        dnssec_secure   = snap.dnssec_secure,
        dnssec_bogus    = snap.dnssec_bogus,
        dnssec_insecure = snap.dnssec_insecure,
    );
    (
        StatusCode::OK,
        [(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8")],
        body,
    )
}

// ── POST /rotate-key ───────────────────────────────────────────────────────

// ── POST /rotate-key ───────────────────────────────────────────────────────

#[derive(Deserialize)]
struct RotateKeyRequest {
    new_key: String,
}

async fn rotate_key_handler(
    State(s): State<AppState>,
    ApiJson(req): ApiJson<RotateKeyRequest>,
) -> impl IntoResponse {
    // Require at least 32 bytes of entropy (64 hex chars) — shorter keys are
    // statistically weak and likely copy-paste mistakes.
    if req.new_key.len() < 32 {
        return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error": "WEAK_KEY",
            "details": "new_key must be at least 32 characters",
        }))).into_response();
    }
    // Reject control characters (CRLF injection, log injection).
    if req.new_key.bytes().any(|b| b < 0x20 || b == 0x7f) {
        return (StatusCode::BAD_REQUEST, JsonExtract(serde_json::json!({
            "error": "INVALID_KEY",
            "details": "new_key must not contain control characters",
        }))).into_response();
    }
    rotate_api_key(req.new_key.clone());
    // Persist to base_dir/api.key so the key survives a restart.
    let key_path = s.base_dir.join("api.key");
    let persist_result = std::fs::write(&key_path, req.new_key.as_bytes()).and_then(|_| {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600))?;
        }
        Ok(())
    });
    if let Err(e) = persist_result {
        // Non-fatal: key is already active in memory; log the write failure.
        warn!(path = %key_path.display(), err = %e, "Failed to persist rotated API key to disk");
    }
    s.audit.send(AuditEvent::ConfigReload);
    info!("API key rotated via POST /rotate-key");
    (StatusCode::OK, JsonExtract(serde_json::json!({
        "status": "ok",
        "message": "API key rotated — old token is immediately invalid",
    }))).into_response()
}

// ── Helpers ────────────────────────────────────────────────────────────────

fn ensure_dot(name: &str) -> String {
    if name.ends_with('.') { name.to_string() } else { format!("{}.", name) }
}

/// Reject any string that contains ASCII control characters (0x00–0x1f, 0x7f).
/// Applied to all user-supplied text fields (value, description) to prevent
/// CRLF injection into logs, stored JSON, or HTTP response bodies.
fn validate_no_control_chars(s: &str, field: &'static str) -> Result<(), String> {
    if s.bytes().any(|b| b < 0x20 || b == 0x7f) {
        return Err(format!("Field '{}' must not contain control characters (\r, \n, etc.)", field));
    }
    Ok(())
}

/// VUL-05: Validate a DNS name before accepting it from the API.
/// Rejects: empty names, root zone ("."), labels > 63 chars, name > 253 chars,
/// non-ASCII / Unicode (including homoglyph attacks), invalid label characters.
/// Underscores are allowed for service labels (_dmarc, _tcp, etc. — RFC 2782/6763).
fn validate_dns_name(name: &str) -> Result<(), &'static str> {
    let n = name.trim_end_matches('.');
    if n.is_empty() {
        return Err("Domain name cannot be empty or the root zone");
    }
    if n.len() > 253 {
        return Err("Domain name exceeds 253 characters");
    }
    for label in n.split('.') {
        if label.is_empty() {
            return Err("Domain label cannot be empty (no consecutive or leading dots)");
        }
        if label.len() > 63 {
            return Err("Domain label exceeds 63 characters");
        }
        if label.starts_with('-') || label.ends_with('-') {
            return Err("Domain label cannot start or end with a hyphen");
        }
        if !label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
            return Err("Domain label contains invalid characters \
                        (ASCII alphanumeric, hyphens, underscores only)");
        }
    }
    Ok(())
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt; // oneshot

    const TEST_KEY: &str = "test-api-key-for-unit-tests";

    fn make_test_app() -> Router {
        // Initialise API key (OnceLock — safe to call multiple times with same value)
        init_api_key(Some(TEST_KEY.to_string()));
        // Initialise BASE_DIR for store/feeds path resolution (OnceLock — idempotent).
        let _ = crate::runtime::BASE_DIR.set(std::path::PathBuf::from("/tmp/runbound-test"));

        let zones = Arc::new(ArcSwap::new(Arc::new(
            crate::dns::local::LocalZoneSet::default()
        )));
        let cfg_arc = Arc::new(crate::config::parser::UnboundConfig::default());
        let log_buffer = crate::logbuffer::new_shared(1000, true);
        let upstreams = crate::upstreams::init_upstreams(&cfg_arc);

        let state = AppState {
            zones:       Arc::clone(&zones),
            zones_mutex: Arc::new(tokio::sync::Mutex::new(())),
            tls_cfg:     Arc::new(crate::config::parser::TlsConfig::default()),
            rate_limiter: ApiRateLimiter::new_public(),
            stats:       crate::stats::Stats::new(),
            cfg:         Arc::clone(&cfg_arc),
            cfg_path:    "/dev/null".to_string(),
            log_buffer,
            upstreams,
            sync_journal: None,
            slave_mode:   false,
            base_dir:     Arc::new(std::path::PathBuf::from("/tmp/runbound-test")),
            audit:        crate::audit::init(false, None, None, std::path::PathBuf::from("/tmp")),
        };
        router(state)
    }

    async fn body_json(body: axum::body::Body) -> serde_json::Value {
        let bytes = body.collect().await.unwrap().to_bytes();
        serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
    }

    fn auth_header() -> (&'static str, String) {
        ("Authorization", format!("Bearer {}", TEST_KEY))
    }

    // ── /stats ────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn stats_requires_auth() {
        let app = make_test_app();
        let resp = app.oneshot(
            Request::builder().uri("/stats").body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn stats_schema() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/stats").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let json = body_json(resp.into_body()).await;
        for field in &["total", "blocked", "forwarded", "qps_1m", "qps_5m",
                       "latency_p50_ms", "cache_hit_rate", "local_hits"] {
            assert!(json.get(field).is_some(), "missing field: {field}");
        }
    }

    // ── /stats/stream ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn stats_stream_requires_auth() {
        let app = make_test_app();
        let resp = app.oneshot(
            Request::builder().uri("/stats/stream").body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn stats_stream_content_type() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/stats/stream").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let ct = resp.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("");
        assert!(ct.contains("text/event-stream"), "unexpected Content-Type: {ct}");
    }

    // ── /upstreams ────────────────────────────────────────────────────────

    #[tokio::test]
    async fn upstreams_requires_auth() {
        let app = make_test_app();
        let resp = app.oneshot(
            Request::builder().uri("/upstreams").body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn upstreams_schema() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/upstreams").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let json = body_json(resp.into_body()).await;
        assert!(json.get("upstreams").is_some());
        assert!(json.get("total").is_some());
        assert!(json.get("healthy").is_some());
    }

    // ── /logs ─────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn logs_requires_auth() {
        let app = make_test_app();
        let resp = app.oneshot(
            Request::builder().uri("/logs").body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn logs_schema() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/logs").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let json = body_json(resp.into_body()).await;
        assert!(json.get("entries").is_some());
        assert!(json.get("total").is_some());
    }

    #[tokio::test]
    async fn logs_limit_too_large() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/logs?limit=2000").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[tokio::test]
    async fn logs_invalid_action() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/logs?action=invalid").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn logs_invalid_client_ip() {
        let app = make_test_app();
        let (k, v) = auth_header();
        let resp = app.oneshot(
            Request::builder().uri("/logs?client=notanip").header(k, v).body(Body::empty()).unwrap()
        ).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    // ── validate_dns_name unit tests (SEC-02) ─────────────────────────────

    #[test]
    fn test_validate_dns_name_253_chars_accepted() {
        // 63+1+63+1+63+1+61 = 253 chars — exactly at RFC 1035 §2.3.4 limit
        let name = format!("{}.{}.{}.{}",
            "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(61));
        assert_eq!(name.len(), 253);
        assert!(validate_dns_name(&name).is_ok());
    }

    #[test]
    fn test_validate_dns_name_254_chars_rejected() {
        // 63+1+63+1+63+1+62 = 254 chars — one over the RFC limit
        let name = format!("{}.{}.{}.{}",
            "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(62));
        assert_eq!(name.len(), 254);
        assert!(validate_dns_name(&name).is_err());
    }

    #[test]
    fn test_validate_dns_name_253_with_trailing_dot_accepted() {
        // trailing dot is stripped before length check
        let name = format!("{}.{}.{}.{}.",
            "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(61));
        assert_eq!(name.trim_end_matches('.').len(), 253);
        assert!(validate_dns_name(&name).is_ok());
    }

    #[test]
    fn test_validate_dns_name_254_with_trailing_dot_rejected() {
        let name = format!("{}.{}.{}.{}.",
            "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(62));
        assert_eq!(name.trim_end_matches('.').len(), 254);
        assert!(validate_dns_name(&name).is_err());
    }

    #[test]
    fn test_validate_dns_name_label_64_chars_rejected() {
        let name = "a".repeat(64);
        assert!(validate_dns_name(&name).is_err());
    }

    #[test]
    fn test_validate_dns_name_label_63_chars_accepted() {
        let name = "a".repeat(63);
        assert!(validate_dns_name(&name).is_ok());
    }
}