arks-server 1.3.11

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
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
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
//! Loopback smart-HTTP listener for clean-room / local serve.
//!
//! Optional in-process TLS terminate via operator-supplied PEMs
//! ([[sot:root/arks-claimed-residual-gates]] B9). Dual-bind drain on rebind
//! supports B7 Claimed evidence when harnessed.

use crate::auth::BasicAuthConfig;
use crate::error::ServerError;
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use arks_repo::Repository;
use rustls::ServerConfig;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};

static HTTP_REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
static HTTP_ACTIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
static GIT_UPLOAD_PACK_TOTAL: AtomicU64 = AtomicU64::new(0);
static GIT_RECEIVE_PACK_TOTAL: AtomicU64 = AtomicU64::new(0);
static LFS_BYTES_TOTAL: AtomicU64 = AtomicU64::new(0);
static SERVER_START: OnceLock<Instant> = OnceLock::new();
static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);

/// Mark the process as shutting down so `/readyz` flips to 503 during drain (O-1).
pub fn mark_shutting_down() {
    SHUTTING_DOWN.store(true, Ordering::SeqCst);
}

/// Returns `true` once graceful shutdown has been initiated.
pub fn is_shutting_down() -> bool {
    SHUTTING_DOWN.load(Ordering::SeqCst)
}

/// Real readiness probe check for `/readyz` and `/healthz` (SO-PROBE-1).
fn check_server_readiness(git_dir: &Path, opts: &ServeHttpOptions) -> Result<(), &'static str> {
    if is_shutting_down()
        || opts
            .shutdown_flag
            .as_ref()
            .is_some_and(|f| f.load(Ordering::SeqCst))
    {
        return Err("shutting_down");
    }
    let meta = std::fs::metadata(git_dir).map_err(|_| "data_dir_missing")?;
    if !meta.is_dir() || meta.permissions().readonly() {
        return Err("data_dir_unwritable");
    }
    if !opts.multi_repo_root {
        let store = crate::web_ui::store::ForgeStore::load_shared(git_dir);
        if store.corrupt {
            return Err("store_corrupt");
        }
    }
    Ok(())
}

/// Gate `/metrics` to loopback peers or a valid `Authorization: Bearer <metrics_token>` (SO-MET-1).
fn metrics_authorized(
    peer_ip: std::net::IpAddr,
    authorization: Option<&str>,
    opts: &ServeHttpOptions,
) -> bool {
    use subtle::ConstantTimeEq as _;
    let token = opts
        .metrics_token
        .clone()
        .or_else(|| crate::ops::resolve_secret_env("ARKS_METRICS_TOKEN"))
        .filter(|t| !t.trim().is_empty());
    if let (Some(expected), Some(auth)) = (token.as_deref(), authorization) {
        if let Some(presented) = auth
            .strip_prefix("Bearer ")
            .or_else(|| auth.strip_prefix("bearer "))
        {
            let a = expected.as_bytes();
            let b = presented.trim().as_bytes();
            if a.len() == b.len() && bool::from(a.ct_eq(b)) {
                return true;
            }
        }
    }
    peer_ip.is_loopback() && !opts.metrics_require_token
}

fn max_http_body_bytes() -> usize {
    std::env::var("ARKS_HTTP_MAX_BODY_BYTES")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(64 * 1024 * 1024)
}

fn max_http_concurrency() -> usize {
    std::env::var("ARKS_HTTP_MAX_CONCURRENCY")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(128)
}

fn max_http_header_timeout() -> Duration {
    let secs = std::env::var("ARKS_HTTP_HEADER_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(10);
    Duration::from_secs(secs)
}

fn max_http_body_timeout() -> Duration {
    let secs = std::env::var("ARKS_HTTP_BODY_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(60);
    Duration::from_secs(secs)
}

/// Returns true for transient `accept()` errors (FD exhaustion `EMFILE`/`ENFILE`,
/// aborted handshake, or interrupt) where the listener must back off rather than exit.
pub(crate) fn is_transient_accept_error(err: &std::io::Error) -> bool {
    if matches!(
        err.kind(),
        std::io::ErrorKind::WouldBlock
            | std::io::ErrorKind::Interrupted
            | std::io::ErrorKind::ConnectionAborted
            | std::io::ErrorKind::ConnectionReset
    ) {
        return true;
    }
    #[cfg(unix)]
    {
        // ENOMEM (12), ENFILE (23), EMFILE (24), macOS ENOBUFS (55), Linux ENOBUFS (105).
        if matches!(err.raw_os_error(), Some(12 | 23 | 24 | 55 | 105)) {
            return true;
        }
    }
    #[cfg(windows)]
    {
        // WSAEMFILE (10024), WSAECONNRESET (10054), WSAENOBUFS (10055).
        if matches!(err.raw_os_error(), Some(10024 | 10054 | 10055)) {
            return true;
        }
    }
    false
}

pub(crate) struct ActiveConnGuard;
impl Drop for ActiveConnGuard {
    fn drop(&mut self) {
        HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Release);
    }
}

/// Atomically reserve an HTTP concurrency slot up to `limit` before spawning a worker thread.
pub(crate) fn try_reserve_http_slot_with_limit(limit: usize) -> Option<ActiveConnGuard> {
    let mut cur = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire);
    loop {
        if cur >= limit {
            return None;
        }
        match HTTP_ACTIVE_CONNECTIONS.compare_exchange_weak(
            cur,
            cur + 1,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(_) => return Some(ActiveConnGuard),
            Err(observed) => cur = observed,
        }
    }
}

/// Atomically reserve an HTTP concurrency slot before spawning a worker thread.
fn try_reserve_http_slot() -> Option<ActiveConnGuard> {
    try_reserve_http_slot_with_limit(max_http_concurrency())
}

/// Returns the number of currently active in-flight HTTP requests (for graceful drain).
#[allow(dead_code)]
pub fn active_http_connections() -> usize {
    HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire)
}

type LoopbackHttp = (
    SocketAddr,
    Arc<AtomicBool>,
    thread::JoinHandle<Result<(), ServerError>>,
);

/// Shared slot: when set to `Some(addr)`, the HTTP accept loop performs a
/// bounded dual-bind rebind. B7 is Claimed for the evidenced HTTP scenario;
/// SSH/forge rebind and OpenSSH-class interop are separate gates.
pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;

/// Optional page handler consulted for `GET` requests before git HTTP; it
/// answers `Some(response)` for the paths it owns and `None` for the rest
/// (used by `instaweb` for its repository browser pages).
pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;

#[derive(Clone, Default)]
pub struct ServeHttpOptions {
    /// When true, answer `info/refs` (even with `service=`) as dumb text/plain so
    /// smart clients fall back to dumb HTTP (gitprotocol-http). Used by G29.
    pub dumb_only: bool,
    /// Optional in-process HTTP Basic (G36). Unset = unauthenticated (G15).
    pub basic_auth: Option<BasicAuthConfig>,
    /// Optional live listen rebind target (Partial; polled in accept loop).
    pub rebind_desired: Option<ListenRebindSlot>,
    /// Optional rustls server config for in-process TLS terminate (B9).
    pub tls: Option<Arc<ServerConfig>>,
    /// Optional browser pages served beside git HTTP.
    pub pages: Option<PageHandler>,
    /// When true, disable the built-in `/info/lfs` Batch + Basic Transfer server (`--no-lfs`).
    pub disable_lfs: bool,
    /// When true, `git_dir` is a multi-repository root directory and `pages` handles all routes
    /// (Web UI + `/<repo>.git/...` Smart HTTP/LFS) without opening a single repo at `git_dir`.
    pub multi_repo_root: bool,
    /// Optional cumulative HTTP header-read deadline override (falls back to
    /// `ARKS_HTTP_HEADER_TIMEOUT_SECS`, default 10s).
    pub header_timeout: Option<Duration>,
    /// Optional trusted reverse-proxy CIDR configuration (falls back to
    /// `ARKS_TRUSTED_PROXIES`, default loopback-only).
    pub trusted_proxies: Option<crate::proxy::TrustedProxyConfig>,
    /// Optional per-server shutdown flag (used alongside global `SHUTTING_DOWN` for `/readyz`).
    pub shutdown_flag: Option<Arc<AtomicBool>>,
    /// Optional Bearer token authorizing `/metrics` from non-loopback peers
    /// (falls back to `ARKS_METRICS_TOKEN`).
    pub metrics_token: Option<String>,
    /// When true, `/metrics` requires the Bearer token even from loopback peers (used in tests
    /// and strict deployments).
    pub metrics_require_token: bool,
    /// Optional opt-in BYO GitHub App webhook handler (`--github-app-config <path>`).
    pub github_app_webhook: Option<Arc<crate::github_app_webhook::GithubAppWebhookState>>,
}

