fail2ban-rs 1.2.1

A pure-Rust fail2ban replacement. Single static binary, fast two-phase matching, nftables/iptables firewall backends.
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
//! Tracking — failure counting, ban/unban decisions, and state persistence.
//!
//! Owns all mutable state: failure counts (ring buffers), active bans,
//! and runtime statistics. Receives Failure events from watchers and
//! TrackerCmd queries from the server. Sends FirewallCmd to enforce.

/// Escalating ban time calculator.
pub mod ban_calc;
/// Fixed-capacity ring buffer for failure timestamps.
pub mod circular;
/// MaxMind GeoIP enrichment.
#[cfg(feature = "maxmind")]
pub mod maxmind;
/// WAL-backed ban state persistence.
pub mod persist;
/// Serializable ban record.
pub mod state;

use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap};
use std::net::IpAddr;
use std::sync::Arc;

use etchdb::{Store, WalBackend};
use serde::Serialize;
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};

use crate::config::JailConfig;
use crate::detect::watcher::Failure;
use crate::enforce::FirewallCmd;
use crate::logging::Logger;
use crate::track::ban_calc::{JailParams, build_jail_params, calc_ban_time};
use crate::track::circular::CircularTimestamps;
#[cfg(feature = "maxmind")]
use crate::track::maxmind::MaxmindState;
use crate::track::persist::BanState;
use crate::track::state::BanRecord;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Commands from the server to the tracker (query/mutate state).
pub enum TrackerCmd {
    /// Return all active bans.
    QueryBans {
        respond: oneshot::Sender<Vec<BanRecord>>,
    },
    /// Manually ban an IP.
    ManualBan {
        ip: IpAddr,
        jail_id: String,
        ban_time: i64,
        respond: oneshot::Sender<crate::error::Result<()>>,
    },
    /// Manually unban an IP.
    ManualUnban {
        ip: IpAddr,
        jail_id: String,
        respond: oneshot::Sender<crate::error::Result<()>>,
    },
    /// Return runtime statistics.
    GetStats { respond: oneshot::Sender<Stats> },
    /// Hot-reload global and jail configurations.
    UpdateConfig {
        global: crate::config::GlobalConfig,
        jails: HashMap<String, JailConfig>,
    },
}

/// Runtime statistics snapshot.
#[derive(Debug, Clone, Serialize)]
pub struct Stats {
    pub uptime_secs: i64,
    pub active_bans: usize,
    pub total_bans: u64,
    pub total_unbans: u64,
    pub total_failures: u64,
    pub jails: HashMap<String, JailStats>,
}

/// Per-jail statistics.
#[derive(Debug, Clone, Default, Serialize)]
pub struct JailStats {
    pub active_bans: usize,
    pub total_bans: u64,
    pub total_failures: u64,
}

// ---------------------------------------------------------------------------
// Internal types
// ---------------------------------------------------------------------------

#[derive(Debug, Eq, PartialEq)]
struct UnbanTimer {
    expires_at: i64,
    ip: IpAddr,
    jail_id: String,
}

impl Ord for UnbanTimer {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.expires_at.cmp(&other.expires_at)
    }
}

impl PartialOrd for UnbanTimer {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

type FailKey = (IpAddr, String);

struct FailState {
    timestamps: CircularTimestamps,
}

/// All mutable tracker state, grouped to reduce function argument counts.
struct TrackerState {
    jail_params: HashMap<String, JailParams>,
    failures: HashMap<FailKey, FailState>,
    store: Arc<Store<BanState, WalBackend<BanState>>>,
    unban_queue: BinaryHeap<Reverse<UnbanTimer>>,
    total_bans: u64,
    total_unbans: u64,
    total_failures: u64,
    jail_bans: HashMap<String, u64>,
    jail_failures: HashMap<String, u64>,
    started_at: i64,
    executor_tx: mpsc::Sender<FirewallCmd>,
    logger: Option<Logger>,
    #[cfg(feature = "maxmind")]
    maxmind: MaxmindState,
}

impl TrackerState {
    fn notify_ban(&self, ip: IpAddr, jail_id: &str, ban_time: i64, manual: bool) {
        if let Some(ref t) = self.logger {
            t.log_ban(ip, jail_id, ban_time, manual);
        }
        if let Some(params) = self.jail_params.get(jail_id)
            && let Some(ref url) = params.webhook
        {
            crate::webhook::notify_ban(url, ip, jail_id, ban_time);
        }
    }

