sozu 2.1.0

sozu, a fast, reliable, hot reconfigurable HTTP reverse proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
use std::{collections::BTreeMap, fs::File, io::Read as IoRead, path::PathBuf};

use sozu_command_lib::{
    certificate::{
        decode_fingerprint, get_fingerprint_from_certificate_path, load_full_certificate,
    },
    config::{ListenerBuilder, validate_health_check_config},
    proto::command::{
        ActivateListener, AddBackend, AddCertificate, AlpnProtocols, Cluster, CountRequests,
        CustomHttpAnswers, DeactivateListener, FrontendFilters, HardStop, HealthCheckConfig,
        ListListeners, ListenerType, LoadBalancingParams, MetricsConfiguration, PathRule,
        ProxyProtocolConfig, QueryCertificatesFilters, QueryClusterByDomain, QueryClustersHashes,
        QueryHealthChecks, QueryMaxConnectionsPerIp, RemoveBackend, RemoveCertificate,
        RemoveListener, ReplaceCertificate, RequestHttpFrontend, RequestTcpFrontend,
        RequestUdpFrontend, RulePosition, SetHealthCheck, SocketAddress, SoftStop, Status,
        SubscribeEvents, TlsVersion, UpdateHttpListenerConfig, UpdateHttpsListenerConfig,
        UpdateTcpListenerConfig, UpdateUdpListenerConfig, request::RequestType,
        response_content::ContentType,
    },
};

use super::CtlError;
use crate::{
    cli::{
        BackendCmd, ClusterCmd, ClusterH2Cmd, ConnectionLimitCmd, HealthCheckCmd, HttpFrontendCmd,
        HttpListenerCmd, HttpsListenerCmd, MetricsCmd, TcpFrontendCmd, TcpListenerCmd,
        UdpFrontendCmd, UdpListenerCmd,
    },
    ctl::CommandManager,
};

impl CommandManager {
    pub fn save_state(&mut self, path: String) -> Result<(), CtlError> {
        debug!("Saving the state to file {}", path);

        let current_directory =
            std::env::current_dir().map_err(|err| CtlError::ResolvePath(path.to_owned(), err))?;

        let absolute_path = current_directory.join(&path);
        self.send_request(
            RequestType::SaveState(String::from(absolute_path.to_string_lossy())).into(),
        )
    }

    pub fn load_state(&mut self, path: String) -> Result<(), CtlError> {
        debug!("Loading the state on path {}", path);

        self.send_request(RequestType::LoadState(path).into())
    }

    pub fn count_requests(&mut self) -> Result<(), CtlError> {
        self.send_request(RequestType::CountRequests(CountRequests {}).into())
    }

    pub fn soft_stop(&mut self) -> Result<(), CtlError> {
        debug!("shutting down proxy softly");

        self.send_request(RequestType::SoftStop(SoftStop {}).into())
    }

    pub fn hard_stop(&mut self) -> Result<(), CtlError> {
        debug!("shutting down proxy the hard way");

        self.send_request(RequestType::HardStop(HardStop {}).into())
    }

    pub fn status(&mut self) -> Result<(), CtlError> {
        debug!("Requesting status…");

        self.send_request(RequestType::Status(Status {}).into())
    }

    pub fn configure_metrics(&mut self, cmd: MetricsCmd) -> Result<(), CtlError> {
        debug!("Configuring metrics: {:?}", cmd);

        let configuration = match cmd {
            MetricsCmd::Enable => MetricsConfiguration::Enabled,
            MetricsCmd::Disable => MetricsConfiguration::Disabled,
            MetricsCmd::Clear => MetricsConfiguration::Clear,
            _ => return Ok(()), // completely unlikely
        };

        self.send_request(RequestType::ConfigureMetrics(configuration as i32).into())
    }

    pub fn reload_configuration(&mut self, path: Option<String>) -> Result<(), CtlError> {
        debug!("Reloading configuration…");
        self.send_request(RequestType::ReloadConfiguration(path.unwrap_or_default()).into())
    }

    pub fn list_frontends(
        &mut self,
        http: bool,
        https: bool,
        tcp: bool,
        domain: Option<String>,
    ) -> Result<(), CtlError> {
        debug!("Listing frontends");

        self.send_request(
            RequestType::ListFrontends(FrontendFilters {
                http,
                https,
                tcp,
                domain,
            })
            .into(),
        )
    }

    pub fn events(&mut self) -> Result<(), CtlError> {
        self.send_request_no_timeout(RequestType::SubscribeEvents(SubscribeEvents {}).into())
    }

    pub fn backend_command(&mut self, cmd: BackendCmd) -> Result<(), CtlError> {
        match cmd {
            BackendCmd::Add {
                id,
                backend_id,
                address,
                sticky_id,
                backup,
            } => self.send_request(
                RequestType::AddBackend(AddBackend {
                    cluster_id: id,
                    address: address.into(),
                    backend_id,
                    load_balancing_parameters: Some(LoadBalancingParams::default()),
                    sticky_id,
                    backup,
                })
                .into(),
            ),
            BackendCmd::Remove {
                id,
                backend_id,
                address,
            } => self.send_request(
                RequestType::RemoveBackend(RemoveBackend {
                    cluster_id: id,
                    address: address.into(),
                    backend_id,
                })
                .into(),
            ),
        }
    }

    pub fn cluster_command(&mut self, cmd: ClusterCmd) -> Result<(), CtlError> {
        match cmd {
            ClusterCmd::Add {
                id,
                sticky_session,
                https_redirect,
                send_proxy,
                expect_proxy,
                load_balancing_policy,
                http2,
                https_redirect_port,
                www_authenticate,
                authorized_hash,
                answer,
            } => {
                let proxy_protocol = match (send_proxy, expect_proxy) {
                    (true, true) => Some(ProxyProtocolConfig::RelayHeader),
                    (true, false) => Some(ProxyProtocolConfig::SendHeader),
                    (false, true) => Some(ProxyProtocolConfig::ExpectHeader),
                    _ => None,
                };

                // Validate every authorized hash matches `<user>:<hex64>`
                // before sending so a typo (missing colon, lowercase off,
                // non-hex chars) surfaces here with a friendly message
                // rather than silently rejecting traffic on the worker.
                for hash in &authorized_hash {
                    if !looks_like_authorized_hash(hash) {
                        return Err(CtlError::ArgsNeeded(
                            "valid `username:hex(sha256(password))`".to_string(),
                            format!(
                                "got {hash:?}; produce one with: \
                                 printf '<password>' | sha256sum"
                            ),
                        ));
                    }
                }

                // The proto carries `https_redirect_port` as `u32` (matches
                // the rewrite_port shape on the frontend) but real TCP
                // ports are 16-bit. Reject out-of-range values up front so
                // a typo doesn't render `Location: https://host:70000/...`
                // on the wire.
                if let Some(port) = https_redirect_port {
                    if port == 0 || port > u16::MAX as u32 {
                        return Err(CtlError::ArgsNeeded(
                            "TCP port in 1..=65535".to_string(),
                            format!("got https_redirect_port={port}"),
                        ));
                    }
                }

                // Resolve each `--answer code=value` entry. The
                // right-hand side is the literal template body by
                // default; `file://<path>` opts into reading the body
                // off disk. Funnels through the canonical
                // `resolve_answer_source` helper so the CLI and TOML
                // loader stay in sync.
                //
                // Cluster-level entries override the listener-level
                // `answers` map (which itself is the global default for
                // every status code on that listener). Both layers
                // accept the same `<body> | file://<path>` value form.
                let mut answers_map = std::collections::BTreeMap::new();
                for entry in &answer {
                    let (code, value) = match entry.split_once('=') {
                        Some((c, v)) if !v.is_empty() => (c, v),
                        _ => {
                            return Err(CtlError::ArgsNeeded(
                                "<code>=<body>|file://<path>".to_string(),
                                format!("got {entry:?}"),
                            ));
                        }
                    };
                    let body =
                        sozu_command_lib::config::resolve_answer_source(value).map_err(|e| {
                            CtlError::ArgsNeeded(
                                "literal body or readable file://<path>".to_string(),
                                format!("{value:?}: {e}"),
                            )
                        })?;
                    answers_map.insert(code.to_owned(), body);
                }

                self.send_request(
                    RequestType::AddCluster(Cluster {
                        cluster_id: id,
                        sticky_session,
                        https_redirect,
                        proxy_protocol: proxy_protocol.map(|pp| pp as i32),
                        load_balancing: load_balancing_policy as i32,
                        http2: if http2 { Some(true) } else { None },
                        answers: answers_map,
                        https_redirect_port,
                        authorized_hashes: authorized_hash,
                        www_authenticate,
                        ..Default::default()
                    })
                    .into(),
                )
            }
            ClusterCmd::Remove { id } => self.send_request(RequestType::RemoveCluster(id).into()),
            ClusterCmd::H2 { cmd } => self.cluster_h2_command(cmd),
            ClusterCmd::HealthCheck { cmd } => self.health_check_command(cmd),
            ClusterCmd::List {
                id: cluster_id,
                domain,
            } => {
                if cluster_id.is_some() && domain.is_some() {
                    return Err(CtlError::ArgsNeeded(
                        "a cluster id".to_string(),
                        "a domain name".to_string(),
                    ));
                }

                let request = if let Some(ref cluster_id) = cluster_id {
                    RequestType::QueryClusterById(cluster_id.to_string()).into()
                } else if let Some(ref domain) = domain {
                    let splitted: Vec<String> =
                        domain.splitn(2, '/').map(|elem| elem.to_string()).collect();

                    if splitted.is_empty() {
                        return Err(CtlError::NeedClusterDomain)?;
                    }

                    let query_domain = QueryClusterByDomain {
                        hostname: splitted.first().ok_or(CtlError::NeedClusterDomain)?.clone(),
                        path: splitted.get(1).cloned().map(|path| format!("/{path}")), // We add the / again because of the splitn removing it
                    };

                    RequestType::QueryClustersByDomain(query_domain).into()
                } else {
                    RequestType::QueryClustersHashes(QueryClustersHashes {}).into()
                };

                self.send_request(request)
            }
        }
    }