impl std::fmt::Debug for ServeHttpOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServeHttpOptions")
            .field("dumb_only", &self.dumb_only)
            .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
            .field("rebind_desired", &self.rebind_desired.is_some())
            .field("tls", &self.tls.is_some())
            .field("pages", &self.pages.is_some())
            .field("disable_lfs", &self.disable_lfs)
            .field("multi_repo_root", &self.multi_repo_root)
            .field("header_timeout", &self.header_timeout)
            .field("trusted_proxies", &self.trusted_proxies.is_some())
            .field("shutdown_flag", &self.shutdown_flag.is_some())
            .field("metrics_token", &self.metrics_token.is_some())
            .field("metrics_require_token", &self.metrics_require_token)
            .field("github_app_webhook", &self.github_app_webhook.is_some())
            .finish()
    }
}

/// Bind `addr` and serve `git_dir` over smart HTTP until `stop` is set or accept fails.
pub fn serve_http(
    git_dir: impl AsRef<Path>,
    addr: SocketAddr,
    stop: Arc<AtomicBool>,
) -> Result<(), ServerError> {
    serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
}

pub fn serve_http_with_opts(
    git_dir: impl AsRef<Path>,
    addr: SocketAddr,
    stop: Arc<AtomicBool>,
    opts: ServeHttpOptions,
) -> Result<(), ServerError> {
    let git_dir = git_dir.as_ref().to_path_buf();
    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
    let mut listener = TcpListener::bind(addr)?;
    listener.set_nonblocking(true)?;
    let mut current = addr;
    // A successful rebind keeps prior listeners accepting for this bounded
    // overlap. Accepted handlers are independently owned and always drain.
    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
    let mut last_accept_err_log: Option<Instant> = None;
    while !stop.load(Ordering::SeqCst) {
        if let Some(slot) = &opts.rebind_desired {
            if let Ok(mut g) = slot.lock() {
                if let Some(new_addr) = g.take() {
                    if new_addr != current {
                        match TcpListener::bind(new_addr) {
                            Ok(l) => {
                                if let Err(e) = l.set_nonblocking(true) {
                                    eprintln!(
                                        "arks serve-http: live rebind Partial bind ok but \
                                         nonblocking fail ({e}); keeping {current}"
                                    );
                                    *g = Some(new_addr);
                                } else {
                                    eprintln!(
                                        "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
                                         prior listener draining for 5s"
                                    );
                                    let old = std::mem::replace(&mut listener, l);
                                    draining.push((
                                        old,
                                        current,
                                        Instant::now() + Duration::from_secs(5),
                                    ));
                                    current = new_addr;
                                }
                            }
                            Err(e) => {
                                eprintln!(
                                    "arks serve-http: live rebind Partial fail {current} → \
                                     {new_addr} ({e}); keeping prior listen"
                                );
                            }
                        }
                    }
                }
            }
        }
        draining.retain(|(_, old_addr, deadline)| {
            if Instant::now() < *deadline {
                true
            } else {
                eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
                false
            }
        });
        match listener.accept() {
            Ok((stream, _)) => {
                dispatch_accepted_stream(stream, &git_dir, &opts);
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                thread::sleep(std::time::Duration::from_millis(1));
            }
            Err(e) if is_transient_accept_error(&e) => {
                if last_accept_err_log
                    .map(|t| t.elapsed() >= Duration::from_secs(1))
                    .unwrap_or(true)
                {
                    eprintln!(
                        "arks serve-http: transient accept error on {current} ({e}); backing off"
                    );
                    last_accept_err_log = Some(Instant::now());
                }
                thread::sleep(std::time::Duration::from_millis(25));
            }
            Err(e) => return Err(e.into()),
        }
        for (old_listener, _, _) in &draining {
            match old_listener.accept() {
                Ok((stream, _)) => {
                    dispatch_accepted_stream(stream, &git_dir, &opts);
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(e) => {
                    if last_accept_err_log
                        .map(|t| t.elapsed() >= Duration::from_secs(1))
                        .unwrap_or(true)
                    {
                        eprintln!("arks serve-http: draining listener accept error: {e}");
                        last_accept_err_log = Some(Instant::now());
                    }
                }
            }
        }
    }
    // Graceful shutdown (O-1): stop accepting and wait for in-flight requests to finish
    // up to `ARKS_SHUTDOWN_GRACE_SECS` (default 30s; legacy alias `ARKS_SHUTDOWN_DRAIN_SECS`).
    drop(listener);
    drop(draining);
    let drain_secs = std::env::var("ARKS_SHUTDOWN_GRACE_SECS")
        .or_else(|_| std::env::var("ARKS_SHUTDOWN_DRAIN_SECS"))
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .unwrap_or(30);
    let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
    while active_http_connections() > 0 && Instant::now() < drain_deadline {
        thread::sleep(Duration::from_millis(25));
    }
    Ok(())
}

/// Bind an ephemeral port; return (bound addr, join handle, stop flag).
pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
    spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
}

pub fn spawn_loopback_with_opts(
    git_dir: PathBuf,
    opts: ServeHttpOptions,
) -> Result<LoopbackHttp, ServerError> {
    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let addr = listener.local_addr()?;
    listener.set_nonblocking(true)?;
    let stop = Arc::new(AtomicBool::new(false));
    let stop2 = stop.clone();
    let handle = thread::spawn(move || {
        let mut last_accept_err_log: Option<Instant> = None;
        while !stop2.load(Ordering::SeqCst) {
            match listener.accept() {
                Ok((stream, _)) => {
                    dispatch_accepted_stream(stream, &git_dir, &opts);
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    thread::sleep(std::time::Duration::from_millis(1));
                }
                Err(e) if is_transient_accept_error(&e) => {
                    if last_accept_err_log
                        .map(|t| t.elapsed() >= Duration::from_secs(1))
                        .unwrap_or(true)
                    {
                        eprintln!(
                            "arks serve-http: transient loopback accept error ({e}); backing off"
                        );
                        last_accept_err_log = Some(Instant::now());
                    }
                    thread::sleep(std::time::Duration::from_millis(25));
                }
                Err(e) => return Err(e.into()),
            }
        }
        Ok(())
    });
    Ok((addr, stop, handle))
}

fn send_fast_503(stream: &mut TcpStream) {
    let _ = stream.set_nonblocking(false);
    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
    let resp = HttpResponse {
        status: 503,
        content_type: "text/plain; charset=utf-8".into(),
        body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
        www_authenticate: None,
        extra_headers: vec![("Retry-After".into(), "1".into())],
    };
    let _ = write_http_response(stream, &resp);
    let _ = stream.shutdown(std::net::Shutdown::Write);
}

fn send_fast_408_with_reason<S: HttpStream>(stream: &mut S, reason: &'static [u8]) {
    let resp = HttpResponse {
        status: 408,
        content_type: "text/plain; charset=utf-8".into(),
        body: reason.to_vec(),
        www_authenticate: None,
        extra_headers: Vec::new(),
    };
    let _ = write_http_response(stream, &resp);
    stream.shutdown_write();
}

fn send_fast_408<S: HttpStream>(stream: &mut S) {
    send_fast_408_with_reason(stream, b"Request Timeout: HTTP header deadline exceeded\n");
}

/// Read HTTP body bytes until `buf.len() >= total_needed` under a cumulative `body_timeout`
/// deadline so Slow-POST dribbles cannot hold worker threads indefinitely (`SEC-11`).
/// Returns `Ok(true)` when body reading finished (or peer closed), or `Ok(false)` on timeout.
fn read_http_body_with_deadline<S: HttpStream>(
    stream: &mut S,
    buf: &mut Vec<u8>,
    tmp: &mut [u8],
    total_needed: usize,
    body_timeout: Duration,
) -> Result<bool, ServerError> {
    if buf.len() >= total_needed {
        return Ok(true);
    }
    let body_deadline = Instant::now() + body_timeout;
    while buf.len() < total_needed {
        let now = Instant::now();
        if now >= body_deadline {
            return Ok(false);
        }
        let rem = body_deadline
            .saturating_duration_since(now)
            .max(Duration::from_millis(1));
        stream.set_stream_read_timeout(rem);
        match stream.read(tmp) {
            Ok(0) => break,
            Ok(n) => {
                buf.extend_from_slice(&tmp[..n]);
                if buf.len() < total_needed && Instant::now() >= body_deadline {
                    return Ok(false);
                }
            }
            Err(e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                ) =>
            {
                return Ok(false);
            }
            Err(e) => return Err(e.into()),
        }
    }
    Ok(true)
}