    fn notify_unban(&self, ip: IpAddr, jail_id: &str, manual: bool) {
        if let Some(ref t) = self.logger {
            t.log_unban(ip, jail_id, manual);
        }
        if let Some(params) = self.jail_params.get(jail_id)
            && let Some(ref url) = params.webhook
        {
            crate::webhook::notify_unban(url, ip, jail_id);
        }
    }
}

// ---------------------------------------------------------------------------
// Main run loop
// ---------------------------------------------------------------------------

/// Run the tracker task.
#[allow(clippy::too_many_arguments, clippy::implicit_hasher)]
pub async fn run(
    global_config: crate::config::GlobalConfig,
    jail_configs: HashMap<String, JailConfig>,
    mut failure_rx: mpsc::Receiver<Failure>,
    mut cmd_rx: mpsc::Receiver<TrackerCmd>,
    executor_tx: mpsc::Sender<FirewallCmd>,
    restored_bans: Vec<BanRecord>,
    restored_ban_counts: HashMap<IpAddr, u32>,
    store: Arc<Store<BanState, WalBackend<BanState>>>,
    logger: Option<Logger>,
    cancel: CancellationToken,
) {
    info!("tracker started");

    #[cfg(not(feature = "maxmind"))]
    if global_config.maxmind_asn.is_some()
        || global_config.maxmind_country.is_some()
        || global_config.maxmind_city.is_some()
    {
        warn!("maxmind paths configured but maxmind feature not compiled — ignoring");
    }

    let mut state = TrackerState {
        jail_params: build_jail_params(&jail_configs),
        failures: HashMap::new(),
        store,
        unban_queue: BinaryHeap::new(),
        total_bans: 0,
        total_unbans: 0,
        total_failures: 0,
        jail_bans: HashMap::new(),
        jail_failures: HashMap::new(),
        started_at: chrono::Utc::now().timestamp(),
        executor_tx,
        logger,
        #[cfg(feature = "maxmind")]
        maxmind: MaxmindState::load(&global_config, &jail_configs),
    };

    // Restore unban timers from persisted state.
    for ban in &restored_bans {
        if let Some(expires) = ban.expires_at {
            state.unban_queue.push(Reverse(UnbanTimer {
                expires_at: expires,
                ip: ban.ip,
                jail_id: ban.jail_id.clone(),
            }));
        }
    }

    // Seed the store with restored bans (from firewall restore filtering).
    // On first boot with etch, the store already has these from WAL replay.
    // On migration from old format, server.rs passes the filtered active_bans.
    {
        let store_state = state.store.read();
        if store_state.bans.is_empty() && !restored_bans.is_empty() {
            drop(store_state);
            let _ = state.store.write(|tx| {
                for ban in &restored_bans {
                    tx.bans.put((ban.ip, ban.jail_id.clone()), ban.clone());
                }
                for (ip, count) in &restored_ban_counts {
                    tx.ban_counts.put(*ip, *count);
                }
                Ok(())
            });
        }
    }

    loop {
        let next_unban_sleep = next_unban_duration(&state.unban_queue);

        tokio::select! {
            () = cancel.cancelled() => {
                info!("tracker shutting down");
                if let Err(e) = state.store.flush() {
                    warn!("final flush failed: {e}");
                }
                break;
            }

            failure = failure_rx.recv() => {
                if let Some(f) = failure {
                    handle_failure(f, &mut state).await;
                } else {
                    info!("failure channel closed");
                    break;
                }
            }

            cmd = cmd_rx.recv() => {
                if let Some(c) = cmd {
                    handle_cmd(c, &mut state).await;
                } else {
                    debug!("tracker cmd channel closed");
                }
            }

            () = tokio::time::sleep(next_unban_sleep) => {
                process_unbans(&mut state).await;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Command handling
// ---------------------------------------------------------------------------

async fn handle_cmd(cmd: TrackerCmd, s: &mut TrackerState) {
    match cmd {
        TrackerCmd::QueryBans { respond } => {
            let list: Vec<BanRecord> = s.store.read().bans.values().cloned().collect();
            let _ = respond.send(list);
        }

        TrackerCmd::ManualBan {
            ip,
            jail_id,
            ban_time,
            respond,
        } => {
            let result = do_manual_ban(ip, &jail_id, ban_time, s).await;
            let _ = respond.send(result);
        }

        TrackerCmd::ManualUnban {
            ip,
            jail_id,
            respond,
        } => {
            let result = do_manual_unban(ip, &jail_id, s).await;
            let _ = respond.send(result);
        }

        TrackerCmd::GetStats { respond } => {
            let now = chrono::Utc::now().timestamp();
            let store_state = s.store.read();
            let mut jail_stats: HashMap<String, JailStats> = HashMap::new();
            for jail_id in s.jail_params.keys() {
                let active = store_state
                    .bans
                    .values()
                    .filter(|b| b.jail_id == *jail_id)
                    .count();
                jail_stats.insert(
                    jail_id.clone(),
                    JailStats {
                        active_bans: active,
                        total_bans: *s.jail_bans.get(jail_id).unwrap_or(&0),
                        total_failures: *s.jail_failures.get(jail_id).unwrap_or(&0),
                    },
                );
            }
            let stats = Stats {
                uptime_secs: (now - s.started_at).max(0),
                active_bans: store_state.bans.len(),
                total_bans: s.total_bans,
                total_unbans: s.total_unbans,
                total_failures: s.total_failures,
                jails: jail_stats,
            };
            drop(store_state);
            let _ = respond.send(stats);
        }

        TrackerCmd::UpdateConfig { global, jails } => {
            info!(
                jails = jails.len(),
                "updating jail and global configurations"
            );
            let new_params = build_jail_params(&jails);
            s.failures
                .retain(|(_, jail_id), _| new_params.contains_key(jail_id));
            s.jail_params = new_params;
            #[cfg(feature = "maxmind")]
            s.maxmind.reload(&global, &jails);
            let _ = &global; // suppress unused warning when maxmind disabled
        }
    }
}

// ---------------------------------------------------------------------------
// Manual ban/unban
// ---------------------------------------------------------------------------

/// Shared ban execution: create record, enqueue unban, send firewall command, notify.
async fn execute_ban(ip: IpAddr, jail_id: &str, ban_time: i64, manual: bool, s: &mut TrackerState) {
    let now = chrono::Utc::now().timestamp();
    let expires_at = if ban_time < 0 {
        None
    } else {
        Some(now.saturating_add(ban_time))
    };

    let ban = BanRecord {
        ip,
        jail_id: jail_id.to_string(),
        banned_at: now,
        expires_at,
    };

    if let Some(exp) = expires_at {
        s.unban_queue.push(Reverse(UnbanTimer {
            expires_at: exp,
            ip,
            jail_id: jail_id.to_string(),
        }));
    }

    let ban_clone = ban.clone();
    let jail_owned = jail_id.to_string();
    if let Err(e) = s.store.write(|tx| {
        tx.bans.put((ip, jail_owned.clone()), ban_clone.clone());
        Ok(())
    }) {
        warn!("etch write failed: {e}");
    }
    s.total_bans += 1;
    *s.jail_bans.entry(jail_id.to_string()).or_insert(0) += 1;

    let cmd = FirewallCmd::Ban {
        ip,
        jail_id: jail_id.to_string(),
        banned_at: now,
        expires_at,
    };
    if s.executor_tx.send(cmd).await.is_err() {
        warn!("executor channel closed");
    }

    s.notify_ban(ip, jail_id, ban_time, manual);
}

async fn do_manual_ban(
    ip: IpAddr,
    jail_id: &str,
    ban_time: i64,
    s: &mut TrackerState,
) -> crate::error::Result<()> {
    if !s.jail_params.contains_key(jail_id) {
        return Err(crate::error::Error::config(format!(
            "unknown jail: {jail_id}"
        )));
    }
    if s.store.read().bans.contains_key(&(ip, jail_id.to_string())) {
        return Err(crate::error::Error::AlreadyBanned {
            ip,
            jail: jail_id.to_string(),
        });
    }
    info!(%ip, jail = %jail_id, ban_time, "manual ban");
    execute_ban(ip, jail_id, ban_time, true, s).await;
    Ok(())
}

async fn do_manual_unban(
    ip: IpAddr,
    jail_id: &str,
    s: &mut TrackerState,
) -> crate::error::Result<()> {
    if !s.jail_params.contains_key(jail_id) {
        return Err(crate::error::Error::config(format!(
            "unknown jail: {jail_id}"
        )));
    }
    let key = (ip, jail_id.to_string());
    if !s.store.read().bans.contains_key(&key) {
        return Err(crate::error::Error::NotBanned {
            ip,
            jail: jail_id.to_string(),
        });
    }
    if let Err(e) = s.store.write(|tx| {
        tx.bans.delete(&key);
        Ok(())
    }) {
        warn!("etch write failed: {e}");
    }
    info!(%ip, jail = %jail_id, "manual unban");
    execute_unban(ip, jail_id, true, s).await;
    Ok(())
}

/// Shared unban execution: update counters, send firewall command, notify.
async fn execute_unban(ip: IpAddr, jail_id: &str, manual: bool, s: &mut TrackerState) {
    s.total_unbans += 1;
    let cmd = FirewallCmd::Unban {
        ip,
        jail_id: jail_id.to_string(),
    };
    if s.executor_tx.send(cmd).await.is_err() {
        warn!("executor channel closed");
    }
    s.notify_unban(ip, jail_id, manual);
}

// ---------------------------------------------------------------------------
// Failure handling
// ---------------------------------------------------------------------------

async fn handle_failure(failure: Failure, s: &mut TrackerState) {
    s.total_failures += 1;
    *s.jail_failures.entry(failure.jail_id.clone()).or_insert(0) += 1;

    let ban_key = (failure.ip, failure.jail_id.clone());
    if s.store.read().bans.contains_key(&ban_key) {
        debug!(ip = %failure.ip, jail = %failure.jail_id, "already banned, ignoring failure");
        return;
    }

    let Some(params) = s.jail_params.get(&failure.jail_id) else {
        warn!(jail = %failure.jail_id, "unknown jail in failure event");
        return;
    };

    let max_retry = params.max_retry;
    let find_time = params.find_time;
    let ban_time = params.ban_time;

    let key = (failure.ip, failure.jail_id.clone());
    let fail_state = s.failures.entry(key).or_insert_with(|| FailState {
        timestamps: CircularTimestamps::new(max_retry as usize),
    });

    fail_state.timestamps.push(failure.timestamp);

    if fail_state.timestamps.threshold_reached(find_time) {
        let count = s
            .store
            .read()
            .ban_counts
            .get(&failure.ip)
            .copied()
            .unwrap_or(0);
        let effective_ban_time = calc_ban_time(ban_time, count, params);
        let ip = failure.ip;
        if let Err(e) = s.store.write(|tx| {
            tx.ban_counts.put(ip, count + 1);
            Ok(())
        }) {
            warn!("etch write failed: {e}");
        }

        #[cfg(feature = "maxmind")]
        {
            let enrichment = s.maxmind.enrich(failure.ip, &failure.jail_id);
            crate::track::maxmind::log_ban_event(
                &failure,
                effective_ban_time,
                count + 1,
                &enrichment,
            );
        }
        #[cfg(not(feature = "maxmind"))]
        info!(
            ip = %failure.ip,
            jail = %failure.jail_id,
            ban_time = effective_ban_time,
            ban_count = count + 1,
            "threshold reached, banning"
        );

        execute_ban(failure.ip, &failure.jail_id, effective_ban_time, false, s).await;
    }
}

// ---------------------------------------------------------------------------
// Unban processing
// ---------------------------------------------------------------------------

async fn process_unbans(s: &mut TrackerState) {
    let now = chrono::Utc::now().timestamp();
    while let Some(Reverse(timer)) = s.unban_queue.peek() {
        if timer.expires_at > now {
            break;
        }
        let Some(Reverse(timer)) = s.unban_queue.pop() else {
            break;
        };
        let ban_key = (timer.ip, timer.jail_id.clone());
        if s.store.read().bans.contains_key(&ban_key) {
            if let Err(e) = s.store.write(|tx| {
                tx.bans.delete(&ban_key);
                Ok(())
            }) {
                warn!("etch write failed: {e}");
            }
            info!(ip = %timer.ip, jail = %timer.jail_id, "unban timer expired");
            execute_unban(timer.ip, &timer.jail_id, false, s).await;
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn next_unban_duration(queue: &BinaryHeap<Reverse<UnbanTimer>>) -> tokio::time::Duration {
    match queue.peek() {
        Some(Reverse(timer)) => {
            let now = chrono::Utc::now().timestamp();
            let secs = (timer.expires_at - now).max(0) as u64;
            tokio::time::Duration::from_secs(secs.min(60))
        }
        None => tokio::time::Duration::from_secs(60),
    }
}

#[cfg(test)]
#[allow(
    clippy::panic,
    clippy::indexing_slicing,
    clippy::unwrap_used,
    clippy::needless_pass_by_value
)]
mod tests {
    use std::collections::HashMap;
    use std::net::{IpAddr, Ipv4Addr};
    use std::sync::Arc;

    use etchdb::Store;
    use tokio::sync::mpsc;
    use tokio_util::sync::CancellationToken;

    use crate::config::JailConfig;
    use crate::detect::watcher::Failure;
    use crate::enforce::FirewallCmd;
    use crate::track::TrackerCmd;
    use crate::track::persist::BanState;

    fn test_jail_config() -> JailConfig {
        JailConfig {
            enabled: true,
            log_path: "/tmp/test.log".into(),
            date_format: crate::detect::date::DateFormat::Syslog,
            filter: vec!["from <HOST>".to_string()],
            max_retry: 3,
            find_time: 600,
            ban_time: 60,
            ignoreself: false,
            maxmind: vec![
                crate::config::MaxmindField::Asn,
                crate::config::MaxmindField::Country,
                crate::config::MaxmindField::City,
            ],
            ..JailConfig::default()
        }
    }

    fn test_store() -> Arc<Store<BanState, etchdb::WalBackend<BanState>>> {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().to_path_buf();
        std::mem::forget(dir); // keep the tempdir alive
        let store = Store::<BanState, etchdb::WalBackend<BanState>>::open_wal(path).unwrap();
        Arc::new(store)
    }

    fn test_global_config() -> crate::config::GlobalConfig {
        crate::config::GlobalConfig {
            state_dir: std::path::PathBuf::from("/tmp/state"),
            socket_path: std::path::PathBuf::from("/tmp/sock"),
            log_level: "info".to_string(),
            channel_size: 1024,
            maxmind_asn: Some(
                std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/GeoLite2-ASN-Test.mmdb"),
            ),
            maxmind_country: Some(
                std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/GeoLite2-Country-Test.mmdb"),
            ),
            maxmind_city: Some(
                std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures/GeoLite2-City-Test.mmdb"),
            ),
        }
    }

    #[tokio::test]
    async fn bans_after_threshold() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4));
        let now = chrono::Utc::now().timestamp();

        // Send 3 failures (= max_retry).
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        // Should receive a Ban command.
        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout")
            .expect("channel closed");

        match cmd {
            FirewallCmd::Ban {
                ip: ban_ip,
                jail_id,
                ..
            } => {
                assert_eq!(ban_ip, ip);
                assert_eq!(jail_id, "sshd");
            }
            other => panic!("expected Ban, got: {other:?}"),
        }

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn reban_on_restart_false_still_bans_new_offenders() {
        let mut jail = test_jail_config();
        jail.reban_on_restart = false;

        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), jail);

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(9, 9, 9, 9));
        let now = chrono::Utc::now().timestamp();

        // Send 3 failures (= max_retry) — should still ban despite reban_on_restart=false.
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout — ban should still fire with reban_on_restart=false")
            .expect("channel closed");

        match cmd {
            FirewallCmd::Ban {
                ip: ban_ip,
                jail_id,
                ..
            } => {
                assert_eq!(ban_ip, ip);
                assert_eq!(jail_id, "sshd");
            }
            other => panic!("expected Ban, got: {other:?}"),
        }

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn no_ban_below_threshold() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(5, 6, 7, 8));
        let now = chrono::Utc::now().timestamp();

        // Only 2 failures (< max_retry of 3).
        for i in 0..2 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        // Give tracker time to process.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Should not receive a Ban.
        let result =
            tokio::time::timeout(std::time::Duration::from_millis(200), executor_rx.recv()).await;
        assert!(result.is_err(), "should not have received a command");

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn no_ban_outside_find_time() {
        let mut jail = test_jail_config();
        jail.find_time = 10; // 10 second window
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), jail);

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(9, 10, 11, 12));
        let now = chrono::Utc::now().timestamp();

        // 3 failures spread over 100 seconds (> find_time of 10).
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + (i * 50),
                })
                .await
                .unwrap();
        }

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let result =
            tokio::time::timeout(std::time::Duration::from_millis(200), executor_rx.recv()).await;
        assert!(result.is_err(), "should not ban outside find_time");

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn already_banned_ip_ignored() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(64);
        let (executor_tx, mut executor_rx) = mpsc::channel(64);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(20, 20, 20, 20));
        let now = chrono::Utc::now().timestamp();

        // Trigger first ban (3 failures).
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        // Receive the ban command.
        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout")
            .expect("channel closed");
        assert!(matches!(cmd, FirewallCmd::Ban { .. }));

        // Send more failures for the same IP — should be silently ignored.
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + 10 + i,
                })
                .await
                .unwrap();
        }

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // Should NOT receive a second Ban command.
        let result =
            tokio::time::timeout(std::time::Duration::from_millis(200), executor_rx.recv()).await;
        // Either timeout (no message) — but not another Ban.
        match result {
            Err(_) => {} // timeout, good
            Ok(other) => panic!("expected no second Ban, got: {other:?}"),
        }

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn unknown_jail_failure_ignored() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        // Send failure for a jail that doesn't exist.
        failure_tx
            .send(Failure {
                ip: IpAddr::V4(Ipv4Addr::new(30, 30, 30, 30)),
                jail_id: "nonexistent".to_string(),
                timestamp: chrono::Utc::now().timestamp(),
            })
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        let result =
            tokio::time::timeout(std::time::Duration::from_millis(200), executor_rx.recv()).await;
        assert!(result.is_err(), "unknown jail should not produce commands");

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn unban_timer_fires() {
        let mut jail = test_jail_config();
        jail.ban_time = 1; // 1 second ban
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), jail);

        let (failure_tx, failure_rx) = mpsc::channel(64);
        let (executor_tx, mut executor_rx) = mpsc::channel(64);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(40, 40, 40, 40));
        let now = chrono::Utc::now().timestamp();

        // Trigger ban.
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        // Receive Ban.
        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout waiting for ban")
            .expect("channel closed");
        assert!(matches!(cmd, FirewallCmd::Ban { .. }));

        // Wait for unban timer (1 second ban + some buffer).
        let mut got_unban = false;
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3);
        while tokio::time::Instant::now() < deadline {
            match tokio::time::timeout(std::time::Duration::from_millis(500), executor_rx.recv())
                .await
            {
                Ok(Some(FirewallCmd::Unban {
                    ip: unban_ip,
                    jail_id,
                })) => {
                    assert_eq!(unban_ip, ip);
                    assert_eq!(jail_id, "sshd");
                    got_unban = true;
                    break;
                }
                Ok(Some(other)) => panic!("unexpected command: {other:?}"),
                Ok(None) => break,
                Err(_) => {} // timeout, try again
            }
        }
        assert!(
            got_unban,
            "should have received Unban after ban_time expired"
        );

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn restored_bans_populate_unban_queue() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let now = chrono::Utc::now().timestamp();
        let restored = vec![crate::track::state::BanRecord {
            ip: IpAddr::V4(Ipv4Addr::new(50, 50, 50, 50)),
            jail_id: "sshd".to_string(),
            banned_at: now - 10,
            expires_at: Some(now + 1), // expires in 1 second
        }];

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(64);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                restored,
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        // The restored ban should expire after ~1 second.
        let mut got_unban = false;
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(4);
        while tokio::time::Instant::now() < deadline {
            match tokio::time::timeout(std::time::Duration::from_millis(500), executor_rx.recv())
                .await
            {
                Ok(Some(FirewallCmd::Unban { ip, .. })) => {
                    assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(50, 50, 50, 50)));
                    got_unban = true;
                    break;
                }
                Ok(Some(_) | None) => break,
                Err(_) => {}
            }
        }
        assert!(got_unban, "restored ban should trigger unban after expiry");

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn manual_ban_via_cmd() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(60, 60, 60, 60));
        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::ManualBan {
                ip,
                jail_id: "sshd".to_string(),
                ban_time: 3600,
                respond: respond_tx,
            })
            .await
            .unwrap();

        let result = respond_rx.await.unwrap();
        assert!(result.is_ok());

        // Should receive Ban command.
        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout")
            .expect("channel closed");
        assert!(matches!(cmd, FirewallCmd::Ban { .. }));

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn manual_ban_already_banned_error() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let ip = IpAddr::V4(Ipv4Addr::new(70, 70, 70, 70));
        let now = chrono::Utc::now().timestamp();
        let restored = vec![crate::track::state::BanRecord {
            ip,
            jail_id: "sshd".to_string(),
            banned_at: now,
            expires_at: Some(now + 3600),
        }];

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, _executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                restored,
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::ManualBan {
                ip,
                jail_id: "sshd".to_string(),
                ban_time: 3600,
                respond: respond_tx,
            })
            .await
            .unwrap();

        let result = respond_rx.await.unwrap();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already banned"));

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn manual_unban_via_cmd() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let ip = IpAddr::V4(Ipv4Addr::new(80, 80, 80, 80));
        let now = chrono::Utc::now().timestamp();
        let restored = vec![crate::track::state::BanRecord {
            ip,
            jail_id: "sshd".to_string(),
            banned_at: now,
            expires_at: Some(now + 3600),
        }];

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                restored,
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::ManualUnban {
                ip,
                jail_id: "sshd".to_string(),
                respond: respond_tx,
            })
            .await
            .unwrap();

        let result = respond_rx.await.unwrap();
        assert!(result.is_ok());

        // Should receive Unban command.
        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout")
            .expect("channel closed");
        assert!(matches!(cmd, FirewallCmd::Unban { .. }));

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn query_bans_via_cmd() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let ip = IpAddr::V4(Ipv4Addr::new(90, 90, 90, 90));
        let now = chrono::Utc::now().timestamp();
        let restored = vec![crate::track::state::BanRecord {
            ip,
            jail_id: "sshd".to_string(),
            banned_at: now,
            expires_at: Some(now + 3600),
        }];

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, _executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                restored,
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::QueryBans {
                respond: respond_tx,
            })
            .await
            .unwrap();

        let bans = respond_rx.await.unwrap();
        assert_eq!(bans.len(), 1);
        assert_eq!(bans[0].ip, ip);

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn get_stats_via_cmd() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, _executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        // Send some failures first.
        let ip = IpAddr::V4(Ipv4Addr::new(100, 100, 100, 100));
        let now = chrono::Utc::now().timestamp();
        for i in 0..2 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::GetStats {
                respond: respond_tx,
            })
            .await
            .unwrap();

        let stats = respond_rx.await.unwrap();
        assert_eq!(stats.total_failures, 2);
        assert_eq!(stats.active_bans, 0);
        assert!(stats.jails.contains_key("sshd"));
        assert_eq!(stats.jails["sshd"].total_failures, 2);

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn same_ip_different_jails_tracked_independently() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());
        let mut nginx = test_jail_config();
        nginx.filter = vec!["client: <HOST>".to_string()];
        jails.insert("nginx".to_string(), nginx);

        let (failure_tx, failure_rx) = mpsc::channel(64);
        let (executor_tx, mut executor_rx) = mpsc::channel(64);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(10, 10, 10, 10));
        let now = chrono::Utc::now().timestamp();

        // Trigger ban in sshd (3 failures = max_retry).
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        // Should receive Ban for sshd.
        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .expect("timeout")
            .expect("channel closed");
        match &cmd {
            FirewallCmd::Ban { jail_id, .. } => assert_eq!(jail_id, "sshd"),
            other => panic!("expected Ban for sshd, got: {other:?}"),
        }

        // Same IP, trigger ban in nginx (3 more failures).
        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "nginx".to_string(),
                    timestamp: now + 10 + i,
                })
                .await
                .unwrap();
        }

        // Should receive Ban for nginx (same IP, different jail).
        let mut got_nginx_ban = false;
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
        while tokio::time::Instant::now() < deadline {
            match tokio::time::timeout(std::time::Duration::from_millis(200), executor_rx.recv())
                .await
            {
                Ok(Some(FirewallCmd::Ban { jail_id, .. })) if jail_id == "nginx" => {
                    got_nginx_ban = true;
                    break;
                }
                Ok(Some(_)) => {}
                Ok(None) => break,
                Err(_) => {}
            }
        }
        assert!(
            got_nginx_ban,
            "same IP should be independently bannable in different jails"
        );

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_maxmind_asn_att() {
        let _ = tracing_subscriber::fmt()
            .with_env_filter("info")
            .with_test_writer()
            .try_init();

        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        // Target: ASN 7018 (AT&T Services, Inc.)
        let ip: std::net::IpAddr = "71.134.65.5".parse().unwrap();
        let now = chrono::Utc::now().timestamp();

        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(cmd, FirewallCmd::Ban { .. }));

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_maxmind_country_uk_ipv6() {
        let _ = tracing_subscriber::fmt()
            .with_env_filter("info")
            .with_test_writer()
            .try_init();

        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        // Target: United Kingdom (IPv6)
        let ip: std::net::IpAddr = "2a02:dd40:22::42".parse().unwrap();
        let now = chrono::Utc::now().timestamp();

        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(cmd, FirewallCmd::Ban { .. }));

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_maxmind_city_sweden() {
        let _ = tracing_subscriber::fmt()
            .with_env_filter("info")
            .with_test_writer()
            .try_init();

        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, mut executor_rx) = mpsc::channel(16);
        let (_cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        // Target: Linköping, Sweden (Validates UTF-8 handling too!)
        let ip: std::net::IpAddr = "89.160.20.142".parse().unwrap();
        let now = chrono::Utc::now().timestamp();

        for i in 0..3 {
            failure_tx
                .send(Failure {
                    ip,
                    jail_id: "sshd".to_string(),
                    timestamp: now + i,
                })
                .await
                .unwrap();
        }

        let cmd = tokio::time::timeout(std::time::Duration::from_secs(2), executor_rx.recv())
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(cmd, FirewallCmd::Ban { .. }));

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_manual_ban_unknown_jail_returns_error() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, _executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(110, 110, 110, 110));
        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::ManualBan {
                ip,
                jail_id: "nonexistent_jail".to_string(),
                ban_time: 3600,
                respond: respond_tx,
            })
            .await
            .unwrap();

        let result = respond_rx.await.unwrap();
        assert!(result.is_err(), "unknown jail should return an error");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("unknown jail"),
            "error should mention unknown jail, got: {err_msg}"
        );

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_manual_unban_unknown_jail_returns_error() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, _executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(111, 111, 111, 111));
        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::ManualUnban {
                ip,
                jail_id: "nonexistent_jail".to_string(),
                respond: respond_tx,
            })
            .await
            .unwrap();

        let result = respond_rx.await.unwrap();
        assert!(result.is_err(), "unknown jail should return an error");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("unknown jail"),
            "error should mention unknown jail, got: {err_msg}"
        );

        cancel.cancel();
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_manual_unban_not_banned_returns_error() {
        let mut jails = HashMap::new();
        jails.insert("sshd".to_string(), test_jail_config());

        // No restored bans — IP is not currently banned.
        let (_failure_tx, failure_rx) = mpsc::channel(16);
        let (executor_tx, _executor_rx) = mpsc::channel(16);
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let cancel = CancellationToken::new();

        let cancel_clone = cancel.clone();
        let handle = tokio::spawn(async move {
            crate::track::run(
                test_global_config(),
                jails,
                failure_rx,
                cmd_rx,
                executor_tx,
                vec![],
                std::collections::HashMap::new(),
                test_store(),
                None,
                cancel_clone,
            )
            .await;
        });

        let ip = IpAddr::V4(Ipv4Addr::new(112, 112, 112, 112));
        let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
        cmd_tx
            .send(TrackerCmd::ManualUnban {
                ip,
                jail_id: "sshd".to_string(),
                respond: respond_tx,
            })
            .await
            .unwrap();

        let result = respond_rx.await.unwrap();
        assert!(
            result.is_err(),
            "unbanning a non-banned IP should return an error"
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not banned"),
            "error should mention not banned, got: {err_msg}"
        );

        cancel.cancel();
        handle.await.unwrap();
    }
}