    pub fn cluster_h2_command(&mut self, cmd: ClusterH2Cmd) -> Result<(), CtlError> {
        let (cluster_id, enable) = match cmd {
            ClusterH2Cmd::Enable { id } => (id, true),
            ClusterH2Cmd::Disable { id } => (id, false),
        };

        let request = RequestType::QueryClusterById(cluster_id.clone()).into();
        let response = self.send_request_get_response(request, true)?;

        let cluster = response
            .content
            .and_then(|content| content.content_type)
            .and_then(|content_type| find_cluster_configuration(content_type, &cluster_id))
            .ok_or_else(|| {
                CtlError::ArgsNeeded("cluster not found".to_owned(), cluster_id.clone())
            })?;

        let updated = Cluster {
            http2: Some(enable),
            ..cluster
        };

        self.send_request(RequestType::AddCluster(updated).into())
    }

    pub fn health_check_command(&mut self, cmd: HealthCheckCmd) -> Result<(), CtlError> {
        match cmd {
            HealthCheckCmd::Set {
                id,
                uri,
                interval,
                timeout,
                healthy_threshold,
                unhealthy_threshold,
                expected_status,
            } => {
                let config = HealthCheckConfig {
                    uri,
                    interval,
                    timeout,
                    healthy_threshold,
                    unhealthy_threshold,
                    expected_status,
                };
                if let Err(reason) = validate_health_check_config(&config) {
                    return Err(CtlError::Failure(reason.to_owned()));
                }
                if config.timeout >= config.interval {
                    warn!(
                        "health check timeout ({}s) >= interval ({}s), checks may overlap",
                        config.timeout, config.interval
                    );
                }
                self.send_request(
                    RequestType::SetHealthCheck(SetHealthCheck {
                        cluster_id: id,
                        config,
                    })
                    .into(),
                )
            }
            HealthCheckCmd::Remove { id } => {
                self.send_request(RequestType::RemoveHealthCheck(id).into())
            }
            HealthCheckCmd::List { id } => self.send_request(
                RequestType::QueryHealthChecks(QueryHealthChecks { cluster_id: id }).into(),
            ),
        }
    }

    pub fn tcp_frontend_command(&mut self, cmd: TcpFrontendCmd) -> Result<(), CtlError> {
        match cmd {
            TcpFrontendCmd::Add { id, address, tags } => self.send_request(
                RequestType::AddTcpFrontend(RequestTcpFrontend {
                    cluster_id: id,
                    address: address.into(),
                    tags: tags.unwrap_or(BTreeMap::new()),
                })
                .into(),
            ),
            TcpFrontendCmd::Remove { id, address } => self.send_request(
                RequestType::RemoveTcpFrontend(RequestTcpFrontend {
                    cluster_id: id,
                    address: address.into(),
                    ..Default::default()
                })
                .into(),
            ),
        }
    }

    pub fn udp_frontend_command(&mut self, cmd: UdpFrontendCmd) -> Result<(), CtlError> {
        match cmd {
            UdpFrontendCmd::Add { id, address, tags } => self.send_request(
                RequestType::AddUdpFrontend(RequestUdpFrontend {
                    cluster_id: id,
                    address: address.into(),
                    tags: tags.unwrap_or(BTreeMap::new()),
                })
                .into(),
            ),
            UdpFrontendCmd::Remove { id, address } => self.send_request(
                RequestType::RemoveUdpFrontend(RequestUdpFrontend {
                    cluster_id: id,
                    address: address.into(),
                    ..Default::default()
                })
                .into(),
            ),
        }
    }

    pub fn http_frontend_command(&mut self, cmd: HttpFrontendCmd) -> Result<(), CtlError> {
        match cmd {
            HttpFrontendCmd::Add { .. } => {
                let frontend = build_http_frontend_add(cmd)?;
                self.send_request(RequestType::AddHttpFrontend(frontend).into())
            }
            HttpFrontendCmd::Remove {
                hostname,
                path_prefix,
                path_regex,
                path_equals,
                address,
                method,
                cluster_id: route,
            } => self.send_request(
                RequestType::RemoveHttpFrontend(RequestHttpFrontend {
                    cluster_id: route.into(),
                    address: address.into(),
                    hostname,
                    path: PathRule::from_cli_options(path_prefix, path_regex, path_equals),
                    method,
                    ..Default::default()
                })
                .into(),
            ),
        }
    }

    pub fn https_frontend_command(&mut self, cmd: HttpFrontendCmd) -> Result<(), CtlError> {
        match cmd {
            HttpFrontendCmd::Add { .. } => {
                let frontend = build_http_frontend_add(cmd)?;
                self.send_request(RequestType::AddHttpsFrontend(frontend).into())
            }
            HttpFrontendCmd::Remove {
                hostname,
                path_prefix,
                path_regex,
                path_equals,
                address,
                method,
                cluster_id: route,
            } => self.send_request(
                RequestType::RemoveHttpsFrontend(RequestHttpFrontend {
                    cluster_id: route.into(),
                    address: address.into(),
                    hostname,
                    path: PathRule::from_cli_options(path_prefix, path_regex, path_equals),
                    method,
                    ..Default::default()
                })
                .into(),
            ),
        }
    }