fn is_mutating_git_lfs_dav_request(req: &HttpRequest) -> bool {
    let method = req.method.to_ascii_uppercase();
    let is_receive_pack =
        req.path.ends_with("/git-receive-pack") || req.path.contains("/git-receive-pack");
    if is_receive_pack && !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS") {
        return true;
    }
    if crate::lfs::is_lfs_path(&req.path) && method == "PUT" {
        return true;
    }
    matches!(
        method.as_str(),
        "PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
    )
}

/// Reject cross-origin mutating Git/LFS/WebDAV writes when browser pages are co-hosted (`INT-S03`).
pub(crate) fn check_cross_origin_write(
    opts: &ServeHttpOptions,
    req: &HttpRequest,
) -> Option<HttpResponse> {
    if opts.pages.is_none() || !is_mutating_git_lfs_dav_request(req) {
        return None;
    }
    let Some(origin) = req
        .origin
        .as_deref()
        .map(str::trim)
        .filter(|o| !o.is_empty())
    else {
        if req
            .sec_fetch_site
            .as_deref()
            .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
        {
            return Some(HttpResponse {
                status: 403,
                content_type: "text/plain; charset=utf-8".into(),
                body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
                www_authenticate: None,
                extra_headers: Vec::new(),
            });
        }
        return None;
    };
    let origin_host = origin
        .strip_prefix("http://")
        .or_else(|| origin.strip_prefix("https://"))
        .unwrap_or(origin)
        .split('/')
        .next()
        .unwrap_or("")
        .trim();
    let matches_host = req
        .host
        .as_deref()
        .map(str::trim)
        .filter(|h| !h.is_empty())
        .is_some_and(|h| origin_host.eq_ignore_ascii_case(h));
    if matches_host {
        None
    } else {
        Some(HttpResponse {
            status: 403,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        })
    }
}

/// Atomically reserve a concurrency slot and dispatch a worker thread (fail-closed on saturation
/// or OS thread exhaustion — never panics and never spawns above `ARKS_HTTP_MAX_CONCURRENCY`).
fn dispatch_accepted_stream(mut stream: TcpStream, git_dir: &Path, opts: &ServeHttpOptions) {
    let Some(guard) = try_reserve_http_slot() else {
        send_fast_503(&mut stream);
        return;
    };
    let dir = git_dir.to_path_buf();
    let opts = opts.clone();
    if let Err(e) = thread::Builder::new()
        .name("arks-http-worker".into())
        .spawn(move || {
            let _ = handle_connection(stream, &dir, &opts, guard);
        })
    {
        // Dropping the closure automatically drops `guard` (freeing the slot) and `stream`.
        eprintln!("arks serve-http: worker thread spawn failed ({e}); rejecting connection");
        thread::sleep(Duration::from_millis(10));
    }
}

/// Scheme label for listen banners (`http` or `https`).
pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
    if opts.tls.is_some() { "https" } else { "http" }
}

const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
const KEEP_ALIVE_IDLE_SECS: u64 = 5;

trait HttpStream: Read + Write {
    fn set_stream_read_timeout(&mut self, timeout: Duration);
    fn shutdown_write(&mut self);
}

impl HttpStream for TcpStream {
    fn set_stream_read_timeout(&mut self, timeout: Duration) {
        let _ = self.set_read_timeout(Some(timeout));
    }
    fn shutdown_write(&mut self) {
        let _ = self.shutdown(std::net::Shutdown::Write);
    }
}

impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
    fn set_stream_read_timeout(&mut self, timeout: Duration) {
        let _ = self.sock.set_read_timeout(Some(timeout));
    }
    fn shutdown_write(&mut self) {
        let _ = self.sock.shutdown(std::net::Shutdown::Write);
    }
}

fn handle_connection(
    mut stream: TcpStream,
    git_dir: &Path,
    opts: &ServeHttpOptions,
    _guard: ActiveConnGuard,
) -> Result<(), ServerError> {
    let _ = SERVER_START.get_or_init(Instant::now);
    // Listener is nonblocking; accepted sockets may inherit that on Windows.
    stream.set_nonblocking(false)?;
    let _ = stream.set_nodelay(true);
    stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
    stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
    let peer_ip = stream
        .peer_addr()
        .map(|a| a.ip())
        .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
    if let Some(tls_cfg) = &opts.tls {
        let conn = rustls::ServerConnection::new(tls_cfg.clone())
            .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
        let mut tls = rustls::StreamOwned::new(conn, stream);
        // Complete handshake before HTTP parse.
        tls.conn
            .complete_io(&mut tls.sock)
            .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
        handle_connection_io(&mut tls, peer_ip, git_dir, opts)
    } else {
        handle_connection_io(&mut stream, peer_ip, git_dir, opts)
    }
}

fn handle_connection_io<S: HttpStream>(
    stream: &mut S,
    peer_ip: std::net::IpAddr,
    git_dir: &Path,
    opts: &ServeHttpOptions,
) -> Result<(), ServerError> {
    let mut buf = Vec::with_capacity(4096);
    let mut tmp = [0u8; 8192];
    let header_timeout = opts.header_timeout.unwrap_or_else(max_http_header_timeout);
    for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
        let mut header_deadline = if req_idx == 0 {
            Some(Instant::now() + header_timeout)
        } else {
            stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
            None
        };
        let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
        // Read headers in O(N) by scanning only newly arrived bytes (plus 3-byte overlap),
        // bounded by a cumulative header deadline to defeat Slowloris dribbles.
        while header_end.is_none() {
            if let Some(dl) = header_deadline {
                let now = Instant::now();
                if now >= dl {
                    send_fast_408(stream);
                    return Ok(());
                }
                let rem = dl
                    .saturating_duration_since(now)
                    .max(Duration::from_millis(1));
                stream.set_stream_read_timeout(rem);
            }
            let prev_len = buf.len();
            match stream.read(&mut tmp) {
                Ok(0) => {
                    if req_idx > 0 && buf.is_empty() {
                        return Ok(());
                    }
                    break;
                }
                Ok(n) => {
                    if header_deadline.is_none() {
                        header_deadline = Some(Instant::now() + header_timeout);
                    }
                    buf.extend_from_slice(&tmp[..n]);
                    let search_from = prev_len.saturating_sub(3);
                    if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
                    {
                        header_end = Some(search_from + rel);
                        break;
                    }
                    if buf.len() > 1024 * 1024 {
                        return Err(ServerError::Protocol("headers too large".into()));
                    }
                    if header_deadline.is_some_and(|dl| Instant::now() >= dl) {
                        send_fast_408(stream);
                        return Ok(());
                    }
                }
                Err(e)
                    if req_idx > 0
                        && buf.is_empty()
                        && matches!(
                            e.kind(),
                            std::io::ErrorKind::WouldBlock
                                | std::io::ErrorKind::TimedOut
                                | std::io::ErrorKind::ConnectionReset
                                | std::io::ErrorKind::UnexpectedEof
                        ) =>
                {
                    return Ok(());
                }
                Err(e)
                    if header_deadline.is_some()
                        && matches!(
                            e.kind(),
                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                        ) =>
                {
                    send_fast_408(stream);
                    return Ok(());
                }
                Err(e) => return Err(e.into()),
            }
        }
        let Some(header_end) = header_end else {
            if req_idx > 0 && buf.is_empty() {
                return Ok(());
            }
            return Err(ServerError::Protocol("incomplete headers".into()));
        };
        // Restore full body-streaming read timeout once HTTP headers are complete.
        stream.set_stream_read_timeout(Duration::from_secs(30));
        HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
        let header_bytes = &buf[..header_end];
        let header_text = std::str::from_utf8(header_bytes)
            .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
        let mut lines = header_text.split("\r\n");
        let request_line = lines
            .next()
            .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
        let mut parts = request_line.split_whitespace();
        let method = parts
            .next()
            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
            .to_string();
        let target = parts
            .next()
            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
        let http_version = parts.next().unwrap_or("HTTP/1.1");
        let (path, query) = match target.split_once('?') {
            Some((p, q)) => (p.to_string(), q.to_string()),
            None => (target.to_string(), String::new()),
        };
        let mut content_length_opt: Option<usize> = None;
        let mut has_transfer_encoding = false;
        let mut header_smuggle_error: Option<&'static str> = None;
        let mut expect_continue = false;
        let mut content_encoding = String::new();
        let mut connection_close = false;
        let mut connection_keep_alive = false;
        let mut git_protocol = None;
        let mut authorization = None;
        let mut destination = None;
        let mut lock_token = None;
        let mut host = None;
        let mut cookie = None;
        let mut origin = None;
        let mut forwarded_proto = None;
        let mut sec_fetch_site = None;
        let mut headers: Vec<(String, String)> = Vec::new();
        for line in lines {
            if let Some((k, v)) = line.split_once(':') {
                let key = k.trim();
                if !key.is_empty() && headers.len() < 128 {
                    headers.push((key.to_ascii_lowercase(), v.trim().to_string()));
                }
            }
            let lower = line.to_ascii_lowercase();
            if let Some(v) = lower.strip_prefix("content-length:") {
                match v.trim().parse::<usize>() {
                    Ok(parsed) => {
                        if let Some(prev) = content_length_opt {
                            if prev != parsed {
                                header_smuggle_error = Some("conflicting Content-Length headers");
                            }
                        } else {
                            content_length_opt = Some(parsed);
                        }
                    }
                    Err(_) => {
                        header_smuggle_error = Some("invalid Content-Length header");
                    }
                }
            }
            if lower.starts_with("transfer-encoding:") {
                has_transfer_encoding = true;
            }
            if let Some(v) = lower.strip_prefix("connection:") {
                if v.contains("close") {
                    connection_close = true;
                }
                if v.contains("keep-alive") {
                    connection_keep_alive = true;
                }
            }
            if lower.starts_with("host:") {
                if let Some((_, v)) = line.split_once(':') {
                    host = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("cookie:") {
                if let Some((_, v)) = line.split_once(':') {
                    cookie = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("origin:") {
                if let Some((_, v)) = line.split_once(':') {
                    origin = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("x-forwarded-proto:") {
                if let Some((_, v)) = line.split_once(':') {
                    forwarded_proto = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("sec-fetch-site:") {
                if let Some((_, v)) = line.split_once(':') {
                    sec_fetch_site = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("expect:") && lower.contains("100-continue") {
                // git/curl POST often waits for 100 before sending the pack body
                // (gitprotocol-http / HTTP/1.1). Without this, clients see empty replies.
                expect_continue = true;
            }
            if let Some(v) = lower.strip_prefix("content-encoding:") {
                content_encoding = v.trim().to_string();
            }
            // gitprotocol-v2: clients send `Git-Protocol: version=2`.
            if lower.starts_with("git-protocol:") {
                if let Some((_, v)) = line.split_once(':') {
                    git_protocol = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("authorization:") {
                if let Some((_, v)) = line.split_once(':') {
                    authorization = Some(v.trim().to_string());
                }
            }
            // WebDAV (RFC 4918) — dumb HTTP push (git-http-push).
            if lower.starts_with("destination:") {
                if let Some((_, v)) = line.split_once(':') {
                    destination = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("lock-token:") {
                if let Some((_, v)) = line.split_once(':') {
                    lock_token = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("if:") && lock_token.is_none() {
                // git-http-push sends `If: (<opaquelocktoken:…>)` with the lock.
                if let Some((_, v)) = line.split_once(':') {
                    let v = v.trim();
                    if let Some(start) = v.find("opaquelocktoken:") {
                        let rest = &v[start..];
                        let end = rest
                            .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
                            .unwrap_or(rest.len());
                        lock_token = Some(rest[..end].to_string());
                    }
                }
            }
        }
        if header_smuggle_error.is_none() && has_transfer_encoding && content_length_opt.is_some() {
            header_smuggle_error = Some("ambiguous Transfer-Encoding and Content-Length headers");
        }
        if let Some(reason) = header_smuggle_error {
            let resp = HttpResponse {
                status: 400,
                content_type: "text/plain; charset=utf-8".into(),
                body: format!("Bad Request: {reason}\n").into_bytes(),
                www_authenticate: None,
                extra_headers: Vec::new(),
            };
            return write_http_response(stream, &resp);
        }
        let content_length = content_length_opt.unwrap_or(0);
        let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
            connection_keep_alive && !connection_close
        } else {
            !connection_close
        };
        let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
            Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
        } else {
            None
        };
        let body_start = header_end + 4;
        let is_head = method == "HEAD";
        if path == "/livez" {
            let resp = if method == "OPTIONS" {
                HttpResponse {
                    status: 204,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: Vec::new(),
                    www_authenticate: None,
                    extra_headers: vec![
                        ("Allow".into(), "GET, HEAD, OPTIONS".into()),
                        ("Cache-Control".into(), "no-store".into()),
                    ],
                }
            } else {
                HttpResponse {
                    status: 200,
                    content_type: "application/json; charset=utf-8".into(),
                    body: b"{\"status\":\"alive\"}\n".to_vec(),
                    www_authenticate: None,
                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                }
            };
            buf.drain(..body_start.min(buf.len()));
            write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
            if keep_alive_rem.is_some() {
                continue;
            }
            return Ok(());
        }
        if path == "/healthz" || path == "/readyz" {
            let resp = if method == "OPTIONS" {
                HttpResponse {
                    status: 204,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: Vec::new(),
                    www_authenticate: None,
                    extra_headers: vec![
                        ("Allow".into(), "GET, HEAD, OPTIONS".into()),
                        ("Cache-Control".into(), "no-store".into()),
                    ],
                }
            } else {
                match check_server_readiness(git_dir, opts) {
                    Ok(()) => HttpResponse {
                        status: 200,
                        content_type: "application/json; charset=utf-8".into(),
                        body: b"{\"status\":\"ok\"}\n".to_vec(),
                        www_authenticate: None,
                        extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                    },
                    Err(reason) => HttpResponse {
                        status: 503,
                        content_type: "application/json; charset=utf-8".into(),
                        body: format!("{{\"status\":\"not_ready\",\"reason\":\"{reason}\"}}\n")
                            .into_bytes(),
                        www_authenticate: None,
                        extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                    },
                }
            };
            buf.drain(..body_start.min(buf.len()));
            write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
            if keep_alive_rem.is_some() {
                continue;
            }
            return Ok(());
        }
        if path == "/metrics" {
            let resp = if !metrics_authorized(peer_ip, authorization.as_deref(), opts) {
                HttpResponse {
                    status: 404,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: b"not found\n".to_vec(),
                    www_authenticate: None,
                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                }
            } else if method == "OPTIONS" {
                HttpResponse {
                    status: 204,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: Vec::new(),
                    www_authenticate: None,
                    extra_headers: vec![
                        ("Allow".into(), "GET, HEAD, OPTIONS".into()),
                        ("Cache-Control".into(), "no-store".into()),
                    ],
                }
            } else {
                let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
                let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
                let upload = GIT_UPLOAD_PACK_TOTAL.load(Ordering::Relaxed);
                let receive = GIT_RECEIVE_PACK_TOTAL.load(Ordering::Relaxed);
                let lfs_bytes = LFS_BYTES_TOTAL.load(Ordering::Relaxed);
                let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
                let ver = env!("CARGO_PKG_VERSION");
                let metrics = format!(
                    "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
                     # TYPE arks_http_requests_total counter\n\
                     arks_http_requests_total {total}\n\
                     # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
                     # TYPE arks_http_active_connections gauge\n\
                     arks_http_active_connections {active}\n\
                     # HELP arks_uptime_seconds Server process uptime in seconds.\n\
                     # TYPE arks_uptime_seconds gauge\n\
                     arks_uptime_seconds {uptime}\n\
                     # HELP arks_git_upload_pack_total Total Git upload-pack RPC requests.\n\
                     # TYPE arks_git_upload_pack_total counter\n\
                     arks_git_upload_pack_total {upload}\n\
                     # HELP arks_git_receive_pack_total Total Git receive-pack RPC requests.\n\
                     # TYPE arks_git_receive_pack_total counter\n\
                     arks_git_receive_pack_total {receive}\n\
                     # HELP arks_lfs_bytes_total Total Git LFS bytes transferred.\n\
                     # TYPE arks_lfs_bytes_total counter\n\
                     arks_lfs_bytes_total {lfs_bytes}\n\
                     # HELP arks_build_info Build version information.\n\
                     # TYPE arks_build_info gauge\n\
                     arks_build_info{{version=\"{ver}\"}} 1\n"
                );
                HttpResponse {
                    status: 200,
                    content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
                    body: metrics.into_bytes(),
                    www_authenticate: None,
                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
                }
            };
            buf.drain(..body_start.min(buf.len()));
            write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
            if keep_alive_rem.is_some() {
                continue;
            }
            return Ok(());
        }
        let max_body = max_http_body_bytes();
        if content_length > max_body {
            let resp = HttpResponse {
                status: 413,
                content_type: "text/plain; charset=utf-8".into(),
                body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
                www_authenticate: None,
                extra_headers: Vec::new(),
            };
            return write_http_response(stream, &resp);
        }
        if expect_continue && content_length > 0 {
            if let Some(cfg) = &opts.basic_auth
                && !cfg.check_authorization(authorization.as_deref())
            {
                let resp = HttpResponse {
                    status: 401,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: b"unauthorized\n".to_vec(),
                    www_authenticate: Some(cfg.challenge_header()),
                    extra_headers: Vec::new(),
                };
                return write_http_response(stream, &resp);
            }
            stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
            stream.flush()?;
        }
        let total_needed = body_start.saturating_add(content_length);
        if !read_http_body_with_deadline(
            stream,
            &mut buf,
            &mut tmp,
            total_needed,
            max_http_body_timeout(),
        )? {
            send_fast_408_with_reason(stream, b"Request Timeout: HTTP body deadline exceeded\n");
            return Ok(());
        }
        let avail_end = total_needed.min(buf.len());
        let mut body = buf[body_start..avail_end].to_vec();
        buf.drain(..avail_end);
        // Stock git/curl may gzip the upload-pack / receive-pack POST once the prior
        // advertisement is large (observed ~32+ refs). Accept Content-Encoding: gzip
        // and gzip magic even if the header is omitted — except for raw binary LFS PUTs!
        let is_lfs = crate::lfs::is_lfs_path(&path);
        let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
        if content_encoding.contains("gzip") || gzip_magic {
            use flate2::read::GzDecoder;
            use std::io::Read as _;
            let decoder = GzDecoder::new(body.as_slice());
            let mut decoded = Vec::new();
            decoder
                .take((max_body as u64).saturating_add(1))
                .read_to_end(&mut decoded)
                .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
            if decoded.len() > max_body {
                let resp = HttpResponse {
                    status: 413,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: format!(
                        "Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
                    )
                    .into_bytes(),
                    www_authenticate: None,
                    extra_headers: Vec::new(),
                };
                return write_http_response(stream, &resp);
            }
            body = decoded;
        }

        let proxy_cfg = opts
            .trusted_proxies
            .clone()
            .unwrap_or_else(crate::proxy::TrustedProxyConfig::from_env);
        // Strip any client-supplied internal header before injecting resolved client IP.
        headers.retain(|(k, _)| !k.eq_ignore_ascii_case("x-arks-client-ip"));
        let resolved = crate::proxy::resolve_client(peer_ip, &headers, &proxy_cfg);
        headers.push(("x-arks-client-ip".into(), resolved.ip.to_string()));
        let effective_host = resolved.host.or(host);
        let effective_proto = resolved.proto.or_else(|| {
            if opts.tls.is_some() {
                Some("https".into())
            } else {
                None
            }
        });
        let _ = forwarded_proto;

        let mut req = HttpRequest {
            method,
            path: path.clone(),
            query: query.clone(),
            body,
            git_protocol,
            authorization,
            destination,
            lock_token,
            host: effective_host,
            cookie,
            origin,
            forwarded_proto: effective_proto,
            sec_fetch_site,
            headers,
        };
        // Enforce operator `--basic-auth` BEFORE `opts.pages` on BOTH single-repo and
        // multi-repo modes so Web UI, REST API, and Git RPC are uniformly gated
        // (`/healthz`, `/readyz`, `/metrics` were already served above).
        if req.path.contains("/git-upload-pack") {
            GIT_UPLOAD_PACK_TOTAL.fetch_add(1, Ordering::Relaxed);
        } else if req.path.contains("/git-receive-pack") {
            GIT_RECEIVE_PACK_TOTAL.fetch_add(1, Ordering::Relaxed);
        } else if is_lfs {
            LFS_BYTES_TOTAL.fetch_add(req.body.len() as u64, Ordering::Relaxed);
        }
        let resp = if let Some(gh) = &opts.github_app_webhook
            && req.path == gh.config.webhook_path
        {
            crate::github_app_webhook::handle_github_app_webhook(
                gh,
                &req.method,
                &req.headers,
                &req.body,
            )
        } else if let Some(cfg) = &opts.basic_auth
            && !cfg.check_authorization(req.authorization.as_deref())
        {
            HttpResponse {
                status: 401,
                content_type: "text/plain; charset=utf-8".into(),
                body: b"unauthorized\n".to_vec(),
                www_authenticate: Some(cfg.challenge_header()),
                extra_headers: Vec::new(),
            }
        } else if let Some(forbidden) = check_cross_origin_write(opts, &req) {
            forbidden
        } else if opts.multi_repo_root {
            match opts.pages.as_ref().and_then(|p| p(&req)) {
                Some(r) => r,
                None => HttpResponse {
                    status: 404,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: b"repository or path not found\n".to_vec(),
                    www_authenticate: None,
                    extra_headers: Vec::new(),
                },
            }
        } else {
            let mut repo =
                Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
            // dumb_only: strip service= so discovery uses dumb info/refs (smart clients fall back).
            if opts.dumb_only
                && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
            {
                req.query = String::new();
            }
            let is_git_rpc = req.path.contains("/git-upload-pack")
                || req.path.contains("/git-receive-pack")
                || req.path.contains("/info/refs");
            let page = match &opts.pages {
                Some(pages)
                    if matches!(
                        req.method.as_str(),
                        "GET" | "HEAD" | "OPTIONS" | "POST" | "PATCH" | "DELETE"
                    ) && !is_lfs
                        && !is_git_rpc =>
                {
                    pages(&req)
                }
                _ => None,
            };
            let scheme = if req.is_https() || opts.tls.is_some() {
                "https"
            } else {
                "http"
            };
            let is_dav_write = crate::dav::is_dav_method(&req.method)
                && !req.method.eq_ignore_ascii_case("PROPFIND");
            let is_git_write = req.path.contains("/git-receive-pack")
                || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
                || (req.path.contains("/info/lfs/") && req.method.eq_ignore_ascii_case("PUT"))
                || (req.path.contains("/info/lfs/locks")
                    && req.method.eq_ignore_ascii_case("POST"))
                || is_dav_write;
            let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
                crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
            } else {
                None
            };
            let lfs_lock_resp = if page.is_none()
                && auth_denied.is_none()
                && !opts.disable_lfs
                && req.path.contains("/info/lfs/locks")
            {
                let store = crate::web_ui::store::ForgeStore::load_shared(git_dir);
                let actor = crate::web_ui::auth_api::resolve_actor(&store, &req);
                let actor_ref = actor.as_ref().map(|(u, r)| (u.as_str(), r.as_str()));
                crate::lfs_locks::handle_lfs_locks(git_dir, &req, actor_ref)
            } else {
                None
            };
            match page
                .or(auth_denied)
                .or(lfs_lock_resp)
                .map(Ok)
                .unwrap_or_else(|| {
                    handle_smart_http_auth_opts(
                        &mut repo,
                        &req,
                        opts.basic_auth.as_ref(),
                        !opts.disable_lfs,
                        scheme,
                    )
                }) {
                Ok(r) => r,
                Err(e) => {
                    // Fail closed with an HTTP error body (never silent empty close).
                    // Never log raw request body bytes or hex dumps (`SEC-12`).
                    let msg = e.to_string();
                    eprintln!(
                        "arks serve-http error path={path} body_len={} : {msg}",
                        req.body.len()
                    );
                    HttpResponse {
                        status: 500,
                        content_type: "text/plain".into(),
                        body: msg.into_bytes(),
                        www_authenticate: None,
                        extra_headers: Vec::new(),
                    }
                }
            }
        };
        let mut resp = resp;
        let trace = crate::ops::RequestTrace::from_request(&req);
        trace.attach_headers(&mut resp);
        if !is_head {
            maybe_gzip_response(&mut resp, &req);
        }
        crate::ops::maybe_emit_json_access_log(&trace, &req, resp.status, 0);
        let keep_alive = if matches!(resp.status, 408 | 413 | 503) {
            None
        } else {
            keep_alive_rem
        };
        write_http_response_full(stream, &resp, req.is_https(), keep_alive, is_head)?;
        if keep_alive.is_none() {
            return Ok(());
        }
    }
    Ok(())
}

fn is_compressible_content_type(ct: &str) -> bool {
    let mime = ct
        .split(';')
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase();
    mime.starts_with("text/")
        || mime == "application/json"
        || mime == "application/problem+json"
        || mime == "application/javascript"
        || mime == "application/manifest+json"
        || mime == "application/linkset+json"
        || mime == "application/atom+xml"
        || mime == "image/svg+xml"
}

fn maybe_gzip_response(resp: &mut HttpResponse, req: &HttpRequest) {
    if resp.body.len() < 1024
        || matches!(resp.status, 204 | 304)
        || crate::web::core::headers::is_git_wire_path(&req.path)
        || crate::dav::is_dav_method(&req.method)
        || !is_compressible_content_type(&resp.content_type)
    {
        return;
    }
    let accepts_gzip = req
        .header("accept-encoding")
        .is_some_and(|ae| ae.to_ascii_lowercase().contains("gzip"));
    if !accepts_gzip {
        return;
    }
    if resp
        .extra_headers
        .iter()
        .any(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
    {
        return;
    }
    let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
    if enc.write_all(&resp.body).is_ok()
        && let Ok(compressed) = enc.finish()
        && compressed.len() < resp.body.len()
    {
        resp.body = compressed;
        resp.extra_headers
            .push(("Content-Encoding".into(), "gzip".into()));
        if let Some((_, v)) = resp
            .extra_headers
            .iter_mut()
            .find(|(k, _)| k.eq_ignore_ascii_case("vary"))
        {
            if !v.to_ascii_lowercase().contains("accept-encoding") {
                v.push_str(", Accept-Encoding");
            }
        } else {
            resp.extra_headers
                .push(("Vary".into(), "Accept-Encoding".into()));
        }
    }
}

fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
    write_http_response_full(stream, resp, false, None, false)
}

#[cfg(test)]
fn write_http_response_with_options<S: Write>(
    stream: &mut S,
    resp: &HttpResponse,
    is_https: bool,
    keep_alive_remaining: Option<usize>,
) -> Result<(), ServerError> {
    write_http_response_full(stream, resp, is_https, keep_alive_remaining, false)
}

fn write_http_response_full<S: Write>(
    stream: &mut S,
    resp: &HttpResponse,
    is_https: bool,
    keep_alive_remaining: Option<usize>,
    is_head: bool,
) -> Result<(), ServerError> {
    let status_text = match resp.status {
        200 => "OK",
        201 => "Created",
        204 => "No Content",
        207 => "Multi-Status",
        302 => "Found",
        303 => "See Other",
        304 => "Not Modified",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        408 => "Request Timeout",
        409 => "Conflict",
        412 => "Precondition Failed",
        413 => "Payload Too Large",
        415 => "Unsupported Media Type",
        422 => "Unprocessable Entity",
        423 => "Locked",
        428 => "Precondition Required",
        429 => "Too Many Requests",
        500 => "Internal Server Error",
        501 => "Not Implemented",
        503 => "Service Unavailable",
        507 => "Insufficient Storage",
        _ => "Error",
    };
    let conn_header = match keep_alive_remaining {
        Some(rem) => format!(
            "Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
        ),
        None => "Connection: close\r\n".to_string(),
    };
    let mut header = format!(
        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
        resp.status,
        status_text,
        resp.content_type,
        resp.body.len(),
        conn_header
    );
    if let Some(ref wa) = resp.www_authenticate {
        header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
    }
    let mut has_csp = false;
    let mut has_pp = false;
    let mut has_coop = false;
    let mut has_corp = false;
    let mut has_xcto = false;
    let mut has_xfo = false;
    let mut has_rp = false;
    let mut has_hsts = false;
    let is_html = resp.content_type.starts_with("text/html");
    for (k, v) in &resp.extra_headers {
        if k.eq_ignore_ascii_case("content-security-policy") {
            has_csp = true;
            if is_html && is_https && !v.contains("upgrade-insecure-requests") {
                header.push_str(&format!("{k}: {v}; upgrade-insecure-requests\r\n"));
                continue;
            }
        } else if k.eq_ignore_ascii_case("permissions-policy") {
            has_pp = true;
        } else if k.eq_ignore_ascii_case("cross-origin-opener-policy") {
            has_coop = true;
        } else if k.eq_ignore_ascii_case("cross-origin-resource-policy") {
            has_corp = true;
        } else if k.eq_ignore_ascii_case("x-content-type-options") {
            has_xcto = true;
        } else if k.eq_ignore_ascii_case("x-frame-options") {
            has_xfo = true;
        } else if k.eq_ignore_ascii_case("referrer-policy") {
            has_rp = true;
        } else if k.eq_ignore_ascii_case("strict-transport-security") {
            has_hsts = true;
        }
        header.push_str(&format!("{k}: {v}\r\n"));
    }
    if is_html {
        if !has_csp {
            let csp = if is_https {
                crate::web::core::headers::WEB_UI_CSP_HTTPS
            } else {
                crate::web::core::headers::WEB_UI_CSP
            };
            header.push_str(&format!("Content-Security-Policy: {csp}\r\n"));
        }
        if !has_pp {
            header.push_str(&format!(
                "Permissions-Policy: {}\r\n",
                crate::web::core::headers::PERMISSIONS_POLICY
            ));
        }
        if !has_coop {
            header.push_str(&format!(
                "Cross-Origin-Opener-Policy: {}\r\n",
                crate::web::core::headers::COOP
            ));
        }
        if !has_corp {
            header.push_str(&format!(
                "Cross-Origin-Resource-Policy: {}\r\n",
                crate::web::core::headers::CORP
            ));
        }
        if !has_xcto {
            header.push_str(&format!(
                "X-Content-Type-Options: {}\r\n",
                crate::web::core::headers::X_CONTENT_TYPE_OPTIONS
            ));
        }
        if !has_xfo {
            header.push_str(&format!(
                "X-Frame-Options: {}\r\n",
                crate::web::core::headers::X_FRAME_OPTIONS
            ));
        }
        if !has_rp {
            header.push_str(&format!(
                "Referrer-Policy: {}\r\n",
                crate::web::core::headers::REFERRER_POLICY
            ));
        }
    }
    if is_https && !has_hsts {
        header.push_str(&format!(
            "Strict-Transport-Security: {}\r\n",
            crate::web::core::headers::HSTS
        ));
    }
    header.push_str("\r\n");
    if is_head || resp.status == 204 || resp.status == 304 {
        stream.write_all(header.as_bytes())?;
    } else if resp.body.len() <= 64 * 1024 {
        let mut combined = Vec::with_capacity(header.len() + resp.body.len());
        combined.extend_from_slice(header.as_bytes());
        combined.extend_from_slice(&resp.body);
        stream.write_all(&combined)?;
    } else {
        stream.write_all(header.as_bytes())?;
        stream.write_all(&resp.body)?;
    }
    stream.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::basic_authorization_header;
    use sha2::{Digest, Sha256};
    use tempfile::TempDir;

    fn raw_http_exchange(addr: SocketAddr, request: &str) -> String {
        let mut sock = TcpStream::connect(addr).unwrap();
        sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
        sock.write_all(request.as_bytes()).unwrap();
        let mut out = Vec::new();
        let _ = sock.read_to_end(&mut out);
        String::from_utf8_lossy(&out).into_owned()
    }

    fn seed_empty_bare(dir: &Path) {
        std::fs::create_dir_all(dir.join("objects")).unwrap();
        std::fs::create_dir_all(dir.join("refs/heads")).unwrap();
        std::fs::write(dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
    }

    #[test]
    fn basic_auth_gates_pages_on_single_and_multi_repo_while_exempting_health_and_metrics() {
        let dir = TempDir::new().unwrap();
        seed_empty_bare(dir.path());
        let auth_hdr = basic_authorization_header("alice", "s3cret");

        for multi_repo_root in [false, true] {
            let page_hits = Arc::new(AtomicUsize::new(0));
            let hits_cb = Arc::clone(&page_hits);
            let pages: PageHandler = Arc::new(move |req: &HttpRequest| {
                hits_cb.fetch_add(1, Ordering::SeqCst);
                Some(HttpResponse {
                    status: 200,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: format!("page:{}\n", req.path).into_bytes(),
                    www_authenticate: None,
                    extra_headers: Vec::new(),
                })
            });
            let opts = ServeHttpOptions {
                basic_auth: Some(BasicAuthConfig::single("alice", "s3cret")),
                pages: Some(pages),
                multi_repo_root,
                ..ServeHttpOptions::default()
            };
            let (addr, stop, handle) =
                spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();

            // Unauthenticated Web UI and REST API routes MUST return 401 before invoking pages.
            for path in ["/", "/api/v1/issues"] {
                let req =
                    format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
                let resp = raw_http_exchange(addr, &req);
                assert!(
                    resp.starts_with("HTTP/1.1 401 Unauthorized"),
                    "multi_repo={multi_repo_root} path={path} must require Basic Auth: {resp}"
                );
                assert!(resp.contains("WWW-Authenticate: Basic realm=\"arks\""));
            }
            assert_eq!(
                page_hits.load(Ordering::SeqCst),
                0,
                "pages handler must never run before Basic Auth succeeds (multi_repo={multi_repo_root})"
            );

            // Health and metrics endpoints remain exempt.
            for exempt in ["/healthz", "/readyz", "/metrics"] {
                let req =
                    format!("GET {exempt} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
                let resp = raw_http_exchange(addr, &req);
                assert!(
                    resp.starts_with("HTTP/1.1 200 OK"),
                    "exempt endpoint {exempt} must succeed without auth: {resp}"
                );
            }

            // Authenticated request reaches pages cleanly.
            let authed_req = format!(
                "GET / HTTP/1.1\r\nHost: {addr}\r\nAuthorization: {auth_hdr}\r\nConnection: close\r\n\r\n"
            );
            let authed_resp = raw_http_exchange(addr, &authed_req);
            assert!(
                authed_resp.starts_with("HTTP/1.1 200 OK") && authed_resp.contains("page:/"),
                "authenticated request must reach pages: {authed_resp}"
            );
            assert_eq!(page_hits.load(Ordering::SeqCst), 1);

            stop.store(true, Ordering::SeqCst);
            handle.join().unwrap().unwrap();
        }
    }

    #[test]
    fn cross_origin_write_rejected_when_pages_enabled() {
        let dir = TempDir::new().unwrap();
        seed_empty_bare(dir.path());
        let pages: PageHandler = Arc::new(|_req: &HttpRequest| None);
        let opts = ServeHttpOptions {
            pages: Some(pages.clone()),
            ..ServeHttpOptions::default()
        };

        // Unit-level checks across all mutating Git / LFS / WebDAV verbs.
        for (method, path) in [
            ("POST", "/git-receive-pack"),
            ("POST", "/demo.git/git-receive-pack"),
            ("PUT", "/info/lfs/objects/deadbeef"),
            ("PUT", "/refs/heads/main"),
            ("MOVE", "/objects/ab/cdef"),
            ("DELETE", "/refs/heads/topic"),
            ("LOCK", "/refs/heads/main"),
            ("UNLOCK", "/refs/heads/main"),
        ] {
            let mut cross = HttpRequest::new(method, path, "", Vec::new());
            cross.host = Some("127.0.0.1:8080".into());
            cross.origin = Some("https://evil.example".into());
            let resp = check_cross_origin_write(&opts, &cross)
                .expect("cross-origin mutating write must be rejected");
            assert_eq!(resp.status, 403, "{method} {path} must return 403");
            assert!(
                String::from_utf8_lossy(&resp.body).contains("cross-origin write rejected"),
                "{}",
                String::from_utf8_lossy(&resp.body)
            );

            let mut same = cross.clone();
            same.origin = Some("http://127.0.0.1:8080".into());
            assert!(
                check_cross_origin_write(&opts, &same).is_none(),
                "same-origin {method} {path} must be allowed"
            );

            let mut no_origin = cross.clone();
            no_origin.origin = None;
            assert!(
                check_cross_origin_write(&opts, &no_origin).is_none(),
                "missing Origin without Sec-Fetch-Site on {method} {path} must be allowed"
            );

            let mut cross_fetch_site = no_origin.clone();
            cross_fetch_site.sec_fetch_site = Some("cross-site".into());
            let resp = check_cross_origin_write(&opts, &cross_fetch_site)
                .expect("Sec-Fetch-Site: cross-site without Origin must be rejected");
            assert_eq!(resp.status, 403, "{method} {path} must return 403");

            let mut same_fetch_site = no_origin;
            same_fetch_site.sec_fetch_site = Some("same-origin".into());
            assert!(
                check_cross_origin_write(&opts, &same_fetch_site).is_none(),
                "Sec-Fetch-Site: same-origin without Origin on {method} {path} must be allowed"
            );
        }

        // Live loopback enforcement when pages is enabled.
        let (addr, stop, handle) =
            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
        let req = format!(
            "POST /git-receive-pack HTTP/1.1\r\nHost: {addr}\r\nOrigin: https://evil.example\r\nContent-Length: 4\r\nConnection: close\r\n\r\n0000"
        );
        let resp = raw_http_exchange(addr, &req);
        assert!(
            resp.starts_with("HTTP/1.1 403 Forbidden")
                && resp.contains("cross-origin write rejected"),
            "live loopback must reject cross-origin receive-pack with 403: {resp}"
        );
        stop.store(true, Ordering::SeqCst);
        handle.join().unwrap().unwrap();
    }

    #[test]
    fn webdav_writes_require_forge_auth_and_lfs_honors_forwarded_proto_https() {
        let dir = TempDir::new().unwrap();
        seed_empty_bare(dir.path());

        let reader_pat = "arks_pat_reader_test_token";
        let reader_hash = {
            let digest = Sha256::digest(reader_pat.as_bytes());
            let mut s = String::with_capacity(64);
            for b in digest {
                s.push_str(&format!("{b:02x}"));
            }
            s
        };

        let mut store = crate::web_ui::store::ForgeStore::load(dir.path());
        store.users.push(crate::web_ui::store::UserAccount {
            username: "reader1".into(),
            password_hash: "x".into(),
            role: "reader".into(),
            ssh_keys: Vec::new(),
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        store.pats.push(crate::web_ui::store::PatRecord {
            id: 1,
            username: "reader1".into(),
            name: "read".into(),
            token_hash: reader_hash,
            prefix: "arks_pat_r".into(),
            created_at: 1,
            scopes: Vec::new(),
            expires_at: None,
            last_used_at: None,
        });
        store.save(dir.path()).unwrap();

        let (addr, stop, handle) =
            spawn_loopback_with_opts(dir.path().to_path_buf(), ServeHttpOptions::default())
                .unwrap();

        // Unauthenticated mutating WebDAV verbs must receive 401 when ForgeStore has users.
        for (method, path) in [
            ("PUT", "/refs/heads/main"),
            ("MKCOL", "/objects/ab"),
            ("LOCK", "/refs/heads/main"),
            ("DELETE", "/refs/heads/main"),
        ] {
            let req = format!(
                "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
            );
            let resp = raw_http_exchange(addr, &req);
            assert!(
                resp.starts_with("HTTP/1.1 401 Unauthorized"),
                "unauthenticated WebDAV {method} {path} must return 401: {resp}"
            );
        }

        // Reader PAT must receive 403 Forbidden on mutating WebDAV writes.
        let reader_put = format!(
            "PUT /refs/heads/main HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {reader_pat}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
        );
        let reader_resp = raw_http_exchange(addr, &reader_put);
        assert!(
            reader_resp.starts_with("HTTP/1.1 403 Forbidden"),
            "reader role must be denied WebDAV PUT with 403: {reader_resp}"
        );

        // PROPFIND remains read-only discovery on public repos (207 Multi-Status).
        let propfind = format!(
            "PROPFIND / HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
        );
        let prop_resp = raw_http_exchange(addr, &propfind);
        assert!(
            prop_resp.starts_with("HTTP/1.1 207 Multi-Status"),
            "PROPFIND discovery on public repo must return 207: {prop_resp}"
        );

        // Reverse-proxy `X-Forwarded-Proto: https` must produce `https://` LFS batch hrefs.
        let batch_body = format!(
            r#"{{"operation":"upload","objects":[{{"oid":"{}","size":4}}]}}"#,
            "a".repeat(64)
        );
        let lfs_req = format!(
            "POST /info/lfs/objects/batch HTTP/1.1\r\nHost: proxy.example.invalid\r\nX-Forwarded-Proto: https\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            batch_body.len(),
            batch_body
        );
        let lfs_resp = raw_http_exchange(addr, &lfs_req);
        assert!(
            lfs_resp.starts_with("HTTP/1.1 200 OK")
                && lfs_resp.contains("https://proxy.example.invalid/info/lfs/objects/"),
            "LFS batch must honor X-Forwarded-Proto: https: {lfs_resp}"
        );

        stop.store(true, Ordering::SeqCst);
        handle.join().unwrap().unwrap();
    }

    #[test]
    fn slow_post_body_dribble_hits_cumulative_deadline() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let client = thread::spawn(move || {
            let mut sock = TcpStream::connect(addr).unwrap();
            for _ in 0..8 {
                if sock.write_all(b"x").is_err() {
                    break;
                }
                thread::sleep(Duration::from_millis(60));
            }
        });

        let (mut srv, _) = listener.accept().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 64];
        let completed = read_http_body_with_deadline(
            &mut srv,
            &mut buf,
            &mut tmp,
            1024,
            Duration::from_millis(200),
        )
        .unwrap();
        assert!(
            !completed,
            "Slow-POST dribble must time out against cumulative body deadline"
        );
        drop(srv);
        client.join().unwrap();
    }

    #[test]
    fn html_security_headers_applied_to_html_and_excluded_from_git_wire() {
        let html_resp = HttpResponse {
            status: 200,
            content_type: "text/html; charset=utf-8".into(),
            body: b"<h1>ok</h1>".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
        let mut wire_http = Vec::new();
        write_http_response_with_options(&mut wire_http, &html_resp, false, None).unwrap();
        let http_str = String::from_utf8(wire_http).unwrap();
        assert!(http_str.contains("Content-Security-Policy: default-src 'self'"));
        assert!(http_str.contains("frame-ancestors 'none'"));
        assert!(http_str.contains("Permissions-Policy: camera=()"));
        assert!(http_str.contains("Cross-Origin-Opener-Policy: same-origin"));
        assert!(http_str.contains("Cross-Origin-Resource-Policy: same-origin"));
        assert!(http_str.contains("X-Content-Type-Options: nosniff"));
        assert!(http_str.contains("X-Frame-Options: DENY"));
        assert!(http_str.contains("Referrer-Policy: strict-origin-when-cross-origin"));
        assert!(!http_str.contains("upgrade-insecure-requests"));

        let mut wire_https = Vec::new();
        write_http_response_with_options(&mut wire_https, &html_resp, true, None).unwrap();
        let https_str = String::from_utf8(wire_https).unwrap();
        assert!(https_str.contains("upgrade-insecure-requests"));
        assert!(https_str.contains("Strict-Transport-Security:"));

        let git_resp = HttpResponse {
            status: 200,
            content_type: "application/x-git-upload-pack-advertisement".into(),
            body: b"001e# service=git-upload-pack\n0000".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
        let mut wire_git = Vec::new();
        write_http_response_with_options(&mut wire_git, &git_resp, false, None).unwrap();
        let git_str = String::from_utf8(wire_git).unwrap();
        assert!(!git_str.contains("Content-Security-Policy:"));
        assert!(!git_str.contains("Permissions-Policy:"));
        assert!(!git_str.contains("Cross-Origin-Opener-Policy:"));
        assert!(!git_str.contains("X-Frame-Options:"));
    }

    #[test]
    fn head_and_options_semantics_follow_rfc9110() {
        let resp = HttpResponse {
            status: 200,
            content_type: "text/html; charset=utf-8".into(),
            body: b"<h1>hello</h1>".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
        let mut head_wire = Vec::new();
        write_http_response_full(&mut head_wire, &resp, false, None, true).unwrap();
        let head_str = String::from_utf8(head_wire).unwrap();
        assert!(head_str.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(head_str.contains("Content-Length: 14\r\n"));
        assert!(
            head_str.ends_with("\r\n\r\n"),
            "HEAD wire response must carry empty body: {head_str}"
        );

        let dir = TempDir::new().unwrap();
        seed_empty_bare(dir.path());
        let repo_dir = dir.path().to_path_buf();
        let pages: PageHandler =
            Arc::new(move |req: &HttpRequest| crate::web_ui::handle_web_ui(&repo_dir, req));
        let opts = ServeHttpOptions {
            pages: Some(pages),
            ..ServeHttpOptions::default()
        };
        let (addr, stop, handle) =
            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();

        let head_health = raw_http_exchange(
            addr,
            "HEAD /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(head_health.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(head_health.ends_with("\r\n\r\n"));

        let opt_health = raw_http_exchange(
            addr,
            "OPTIONS /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(opt_health.starts_with("HTTP/1.1 204 No Content\r\n"));
        assert!(opt_health.contains("Allow: GET, HEAD, OPTIONS\r\n"));

        let head_root = raw_http_exchange(
            addr,
            "HEAD / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(head_root.starts_with("HTTP/1.1 200 OK\r\n"), "{head_root}");
        assert!(head_root.ends_with("\r\n\r\n"));

        let opt_root = raw_http_exchange(
            addr,
            "OPTIONS / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(
            opt_root.starts_with("HTTP/1.1 204 No Content\r\n"),
            "{opt_root}"
        );
        assert!(
            opt_root.contains("Allow: GET, HEAD, OPTIONS\r\n"),
            "{opt_root}"
        );

        stop.store(true, Ordering::SeqCst);
        handle.join().unwrap().unwrap();
    }

    #[test]
    fn livez_readyz_and_gated_metrics_follow_o2() {
        let dir = TempDir::new().unwrap();
        seed_empty_bare(dir.path());
        let shutdown_flag = Arc::new(AtomicBool::new(false));
        let opts = ServeHttpOptions {
            shutdown_flag: Some(shutdown_flag.clone()),
            metrics_token: Some("secret-metrics-tok".into()),
            metrics_require_token: true,
            ..ServeHttpOptions::default()
        };
        let (addr, stop, handle) =
            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();

        let live = raw_http_exchange(
            addr,
            "GET /livez HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(live.starts_with("HTTP/1.1 200 OK\r\n"), "{live}");
        assert!(live.contains("\"alive\""));

        let ready_ok = raw_http_exchange(
            addr,
            "GET /readyz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(ready_ok.starts_with("HTTP/1.1 200 OK\r\n"), "{ready_ok}");

        // Metrics without token -> 404 when gated.
        let met_denied = raw_http_exchange(
            addr,
            "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(
            met_denied.starts_with("HTTP/1.1 404 Not Found\r\n"),
            "{met_denied}"
        );

        // Metrics with valid Bearer token -> 200 with full Prometheus series.
        let met_ok = raw_http_exchange(
            addr,
            "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer secret-metrics-tok\r\nConnection: close\r\n\r\n",
        );
        assert!(met_ok.starts_with("HTTP/1.1 200 OK\r\n"), "{met_ok}");
        assert!(met_ok.contains("arks_git_upload_pack_total"));
        assert!(met_ok.contains("arks_git_receive_pack_total"));
        assert!(met_ok.contains("arks_lfs_bytes_total"));
        assert!(met_ok.contains("arks_build_info{version="));

        // Flipping shutdown_flag makes /readyz return 503 while /livez stays 200.
        shutdown_flag.store(true, Ordering::SeqCst);
        let ready_down = raw_http_exchange(
            addr,
            "GET /readyz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(
            ready_down.starts_with("HTTP/1.1 503 Service Unavailable\r\n"),
            "{ready_down}"
        );
        assert!(ready_down.contains("shutting_down"));

        let live_still = raw_http_exchange(
            addr,
            "GET /livez HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
        );
        assert!(live_still.starts_with("HTTP/1.1 200 OK\r\n"));

        stop.store(true, Ordering::SeqCst);
        handle.join().unwrap().unwrap();
    }

    #[test]
    fn gzip_compression_applies_to_html_and_excludes_git_wire() {
        let html_body = "<div>".to_string() + &"hello arks ".repeat(300) + "</div>";
        let mut html_resp = HttpResponse {
            status: 200,
            content_type: "text/html; charset=utf-8".into(),
            body: html_body.as_bytes().to_vec(),
            www_authenticate: None,
            extra_headers: vec![("Vary".into(), "HX-Request, Cookie".into())],
        };
        let req = HttpRequest::new("GET", "/issues", "", Vec::new())
            .with_header("Accept-Encoding", "gzip, deflate");
        maybe_gzip_response(&mut html_resp, &req);
        assert!(
            html_resp
                .extra_headers
                .contains(&("Content-Encoding".into(), "gzip".into()))
        );
        assert!(html_resp.body.len() < html_body.len());
        let mut dec = flate2::read::GzDecoder::new(html_resp.body.as_slice());
        let mut roundtrip = String::new();
        dec.read_to_string(&mut roundtrip).unwrap();
        assert_eq!(roundtrip, html_body);

        // Git wire path must NEVER be gzipped.
        let mut git_resp = HttpResponse {
            status: 200,
            content_type: "text/plain".into(),
            body: vec![b'a'; 4096],
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
        let git_req = HttpRequest::new("GET", "/repo.git/info/refs", "", Vec::new())
            .with_header("Accept-Encoding", "gzip");
        maybe_gzip_response(&mut git_resp, &git_req);
        assert!(
            !git_resp
                .extra_headers
                .iter()
                .any(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
        );
    }
}