    pub fn https_listener_command(&mut self, cmd: HttpsListenerCmd) -> Result<(), CtlError> {
        match cmd {
            HttpsListenerCmd::Add {
                address,
                public_address,
                answer_404,
                answer_503,
                tls_versions,
                cipher_list,
                expect_proxy,
                sticky_name,
                front_timeout,
                back_timeout,
                request_timeout,
                connect_timeout,
            } => {
                let https_listener = ListenerBuilder::new_https(address.into())
                    .with_public_address(public_address)
                    .with_answer_404_path(answer_404)
                    .with_answer_503_path(answer_503)
                    .with_tls_versions(tls_versions)
                    .with_cipher_list(cipher_list)
                    .with_expect_proxy(expect_proxy)
                    .with_sticky_name(sticky_name)
                    .with_front_timeout(front_timeout)
                    .with_back_timeout(back_timeout)
                    .with_request_timeout(request_timeout)
                    .with_connect_timeout(connect_timeout)
                    .to_tls(Some(&self.config))
                    .map_err(CtlError::CreateListener)?;

                self.send_request(RequestType::AddHttpsListener(https_listener).into())
            }
            HttpsListenerCmd::Remove { address } => {
                self.remove_listener(address.into(), ListenerType::Https)
            }
            HttpsListenerCmd::Activate { address } => {
                self.activate_listener(address.into(), ListenerType::Https)
            }
            HttpsListenerCmd::Deactivate { address } => {
                self.deactivate_listener(address.into(), ListenerType::Https)
            }
            HttpsListenerCmd::Update {
                address,
                public_address,
                sticky_name,
                front_timeout,
                back_timeout,
                connect_timeout,
                request_timeout,
                expect_proxy,
                no_expect_proxy,
                strict_sni_binding,
                no_strict_sni_binding,
                disable_http11,
                enable_http11,
                alpn_protocols,
                reset_alpn,
                h2_max_rst_stream_per_window,
                h2_max_ping_per_window,
                h2_max_settings_per_window,
                h2_max_empty_data_per_window,
                h2_max_continuation_frames,
                h2_max_glitch_count,
                h2_initial_connection_window,
                h2_max_concurrent_streams,
                h2_stream_shrink_ratio,
                h2_max_rst_stream_lifetime,
                h2_max_rst_stream_abusive_lifetime,
                h2_max_rst_stream_emitted_lifetime,
                h2_max_header_list_size,
                h2_max_header_table_size,
                h2_max_header_fields,
                h2_stream_idle_timeout_seconds,
                h2_graceful_shutdown_deadline_seconds,
                h2_max_window_update_stream0_per_window,
                sozu_id_header,
                answer_301,
                answer_401,
                answer_404,
                answer_408,
                answer_413,
                answer_421,
                answer_429,
                answer_502,
                answer_503,
                answer_504,
                answer_507,
                hsts_max_age,
                hsts_include_subdomains,
                hsts_preload,
                hsts_disabled,
                hsts_force_replace_backend,
            } => self.update_https_listener_command(
                address,
                public_address,
                sticky_name,
                front_timeout,
                back_timeout,
                connect_timeout,
                request_timeout,
                expect_proxy,
                no_expect_proxy,
                strict_sni_binding,
                no_strict_sni_binding,
                disable_http11,
                enable_http11,
                alpn_protocols,
                reset_alpn,
                h2_max_rst_stream_per_window,
                h2_max_ping_per_window,
                h2_max_settings_per_window,
                h2_max_empty_data_per_window,
                h2_max_continuation_frames,
                h2_max_glitch_count,
                h2_initial_connection_window,
                h2_max_concurrent_streams,
                h2_stream_shrink_ratio,
                h2_max_rst_stream_lifetime,
                h2_max_rst_stream_abusive_lifetime,
                h2_max_rst_stream_emitted_lifetime,
                h2_max_header_list_size,
                h2_max_header_table_size,
                h2_max_header_fields,
                h2_stream_idle_timeout_seconds,
                h2_graceful_shutdown_deadline_seconds,
                h2_max_window_update_stream0_per_window,
                sozu_id_header,
                answer_301,
                answer_401,
                answer_404,
                answer_408,
                answer_413,
                answer_421,
                answer_429,
                answer_502,
                answer_503,
                answer_504,
                answer_507,
                hsts_max_age,
                hsts_include_subdomains,
                hsts_preload,
                hsts_disabled,
                hsts_force_replace_backend,
            ),
        }
    }

    pub fn http_listener_command(&mut self, cmd: HttpListenerCmd) -> Result<(), CtlError> {
        match cmd {
            HttpListenerCmd::Add {
                address,
                public_address,
                answer_404,
                answer_503,
                expect_proxy,
                sticky_name,
                front_timeout,
                back_timeout,
                request_timeout,
                connect_timeout,
            } => {
                let http_listener = ListenerBuilder::new_http(address.into())
                    .with_public_address(public_address)
                    .with_answer_404_path(answer_404)
                    .with_answer_503_path(answer_503)
                    .with_expect_proxy(expect_proxy)
                    .with_sticky_name(sticky_name)
                    .with_front_timeout(front_timeout)
                    .with_request_timeout(request_timeout)
                    .with_back_timeout(back_timeout)
                    .with_connect_timeout(connect_timeout)
                    .to_http(Some(&self.config))
                    .map_err(CtlError::CreateListener)?;

                self.send_request(RequestType::AddHttpListener(http_listener).into())
            }
            HttpListenerCmd::Remove { address } => {
                self.remove_listener(address.into(), ListenerType::Http)
            }
            HttpListenerCmd::Activate { address } => {
                self.activate_listener(address.into(), ListenerType::Http)
            }
            HttpListenerCmd::Deactivate { address } => {
                self.deactivate_listener(address.into(), ListenerType::Http)
            }
            HttpListenerCmd::Update {
                address,
                public_address,
                sticky_name,
                front_timeout,
                back_timeout,
                connect_timeout,
                request_timeout,
                expect_proxy,
                no_expect_proxy,
                h2_max_rst_stream_per_window,
                h2_max_ping_per_window,
                h2_max_settings_per_window,
                h2_max_empty_data_per_window,
                h2_max_continuation_frames,
                h2_max_glitch_count,
                h2_initial_connection_window,
                h2_max_concurrent_streams,
                h2_stream_shrink_ratio,
                h2_max_rst_stream_lifetime,
                h2_max_rst_stream_abusive_lifetime,
                h2_max_rst_stream_emitted_lifetime,
                h2_max_header_list_size,
                h2_max_header_table_size,
                h2_max_header_fields,
                h2_stream_idle_timeout_seconds,
                h2_graceful_shutdown_deadline_seconds,
                h2_max_window_update_stream0_per_window,
                sozu_id_header,
                answer_301,
                answer_401,
                answer_404,
                answer_408,
                answer_413,
                answer_421,
                answer_429,
                answer_502,
                answer_503,
                answer_504,
                answer_507,
            } => self.update_http_listener_command(
                address,
                public_address,
                sticky_name,
                front_timeout,
                back_timeout,
                connect_timeout,
                request_timeout,
                expect_proxy,
                no_expect_proxy,
                h2_max_rst_stream_per_window,
                h2_max_ping_per_window,
                h2_max_settings_per_window,
                h2_max_empty_data_per_window,
                h2_max_continuation_frames,
                h2_max_glitch_count,
                h2_initial_connection_window,
                h2_max_concurrent_streams,
                h2_stream_shrink_ratio,
                h2_max_rst_stream_lifetime,
                h2_max_rst_stream_abusive_lifetime,
                h2_max_rst_stream_emitted_lifetime,
                h2_max_header_list_size,
                h2_max_header_table_size,
                h2_max_header_fields,
                h2_stream_idle_timeout_seconds,
                h2_graceful_shutdown_deadline_seconds,
                h2_max_window_update_stream0_per_window,
                sozu_id_header,
                answer_301,
                answer_401,
                answer_404,
                answer_408,
                answer_413,
                answer_421,
                answer_429,
                answer_502,
                answer_503,
                answer_504,
                answer_507,
            ),
        }
    }

    pub fn tcp_listener_command(&mut self, cmd: TcpListenerCmd) -> Result<(), CtlError> {
        match cmd {
            TcpListenerCmd::Add {
                address,
                public_address,
                expect_proxy,
            } => {
                let listener = ListenerBuilder::new_tcp(address.into())
                    .with_public_address(public_address)
                    .with_expect_proxy(expect_proxy)
                    .to_tcp(Some(&self.config))
                    .map_err(CtlError::CreateListener)?;

                self.send_request(RequestType::AddTcpListener(listener).into())
            }
            TcpListenerCmd::Remove { address } => {
                self.remove_listener(address.into(), ListenerType::Tcp)
            }
            TcpListenerCmd::Activate { address } => {
                self.activate_listener(address.into(), ListenerType::Tcp)
            }
            TcpListenerCmd::Deactivate { address } => {
                self.deactivate_listener(address.into(), ListenerType::Tcp)
            }
            TcpListenerCmd::Update {
                address,
                public_address,
                front_timeout,
                back_timeout,
                connect_timeout,
                expect_proxy,
                no_expect_proxy,
            } => self.update_tcp_listener_command(
                address,
                public_address,
                front_timeout,
                back_timeout,
                connect_timeout,
                expect_proxy,
                no_expect_proxy,
            ),
        }
    }

    pub fn udp_listener_command(&mut self, cmd: UdpListenerCmd) -> Result<(), CtlError> {
        match cmd {
            UdpListenerCmd::Add {
                address,
                public_address,
                front_timeout,
                back_timeout,
                max_rx_datagram_size,
                max_flows,
            } => {
                let mut builder = ListenerBuilder::new_udp(address.into());
                builder
                    .with_public_address(public_address)
                    .with_front_timeout(front_timeout)
                    .with_back_timeout(back_timeout);
                // `ListenerBuilder` exposes no dedicated setters for the two
                // UDP-only knobs; assign the public fields directly. `to_udp`
                // applies the documented defaults (1500 / 0) when left `None`.
                builder.max_rx_datagram_size = max_rx_datagram_size;
                builder.max_flows = max_flows;

                let listener = builder
                    .to_udp(Some(&self.config))
                    .map_err(CtlError::CreateListener)?;

                self.send_request(RequestType::AddUdpListener(listener).into())
            }
            UdpListenerCmd::Remove { address } => {
                self.remove_listener(address.into(), ListenerType::Udp)
            }
            UdpListenerCmd::Activate { address } => {
                self.activate_listener(address.into(), ListenerType::Udp)
            }
            UdpListenerCmd::Deactivate { address } => {
                self.deactivate_listener(address.into(), ListenerType::Udp)
            }
            UdpListenerCmd::Update {
                address,
                public_address,
                front_timeout,
                back_timeout,
                max_rx_datagram_size,
                max_flows,
            } => self.update_udp_listener_command(
                address,
                public_address,
                front_timeout,
                back_timeout,
                max_rx_datagram_size,
                max_flows,
            ),
        }
    }

    pub fn list_listeners(&mut self) -> Result<(), CtlError> {
        self.send_request(RequestType::ListListeners(ListListeners {}).into())
    }

    /// Patch a running HTTP listener in place. Only `Some` fields in the patch
    /// are applied; `None` fields preserve the listener's current value.
    #[allow(clippy::too_many_arguments)]
    pub fn update_http_listener_command(
        &mut self,
        address: std::net::SocketAddr,
        public_address: Option<std::net::SocketAddr>,
        sticky_name: Option<String>,
        front_timeout: Option<u32>,
        back_timeout: Option<u32>,
        connect_timeout: Option<u32>,
        request_timeout: Option<u32>,
        expect_proxy_flag: bool,
        no_expect_proxy_flag: bool,
        h2_max_rst_stream_per_window: Option<u32>,
        h2_max_ping_per_window: Option<u32>,
        h2_max_settings_per_window: Option<u32>,
        h2_max_empty_data_per_window: Option<u32>,
        h2_max_continuation_frames: Option<u32>,
        h2_max_glitch_count: Option<u32>,
        h2_initial_connection_window: Option<u32>,
        h2_max_concurrent_streams: Option<u32>,
        h2_stream_shrink_ratio: Option<u32>,
        h2_max_rst_stream_lifetime: Option<u64>,
        h2_max_rst_stream_abusive_lifetime: Option<u64>,
        h2_max_rst_stream_emitted_lifetime: Option<u64>,
        h2_max_header_list_size: Option<u32>,
        h2_max_header_table_size: Option<u32>,
        h2_max_header_fields: Option<u32>,
        h2_stream_idle_timeout_seconds: Option<u32>,
        h2_graceful_shutdown_deadline_seconds: Option<u32>,
        h2_max_window_update_stream0_per_window: Option<u32>,
        sozu_id_header: Option<String>,
        answer_301: Option<PathBuf>,
        answer_401: Option<PathBuf>,
        answer_404: Option<PathBuf>,
        answer_408: Option<PathBuf>,
        answer_413: Option<PathBuf>,
        answer_421: Option<PathBuf>,
        answer_429: Option<PathBuf>,
        answer_502: Option<PathBuf>,
        answer_503: Option<PathBuf>,
        answer_504: Option<PathBuf>,
        answer_507: Option<PathBuf>,
    ) -> Result<(), CtlError> {
        let expect_proxy = if expect_proxy_flag {
            Some(true)
        } else if no_expect_proxy_flag {
            Some(false)
        } else {
            None
        };

        let http_answers = build_http_answers(
            answer_301, answer_401, answer_404, answer_408, answer_413, answer_421, answer_429,
            answer_502, answer_503, answer_504, answer_507,
        )?;

        let patch = UpdateHttpListenerConfig {
            address: address.into(),
            public_address: public_address.map(|a| a.into()),
            expect_proxy,
            sticky_name,
            front_timeout,
            back_timeout,
            connect_timeout,
            request_timeout,
            http_answers,
            h2_max_rst_stream_per_window,
            h2_max_ping_per_window,
            h2_max_settings_per_window,
            h2_max_empty_data_per_window,
            h2_max_continuation_frames,
            h2_max_glitch_count,
            h2_initial_connection_window,
            h2_max_concurrent_streams,
            h2_stream_shrink_ratio,
            h2_max_rst_stream_lifetime,
            h2_max_rst_stream_abusive_lifetime,
            h2_max_rst_stream_emitted_lifetime,
            h2_max_header_list_size,
            h2_max_header_table_size,
            h2_max_header_fields,
            h2_stream_idle_timeout_seconds,
            h2_graceful_shutdown_deadline_seconds,
            h2_max_window_update_stream0_per_window,
            sozu_id_header,
            ..Default::default()
        };
        self.send_request(RequestType::UpdateHttpListener(patch).into())
    }

    /// Patch a running HTTPS listener in place. Only `Some` fields in the patch
    /// are applied; `None` fields preserve the listener's current value.
    #[allow(clippy::too_many_arguments)]
    pub fn update_https_listener_command(
        &mut self,
        address: std::net::SocketAddr,
        public_address: Option<std::net::SocketAddr>,
        sticky_name: Option<String>,
        front_timeout: Option<u32>,
        back_timeout: Option<u32>,
        connect_timeout: Option<u32>,
        request_timeout: Option<u32>,
        expect_proxy_flag: bool,
        no_expect_proxy_flag: bool,
        strict_sni_binding_flag: bool,
        no_strict_sni_binding_flag: bool,
        disable_http11_flag: bool,
        enable_http11_flag: bool,
        alpn_protocols: Option<Vec<String>>,
        reset_alpn: bool,
        h2_max_rst_stream_per_window: Option<u32>,
        h2_max_ping_per_window: Option<u32>,
        h2_max_settings_per_window: Option<u32>,
        h2_max_empty_data_per_window: Option<u32>,
        h2_max_continuation_frames: Option<u32>,
        h2_max_glitch_count: Option<u32>,
        h2_initial_connection_window: Option<u32>,
        h2_max_concurrent_streams: Option<u32>,
        h2_stream_shrink_ratio: Option<u32>,
        h2_max_rst_stream_lifetime: Option<u64>,
        h2_max_rst_stream_abusive_lifetime: Option<u64>,
        h2_max_rst_stream_emitted_lifetime: Option<u64>,
        h2_max_header_list_size: Option<u32>,
        h2_max_header_table_size: Option<u32>,
        h2_max_header_fields: Option<u32>,
        h2_stream_idle_timeout_seconds: Option<u32>,
        h2_graceful_shutdown_deadline_seconds: Option<u32>,
        h2_max_window_update_stream0_per_window: Option<u32>,
        sozu_id_header: Option<String>,
        answer_301: Option<PathBuf>,
        answer_401: Option<PathBuf>,
        answer_404: Option<PathBuf>,
        answer_408: Option<PathBuf>,
        answer_413: Option<PathBuf>,
        answer_421: Option<PathBuf>,
        answer_429: Option<PathBuf>,
        answer_502: Option<PathBuf>,
        answer_503: Option<PathBuf>,
        answer_504: Option<PathBuf>,
        answer_507: Option<PathBuf>,
        hsts_max_age: Option<u32>,
        hsts_include_subdomains: bool,
        hsts_preload: bool,
        hsts_disabled: bool,
        hsts_force_replace_backend: bool,
    ) -> Result<(), CtlError> {
        let expect_proxy = if expect_proxy_flag {
            Some(true)
        } else if no_expect_proxy_flag {
            Some(false)
        } else {
            None
        };

        let strict_sni_binding = if strict_sni_binding_flag {
            Some(true)
        } else if no_strict_sni_binding_flag {
            Some(false)
        } else {
            None
        };

        let disable_http11 = if disable_http11_flag {
            Some(true)
        } else if enable_http11_flag {
            Some(false)
        } else {
            None
        };

        // `--reset-alpn` ⇒ Some(AlpnProtocols { values: [] }) = "reset to default"
        // `--alpn-protocols h2,http/1.1` ⇒ Some(AlpnProtocols { values: [...] })
        // neither ⇒ None = "preserve current value"
        let alpn_protocols_patch = if reset_alpn {
            Some(AlpnProtocols { values: vec![] })
        } else {
            alpn_protocols.map(|values| AlpnProtocols { values })
        };

        let http_answers = build_http_answers(
            answer_301, answer_401, answer_404, answer_408, answer_413, answer_421, answer_429,
            answer_502, answer_503, answer_504, answer_507,
        )?;

        // Reuses the same builder as `frontend https add` so the
        // mutual-exclusion rules and the canonical
        // `DEFAULT_HSTS_MAX_AGE` substitution stay in lock-step
        // between the two CLI surfaces.
        let hsts = build_hsts_from_cli(
            hsts_max_age,
            hsts_include_subdomains,
            hsts_preload,
            hsts_disabled,
            hsts_force_replace_backend,
        )?;

        let patch = UpdateHttpsListenerConfig {
            address: address.into(),
            public_address: public_address.map(|a| a.into()),
            expect_proxy,
            sticky_name,
            front_timeout,
            back_timeout,
            connect_timeout,
            request_timeout,
            http_answers,
            alpn_protocols: alpn_protocols_patch,
            strict_sni_binding,
            disable_http11,
            h2_max_rst_stream_per_window,
            h2_max_ping_per_window,
            h2_max_settings_per_window,
            h2_max_empty_data_per_window,
            h2_max_continuation_frames,
            h2_max_glitch_count,
            h2_initial_connection_window,
            h2_max_concurrent_streams,
            h2_stream_shrink_ratio,
            h2_max_rst_stream_lifetime,
            h2_max_rst_stream_abusive_lifetime,
            h2_max_rst_stream_emitted_lifetime,
            h2_max_header_list_size,
            h2_max_header_table_size,
            h2_max_header_fields,
            h2_stream_idle_timeout_seconds,
            h2_graceful_shutdown_deadline_seconds,
            h2_max_window_update_stream0_per_window,
            sozu_id_header,
            hsts,
            ..Default::default()
        };
        self.send_request(RequestType::UpdateHttpsListener(patch).into())
    }

    /// Patch a running TCP listener in place. Only `Some` fields in the patch
    /// are applied; `None` fields preserve the listener's current value.
    pub fn update_tcp_listener_command(
        &mut self,
        address: std::net::SocketAddr,
        public_address: Option<std::net::SocketAddr>,
        front_timeout: Option<u32>,
        back_timeout: Option<u32>,
        connect_timeout: Option<u32>,
        expect_proxy_flag: bool,
        no_expect_proxy_flag: bool,
    ) -> Result<(), CtlError> {
        let expect_proxy = if expect_proxy_flag {
            Some(true)
        } else if no_expect_proxy_flag {
            Some(false)
        } else {
            None
        };

        let patch = UpdateTcpListenerConfig {
            address: address.into(),
            public_address: public_address.map(|a| a.into()),
            expect_proxy,
            front_timeout,
            back_timeout,
            connect_timeout,
        };
        self.send_request(RequestType::UpdateTcpListener(patch).into())
    }

    /// Patch a running UDP listener in place. Only `Some` fields in the patch
    /// are applied; `None` fields preserve the listener's current value.
    pub fn update_udp_listener_command(
        &mut self,
        address: std::net::SocketAddr,
        public_address: Option<std::net::SocketAddr>,
        front_timeout: Option<u32>,
        back_timeout: Option<u32>,
        max_rx_datagram_size: Option<u32>,
        max_flows: Option<u32>,
    ) -> Result<(), CtlError> {
        let patch = UpdateUdpListenerConfig {
            address: address.into(),
            public_address: public_address.map(|a| a.into()),
            front_timeout,
            back_timeout,
            max_rx_datagram_size,
            max_flows,
        };
        self.send_request(RequestType::UpdateUdpListener(patch).into())
    }

    pub fn remove_listener(
        &mut self,
        address: SocketAddress,
        listener_type: ListenerType,
    ) -> Result<(), CtlError> {
        self.send_request(
            RequestType::RemoveListener(RemoveListener {
                address,
                proxy: listener_type.into(),
            })
            .into(),
        )
    }

    pub fn activate_listener(
        &mut self,
        address: SocketAddress,
        listener_type: ListenerType,
    ) -> Result<(), CtlError> {
        self.send_request(
            RequestType::ActivateListener(ActivateListener {
                address,
                proxy: listener_type.into(),
                from_scm: false,
            })
            .into(),
        )
    }

    pub fn deactivate_listener(
        &mut self,
        address: SocketAddress,
        listener_type: ListenerType,
    ) -> Result<(), CtlError> {
        self.send_request(
            RequestType::DeactivateListener(DeactivateListener {
                address,
                proxy: listener_type.into(),
                to_scm: false,
            })
            .into(),
        )
    }

    pub fn logging_filter(&mut self, filter: String) -> Result<(), CtlError> {
        self.send_request(RequestType::Logging(filter).into())
    }

    pub fn add_certificate(
        &mut self,
        address: SocketAddress,
        certificate_path: &str,
        certificate_chain_path: &str,
        key_path: &str,
        versions: Vec<TlsVersion>,
    ) -> Result<(), CtlError> {
        let new_certificate = load_full_certificate(
            certificate_path,
            certificate_chain_path,
            key_path,
            versions,
            vec![],
        )
        .map_err(CtlError::LoadCertificate)?;

        self.send_request(
            RequestType::AddCertificate(AddCertificate {
                address,
                certificate: new_certificate,
                expired_at: None,
            })
            .into(),
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn replace_certificate(
        &mut self,
        address: SocketAddress,
        new_certificate_path: &str,
        new_certificate_chain_path: &str,
        new_key_path: &str,
        old_certificate_path: Option<&str>,
        old_fingerprint: Option<&str>,
        versions: Vec<TlsVersion>,
    ) -> Result<(), CtlError> {
        let old_fingerprint = match (old_certificate_path, old_fingerprint) {
            (None, None) | (Some(_), Some(_)) => {
                return Err(CtlError::ArgsNeeded(
                    "the path to the old certificate".to_string(),
                    "the path to the old fingerprint".to_string(),
                ));
            }
            (Some(old_certificate_path), None) => {
                get_fingerprint_from_certificate_path(old_certificate_path)
                    .map_err(CtlError::GetFingerprint)?
            }
            (None, Some(fingerprint)) => {
                decode_fingerprint(fingerprint).map_err(CtlError::DecodeFingerprint)?
            }
        };

        let new_certificate = load_full_certificate(
            new_certificate_path,
            new_certificate_chain_path,
            new_key_path,
            versions,
            vec![],
        )
        .map_err(CtlError::LoadCertificate)?;

        self.send_request(
            RequestType::ReplaceCertificate(ReplaceCertificate {
                address,
                new_certificate,
                old_fingerprint: old_fingerprint.to_string(),
                new_expired_at: None,
            })
            .into(),
        )?;

        Ok(())
    }

    pub fn remove_certificate(
        &mut self,
        address: SocketAddress,
        certificate_path: Option<&str>,
        fingerprint: Option<&str>,
    ) -> Result<(), CtlError> {
        let fingerprint = match (certificate_path, fingerprint) {
            (None, None) | (Some(_), Some(_)) => {
                return Err(CtlError::ArgsNeeded(
                    "the path to the certificate".to_string(),
                    "the fingerprint of the certificate".to_string(),
                ));
            }
            (Some(certificate_path), None) => {
                get_fingerprint_from_certificate_path(certificate_path)
                    .map_err(CtlError::GetFingerprint)?
            }
            (None, Some(fingerprint)) => {
                decode_fingerprint(fingerprint).map_err(CtlError::DecodeFingerprint)?
            }
        };

        self.send_request(
            RequestType::RemoveCertificate(RemoveCertificate {
                address,
                fingerprint: fingerprint.to_string(),
            })
            .into(),
        )
    }

    pub fn query_certificates(
        &mut self,
        fingerprint: Option<String>,
        domain: Option<String>,
        query_workers: bool,
    ) -> Result<(), CtlError> {
        let filters = QueryCertificatesFilters {
            domain,
            fingerprint,
        };

        if query_workers {
            self.send_request(RequestType::QueryCertificatesFromWorkers(filters).into())
        } else {
            self.send_request(RequestType::QueryCertificatesFromTheState(filters).into())
        }
    }

    pub fn upgrade_worker(&mut self, worker_id: u32) -> Result<(), CtlError> {
        debug!("upgrading worker {}", worker_id);
        self.send_request(RequestType::UpgradeWorker(worker_id).into())
    }

    /// Drives `sozu connection-limit {set|remove|show}` from the CLI to
    /// the worker via the command socket. The setter is non-sticky:
    /// workers reset to the TOML-configured value on restart, so
    /// operators must mirror the change in the config to make it
    /// durable. The query path returns the live in-memory value.
    pub fn connection_limit_command(&mut self, cmd: ConnectionLimitCmd) -> Result<(), CtlError> {
        match cmd {
            ConnectionLimitCmd::Set { limit } => {
                self.send_request(RequestType::SetMaxConnectionsPerIp(limit).into())
            }
            ConnectionLimitCmd::Remove => {
                self.send_request(RequestType::SetMaxConnectionsPerIp(0).into())
            }
            ConnectionLimitCmd::Show => self.send_request(
                RequestType::QueryMaxConnectionsPerIp(QueryMaxConnectionsPerIp {}).into(),
            ),
        }
    }
}

fn find_cluster_configuration(content_type: ContentType, cluster_id: &str) -> Option<Cluster> {
    match content_type {
        ContentType::Clusters(infos) => infos
            .vec
            .into_iter()
            .find(|info| {
                info.configuration
                    .as_ref()
                    .is_some_and(|cluster| cluster.cluster_id == cluster_id)
            })
            .and_then(|info| info.configuration),
        ContentType::WorkerResponses(mut worker_responses) => {
            if let Some(content) = worker_responses.map.remove("main") {
                return content
                    .content_type
                    .and_then(|content_type| find_cluster_configuration(content_type, cluster_id));
            }

            worker_responses.map.into_values().find_map(|content| {
                content
                    .content_type
                    .and_then(|content_type| find_cluster_configuration(content_type, cluster_id))
            })
        }
        _ => None,
    }
}

/// Build a [`RequestHttpFrontend`] from the policy fields collected by
/// `HttpFrontendCmd::Add`. The same builder feeds both
/// `RequestType::AddHttpFrontend` and `RequestType::AddHttpsFrontend` so
/// the two `frontend {http,https} add` paths stay in lock-step.
///
/// Validates each policy field up front and returns a typed
/// [`CtlError::ArgsNeeded`] on a malformed input rather than letting a
/// silent default reach the worker.
fn build_http_frontend_add(cmd: HttpFrontendCmd) -> Result<RequestHttpFrontend, CtlError> {
    let HttpFrontendCmd::Add {
        hostname,
        path_prefix,
        path_regex,
        path_equals,
        address,
        method,
        cluster_id: route,
        tags,
        redirect,
        redirect_scheme,
        redirect_template,
        rewrite_host,
        rewrite_path,
        rewrite_port,
        required_auth,
        header,
        hsts_max_age,
        hsts_include_subdomains,
        hsts_preload,
        hsts_disabled,
        hsts_force_replace_backend,
    } = cmd
    else {
        return Err(CtlError::ArgsNeeded(
            "HttpFrontendCmd::Add".to_owned(),
            "got non-Add variant — should be unreachable".to_owned(),
        ));
    };

    // Map `--redirect <forward|permanent|unauthorized>` onto the proto
    // enum. Unknown / mistyped value surfaces a typed error here.
    let redirect_proto = match redirect.as_deref() {
        None => None,
        Some(s) => Some(match s.to_ascii_lowercase().as_str() {
            "forward" => sozu_command_lib::proto::command::RedirectPolicy::Forward as i32,
            "permanent" => sozu_command_lib::proto::command::RedirectPolicy::Permanent as i32,
            "unauthorized" => sozu_command_lib::proto::command::RedirectPolicy::Unauthorized as i32,
            other => {
                return Err(CtlError::ArgsNeeded(
                    "redirect in {forward, permanent, unauthorized}".to_owned(),
                    format!("got --redirect={other:?}"),
                ));
            }
        }),
    };

    let redirect_scheme_proto = match redirect_scheme.as_deref() {
        None => None,
        Some(s) => Some(match s.to_ascii_lowercase().as_str() {
            "use-same" | "use_same" => {
                sozu_command_lib::proto::command::RedirectScheme::UseSame as i32
            }
            "use-http" | "use_http" => {
                sozu_command_lib::proto::command::RedirectScheme::UseHttp as i32
            }
            "use-https" | "use_https" => {
                sozu_command_lib::proto::command::RedirectScheme::UseHttps as i32
            }
            other => {
                return Err(CtlError::ArgsNeeded(
                    "redirect-scheme in {use-same, use-http, use-https}".to_owned(),
                    format!("got --redirect-scheme={other:?}"),
                ));
            }
        }),
    };

    if let Some(port) = rewrite_port {
        if port == 0 || port > u16::MAX as u32 {
            return Err(CtlError::ArgsNeeded(
                "TCP port in 1..=65535".to_owned(),
                format!("got rewrite_port={port}"),
            ));
        }
    }

    // Each `--header` entry is `<position>=<key>=<value>`. Split on the
    // first two `=` so the value may contain further `=` bytes (common
    // in cookie / quoted strings). Empty value preserves HAProxy
    // `del-header` parity.
    let mut headers_proto = Vec::with_capacity(header.len());
    for (index, raw) in header.iter().enumerate() {
        let (position, rest) = raw.split_once('=').ok_or_else(|| {
            CtlError::ArgsNeeded(
                "<position>=<name>=<value>".to_owned(),
                format!("--header[{index}] = {raw:?} (missing first `=`)"),
            )
        })?;
        let (key, val) = rest.split_once('=').ok_or_else(|| {
            CtlError::ArgsNeeded(
                "<position>=<name>=<value>".to_owned(),
                format!("--header[{index}] = {raw:?} (missing second `=`)"),
            )
        })?;
        let position_proto = match position.to_ascii_lowercase().as_str() {
            "request" => sozu_command_lib::proto::command::HeaderPosition::Request as i32,
            "response" => sozu_command_lib::proto::command::HeaderPosition::Response as i32,
            "both" => sozu_command_lib::proto::command::HeaderPosition::Both as i32,
            other => {
                return Err(CtlError::ArgsNeeded(
                    "header position in {request, response, both}".to_owned(),
                    format!("--header[{index}] position={other:?}"),
                ));
            }
        };
        // Reject CRLF / NUL / other C0 controls. CRLF in the value would
        // let an operator (or a misuse via piped CLI args) splice
        // arbitrary header / request lines into the H1 wire on the
        // backend side (CWE-113 / request smuggling). The H2 emission
        // path filters values at runtime; the H1 path serialises raw,
        // so we reject at CLI parse time as a defense in depth and to
        // give a clear error.
        //
        // The KEY check is stricter than the value check — RFC 9110
        // §5.1 field names follow the `token` grammar (no HTAB, no SP,
        // no C0 controls); reusing the value-side predicate would let
        // `Host\t` slip through and produce an invalid header line on
        // the wire (security review follow-up on `da845c71`).
        if !is_valid_header_name(key.as_bytes()) {
            return Err(CtlError::ArgsNeeded(
                "header key matching RFC 9110 token grammar (alphanumeric or one of !#$%&'*+-.^_`|~)".to_owned(),
                format!("--header[{index}] key={key:?}"),
            ));
        }
        if header_value_has_control_byte(val.as_bytes()) {
            return Err(CtlError::ArgsNeeded(
                "header value without control characters (NUL / CR / LF / other C0)".to_owned(),
                format!("--header[{index}] val={val:?}"),
            ));
        }
        headers_proto.push(sozu_command_lib::proto::command::Header {
            position: position_proto,
            key: key.to_owned(),
            val: val.to_owned(),
        });
    }

    // Build the typed HSTS block from the four `--hsts-*` flags. Layering:
    // - `--hsts-disabled` is mutually exclusive with the enabling flags;
    //   if combined we error rather than silently picking one (operator
    //   intent is ambiguous).
    // - any of `--hsts-max-age`, `--hsts-include-subdomains`,
    //   `--hsts-preload` flips the frontend into "explicit enable"; the
    //   worker substitutes `DEFAULT_HSTS_MAX_AGE = 31_536_000` if
    //   `--hsts-max-age` is omitted (matching the TOML semantics in
    //   `command/src/config.rs::FileHstsConfig::to_proto`).
    // - none of the flags = `None` = inherit listener default.
    let hsts_proto = build_hsts_from_cli(
        hsts_max_age,
        hsts_include_subdomains,
        hsts_preload,
        hsts_disabled,
        hsts_force_replace_backend,
    )?;

    Ok(RequestHttpFrontend {
        cluster_id: route.into(),
        address: address.into(),
        hostname,
        path: PathRule::from_cli_options(path_prefix, path_regex, path_equals),
        method,
        position: RulePosition::Tree.into(),
        tags: tags.unwrap_or_default(),
        redirect: redirect_proto,
        redirect_scheme: redirect_scheme_proto,
        redirect_template,
        rewrite_host,
        rewrite_path,
        rewrite_port,
        required_auth: if required_auth { Some(true) } else { None },
        headers: headers_proto,
        hsts: hsts_proto,
    })
}

/// Combine the four `--hsts-*` CLI flags into an `Option<HstsConfig>`.
/// `None` = inherit listener default; `Some(HstsConfig { enabled: Some(false), .. })`
/// = explicit disable (suppresses listener default); `Some(HstsConfig { enabled: Some(true), .. })`
/// = explicit enable with the specified knobs (the helper substitutes the
/// canonical `DEFAULT_HSTS_MAX_AGE = 31_536_000` here so the IPC payload
/// is self-contained — the worker no longer needs to apply a default for
/// CLI-built frontends; only the TOML loader path still substitutes there
/// because `FileHstsConfig` carries the typed `Option<u32>` shape).
/// `--hsts-disabled` mutually excludes the three enabling flags; the
/// function returns a typed `CtlError::ArgsNeeded` rather than silently
/// picking an interpretation.
fn build_hsts_from_cli(
    max_age: Option<u32>,
    include_subdomains: bool,
    preload: bool,
    disabled: bool,
    force_replace_backend: bool,
) -> Result<Option<sozu_command_lib::proto::command::HstsConfig>, CtlError> {
    use sozu_command_lib::proto::command::HstsConfig;

    let any_enabling = max_age.is_some() || include_subdomains || preload || force_replace_backend;
    if disabled && any_enabling {
        return Err(CtlError::ArgsNeeded(
            "either --hsts-disabled OR (--hsts-max-age | --hsts-include-subdomains | --hsts-preload | --hsts-force-replace-backend) — not both"
                .to_owned(),
            "got --hsts-disabled together with one of the enabling flags".to_owned(),
        ));
    }
    if disabled {
        return Ok(Some(HstsConfig {
            enabled: Some(false),
            max_age: None,
            include_subdomains: None,
            preload: None,
            force_replace_backend: None,
        }));
    }
    if !any_enabling {
        return Ok(None);
    }
    Ok(Some(HstsConfig {
        enabled: Some(true),
        // Substitute the canonical default at CLI-build time so the
        // resulting IPC payload renders end-to-end without the worker
        // having to re-apply a default. Mirrors the TOML loader's
        // substitution in `FileHstsConfig::to_proto`.
        max_age: max_age.or(Some(sozu_command_lib::config::DEFAULT_HSTS_MAX_AGE)),
        include_subdomains: if include_subdomains { Some(true) } else { None },
        preload: if preload { Some(true) } else { None },
        force_replace_backend: if force_replace_backend {
            Some(true)
        } else {
            None
        },
    }))
}

#[cfg(test)]
mod hsts_cli_tests {
    use super::*;
    use sozu_command_lib::config::DEFAULT_HSTS_MAX_AGE;

    #[test]
    fn no_flags_returns_none() {
        // No `--hsts-*` flags = inherit listener default.
        assert!(matches!(
            build_hsts_from_cli(None, false, false, false, false),
            Ok(None)
        ));
    }

    #[test]
    fn disabled_only_returns_some_disabled() {
        let out = build_hsts_from_cli(None, false, false, true, false)
            .expect("should validate")
            .expect("should be Some");
        assert_eq!(out.enabled, Some(false));
        assert_eq!(out.max_age, None);
        assert_eq!(out.include_subdomains, None);
        assert_eq!(out.preload, None);
        assert_eq!(out.force_replace_backend, None);
    }

    #[test]
    fn partial_enabling_substitutes_default_max_age() {
        // Operator opted into HSTS via --hsts-include-subdomains alone;
        // helper must substitute the canonical default so the worker
        // does not see a `max_age = None` and silently no-op the render.
        let out = build_hsts_from_cli(None, true, false, false, false)
            .expect("should validate")
            .expect("should be Some");
        assert_eq!(out.enabled, Some(true));
        assert_eq!(out.max_age, Some(DEFAULT_HSTS_MAX_AGE));
        assert_eq!(out.include_subdomains, Some(true));
        assert_eq!(out.force_replace_backend, None);
    }

    #[test]
    fn explicit_max_age_kept() {
        let out = build_hsts_from_cli(Some(63_072_000), true, true, false, false)
            .expect("should validate")
            .expect("should be Some");
        assert_eq!(out.max_age, Some(63_072_000));
        assert_eq!(out.preload, Some(true));
    }

    #[test]
    fn force_replace_backend_alone_enables_with_default_max_age() {
        // Setting --hsts-force-replace-backend on its own is also an
        // enabling flag — operator wants override semantics; the
        // canonical default max-age applies.
        let out = build_hsts_from_cli(None, false, false, false, true)
            .expect("should validate")
            .expect("should be Some");
        assert_eq!(out.enabled, Some(true));
        assert_eq!(out.max_age, Some(DEFAULT_HSTS_MAX_AGE));
        assert_eq!(out.force_replace_backend, Some(true));
    }

    #[test]
    fn disabled_with_force_replace_returns_args_needed() {
        match build_hsts_from_cli(None, false, false, true, true).unwrap_err() {
            CtlError::ArgsNeeded(_, _) => {}
            other => panic!("expected ArgsNeeded, got {other:?}"),
        }
    }

    #[test]
    fn disabled_with_enabling_flags_returns_args_needed() {
        match build_hsts_from_cli(Some(31_536_000), false, false, true, false).unwrap_err() {
            CtlError::ArgsNeeded(_, _) => {}
            other => panic!("expected ArgsNeeded, got {other:?}"),
        }
    }
}

/// Reject NUL / CR / LF / other C0 controls in a header value. HTAB
/// (`\x09`) is permitted per RFC 9110 §5.5 and matches the runtime
/// filter at `lib::protocol::mux::converter::call`.
fn header_value_has_control_byte(bytes: &[u8]) -> bool {
    bytes
        .iter()
        .any(|&b| matches!(b, 0x00..=0x08 | 0x0A..=0x1F | 0x7F))
}

/// Header field names follow the RFC 9110 §5.1 `token` grammar: a
/// non-empty sequence of `tchar` bytes (alphanumeric plus a closed
/// punctuation list). HTAB and SP are NOT tchar — they belong to
/// field-VALUE grammar. Reusing `header_value_has_control_byte` for
/// keys would let `Host\t` slip through and produce an invalid header
/// line on the H1 backend wire.
fn is_valid_header_name(bytes: &[u8]) -> bool {
    if bytes.is_empty() {
        return false;
    }
    bytes.iter().all(|&b| {
        b.is_ascii_alphanumeric()
            || matches!(
                b,
                b'!' | b'#'
                    | b'$'
                    | b'%'
                    | b'&'
                    | b'\''
                    | b'*'
                    | b'+'
                    | b'-'
                    | b'.'
                    | b'^'
                    | b'_'
                    | b'`'
                    | b'|'
                    | b'~'
            )
    })
}

/// Validate that `s` matches the canonical `<user>:<hex(sha256)>` form
/// the worker stores in `Cluster.authorized_hashes`. Equivalent to the
/// regex `^[A-Za-z0-9_\-]+:[0-9a-f]{64}$`; inlined as bytes so we don't
/// pull `regex` in here for a one-line validator.
pub(crate) fn looks_like_authorized_hash(s: &str) -> bool {
    let Some((user, hex)) = s.split_once(':') else {
        return false;
    };
    !user.is_empty()
        && user
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
        && hex.len() == 64
        && hex
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// Load the content of an HTTP-answer file path. Returns `None` if the path is
/// `None`. Mirrors the logic in `command/src/config.rs::read_http_answer_file`.
fn read_answer_path(path: &Option<PathBuf>) -> Result<Option<String>, CtlError> {
    let Some(path) = path else { return Ok(None) };
    let mut content = String::new();
    File::open(path)
        .and_then(|mut f| f.read_to_string(&mut content))
        .map_err(|io_error| CtlError::ResolvePath(path.display().to_string(), io_error))?;
    Ok(Some(content))
}

/// Build a [`CustomHttpAnswers`] proto from optional file-path arguments.
/// Returns `None` when every path argument is `None` (no-op on the listener).
#[allow(clippy::too_many_arguments)]
fn build_http_answers(
    answer_301: Option<PathBuf>,
    answer_401: Option<PathBuf>,
    answer_404: Option<PathBuf>,
    answer_408: Option<PathBuf>,
    answer_413: Option<PathBuf>,
    answer_421: Option<PathBuf>,
    answer_429: Option<PathBuf>,
    answer_502: Option<PathBuf>,
    answer_503: Option<PathBuf>,
    answer_504: Option<PathBuf>,
    answer_507: Option<PathBuf>,
) -> Result<Option<CustomHttpAnswers>, CtlError> {
    // Only produce the sub-message when at least one path was given.
    if answer_301.is_none()
        && answer_401.is_none()
        && answer_404.is_none()
        && answer_408.is_none()
        && answer_413.is_none()
        && answer_421.is_none()
        && answer_429.is_none()
        && answer_502.is_none()
        && answer_503.is_none()
        && answer_504.is_none()
        && answer_507.is_none()
    {
        return Ok(None);
    }
    Ok(Some(CustomHttpAnswers {
        answer_301: read_answer_path(&answer_301)?,
        answer_400: None, // not exposed via the CLI update verb
        answer_401: read_answer_path(&answer_401)?,
        answer_404: read_answer_path(&answer_404)?,
        answer_408: read_answer_path(&answer_408)?,
        answer_413: read_answer_path(&answer_413)?,
        answer_421: read_answer_path(&answer_421)?,
        answer_429: read_answer_path(&answer_429)?,
        answer_502: read_answer_path(&answer_502)?,
        answer_503: read_answer_path(&answer_503)?,
        answer_504: read_answer_path(&answer_504)?,
        answer_507: read_answer_path(&answer_507)?,
    }))
}

#[cfg(test)]
mod tests {
    use sozu_command_lib::proto::command::{
        ClusterInformation, ClusterInformations, LoadBalancingAlgorithms, ResponseContent,
        WorkerResponses,
    };

    use super::*;

    fn cluster(cluster_id: &str, sticky_session: bool) -> Cluster {
        Cluster {
            cluster_id: cluster_id.to_owned(),
            sticky_session,
            https_redirect: false,
            load_balancing: LoadBalancingAlgorithms::RoundRobin as i32,
            ..Default::default()
        }
    }

    fn clusters_response(clusters: Vec<Cluster>) -> ContentType {
        ContentType::Clusters(ClusterInformations {
            vec: clusters
                .into_iter()
                .map(|cluster| ClusterInformation {
                    configuration: Some(cluster),
                    ..Default::default()
                })
                .collect(),
        })
    }

    fn response_content(content_type: ContentType) -> ResponseContent {
        ResponseContent {
            content_type: Some(content_type),
        }
    }

    #[test]
    fn finds_cluster_configuration_from_direct_cluster_response() {
        let found = find_cluster_configuration(
            clusters_response(vec![cluster("other", false), cluster("target", true)]),
            "target",
        );

        assert_eq!(found.map(|cluster| cluster.sticky_session), Some(true));
    }

    #[test]
    fn finds_cluster_configuration_from_main_worker_response() {
        let mut map = BTreeMap::new();
        map.insert(
            "0".to_owned(),
            response_content(clusters_response(vec![cluster("target", true)])),
        );
        map.insert(
            "main".to_owned(),
            response_content(clusters_response(vec![cluster("target", false)])),
        );

        let found = find_cluster_configuration(
            ContentType::WorkerResponses(WorkerResponses { map }),
            "target",
        );

        assert_eq!(found.map(|cluster| cluster.sticky_session), Some(false));
    }

    #[test]
    fn falls_back_to_worker_cluster_response_when_main_is_absent() {
        let mut map = BTreeMap::new();
        map.insert(
            "0".to_owned(),
            response_content(clusters_response(vec![cluster("target", true)])),
        );

        let found = find_cluster_configuration(
            ContentType::WorkerResponses(WorkerResponses { map }),
            "target",
        );

        assert_eq!(
            found.map(|cluster| cluster.cluster_id),
            Some("target".to_owned())
        );
    }

    #[test]
    fn does_not_fall_back_to_worker_when_main_is_present() {
        let mut map = BTreeMap::new();
        map.insert(
            "0".to_owned(),
            response_content(clusters_response(vec![cluster("target", true)])),
        );
        map.insert(
            "main".to_owned(),
            response_content(clusters_response(vec![cluster("other", false)])),
        );

        let found = find_cluster_configuration(
            ContentType::WorkerResponses(WorkerResponses { map }),
            "target",
        );

        assert!(found.is_none());
    }

    #[test]
    fn returns_none_when_cluster_is_missing() {
        let found =
            find_cluster_configuration(clusters_response(vec![cluster("other", false)]), "target");

        assert!(found.is_none());
    }

    #[test]
    fn accepts_canonical_user_hex64() {
        assert!(looks_like_authorized_hash(
            "admin:2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b"
        ));
    }

    #[test]
    fn rejects_missing_colon() {
        assert!(!looks_like_authorized_hash("admin"));
    }

    #[test]
    fn rejects_short_hex_tail() {
        assert!(!looks_like_authorized_hash("admin:deadbeef"));
    }

    #[test]
    fn rejects_uppercase_hex() {
        assert!(!looks_like_authorized_hash(
            "admin:2BB80D537B1DA3E38BD30361AA855686BDE0EACD7162FEF6A25FE97BF527A25B"
        ));
    }

    #[test]
    fn rejects_empty_username() {
        assert!(!looks_like_authorized_hash(
            ":2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b"
        ));
    }

    #[test]
    fn rejects_non_alnum_username() {
        assert!(!looks_like_authorized_hash(
            "admin user:2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b"
        ));
    }
}