Skip to main content

arks_server/
serve.rs

1//! Loopback smart-HTTP listener for clean-room / local serve.
2//!
3//! Optional in-process TLS terminate via operator-supplied PEMs
4//! ([[sot:root/arks-claimed-residual-gates]] B9). Dual-bind drain on rebind
5//! supports B7 Claimed evidence when harnessed.
6
7use crate::auth::BasicAuthConfig;
8use crate::error::ServerError;
9use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
10use arks_repo::Repository;
11use rustls::ServerConfig;
12use std::io::{Read, Write};
13use std::net::{SocketAddr, TcpListener, TcpStream};
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex, OnceLock};
17use std::thread;
18use std::time::{Duration, Instant};
19
20static HTTP_REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
21static HTTP_ACTIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
22static SERVER_START: OnceLock<Instant> = OnceLock::new();
23
24fn max_http_body_bytes() -> usize {
25    std::env::var("ARKS_HTTP_MAX_BODY_BYTES")
26        .ok()
27        .and_then(|v| v.trim().parse::<usize>().ok())
28        .filter(|&n| n > 0)
29        .unwrap_or(64 * 1024 * 1024)
30}
31
32fn max_http_concurrency() -> usize {
33    std::env::var("ARKS_HTTP_MAX_CONCURRENCY")
34        .ok()
35        .and_then(|v| v.trim().parse::<usize>().ok())
36        .filter(|&n| n > 0)
37        .unwrap_or(128)
38}
39
40fn max_http_header_timeout() -> Duration {
41    let secs = std::env::var("ARKS_HTTP_HEADER_TIMEOUT_SECS")
42        .ok()
43        .and_then(|v| v.trim().parse::<u64>().ok())
44        .filter(|&n| n > 0)
45        .unwrap_or(10);
46    Duration::from_secs(secs)
47}
48
49fn max_http_body_timeout() -> Duration {
50    let secs = std::env::var("ARKS_HTTP_BODY_TIMEOUT_SECS")
51        .ok()
52        .and_then(|v| v.trim().parse::<u64>().ok())
53        .filter(|&n| n > 0)
54        .unwrap_or(60);
55    Duration::from_secs(secs)
56}
57
58/// Returns true for transient `accept()` errors (FD exhaustion `EMFILE`/`ENFILE`,
59/// aborted handshake, or interrupt) where the listener must back off rather than exit.
60pub(crate) fn is_transient_accept_error(err: &std::io::Error) -> bool {
61    if matches!(
62        err.kind(),
63        std::io::ErrorKind::WouldBlock
64            | std::io::ErrorKind::Interrupted
65            | std::io::ErrorKind::ConnectionAborted
66            | std::io::ErrorKind::ConnectionReset
67    ) {
68        return true;
69    }
70    #[cfg(unix)]
71    {
72        // ENOMEM (12), ENFILE (23), EMFILE (24), macOS ENOBUFS (55), Linux ENOBUFS (105).
73        if matches!(err.raw_os_error(), Some(12 | 23 | 24 | 55 | 105)) {
74            return true;
75        }
76    }
77    #[cfg(windows)]
78    {
79        // WSAEMFILE (10024), WSAECONNRESET (10054), WSAENOBUFS (10055).
80        if matches!(err.raw_os_error(), Some(10024 | 10054 | 10055)) {
81            return true;
82        }
83    }
84    false
85}
86
87pub(crate) struct ActiveConnGuard;
88impl Drop for ActiveConnGuard {
89    fn drop(&mut self) {
90        HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Release);
91    }
92}
93
94/// Atomically reserve an HTTP concurrency slot up to `limit` before spawning a worker thread.
95pub(crate) fn try_reserve_http_slot_with_limit(limit: usize) -> Option<ActiveConnGuard> {
96    let mut cur = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire);
97    loop {
98        if cur >= limit {
99            return None;
100        }
101        match HTTP_ACTIVE_CONNECTIONS.compare_exchange_weak(
102            cur,
103            cur + 1,
104            Ordering::AcqRel,
105            Ordering::Acquire,
106        ) {
107            Ok(_) => return Some(ActiveConnGuard),
108            Err(observed) => cur = observed,
109        }
110    }
111}
112
113/// Atomically reserve an HTTP concurrency slot before spawning a worker thread.
114fn try_reserve_http_slot() -> Option<ActiveConnGuard> {
115    try_reserve_http_slot_with_limit(max_http_concurrency())
116}
117
118/// Returns the number of currently active in-flight HTTP requests (for graceful drain).
119#[allow(dead_code)]
120pub fn active_http_connections() -> usize {
121    HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire)
122}
123
124type LoopbackHttp = (
125    SocketAddr,
126    Arc<AtomicBool>,
127    thread::JoinHandle<Result<(), ServerError>>,
128);
129
130/// Shared slot: when set to `Some(addr)`, the HTTP accept loop performs a
131/// bounded dual-bind rebind. B7 is Claimed for the evidenced HTTP scenario;
132/// SSH/forge rebind and OpenSSH-class interop are separate gates.
133pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
134
135/// Optional page handler consulted for `GET` requests before git HTTP; it
136/// answers `Some(response)` for the paths it owns and `None` for the rest
137/// (used by `instaweb` for its repository browser pages).
138pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
139
140#[derive(Clone, Default)]
141pub struct ServeHttpOptions {
142    /// When true, answer `info/refs` (even with `service=`) as dumb text/plain so
143    /// smart clients fall back to dumb HTTP (gitprotocol-http). Used by G29.
144    pub dumb_only: bool,
145    /// Optional in-process HTTP Basic (G36). Unset = unauthenticated (G15).
146    pub basic_auth: Option<BasicAuthConfig>,
147    /// Optional live listen rebind target (Partial; polled in accept loop).
148    pub rebind_desired: Option<ListenRebindSlot>,
149    /// Optional rustls server config for in-process TLS terminate (B9).
150    pub tls: Option<Arc<ServerConfig>>,
151    /// Optional browser pages served beside git HTTP.
152    pub pages: Option<PageHandler>,
153    /// When true, disable the built-in `/info/lfs` Batch + Basic Transfer server (`--no-lfs`).
154    pub disable_lfs: bool,
155    /// When true, `git_dir` is a multi-repository root directory and `pages` handles all routes
156    /// (Web UI + `/<repo>.git/...` Smart HTTP/LFS) without opening a single repo at `git_dir`.
157    pub multi_repo_root: bool,
158    /// Optional cumulative HTTP header-read deadline override (falls back to
159    /// `ARKS_HTTP_HEADER_TIMEOUT_SECS`, default 10s).
160    pub header_timeout: Option<Duration>,
161}
162
163impl std::fmt::Debug for ServeHttpOptions {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.debug_struct("ServeHttpOptions")
166            .field("dumb_only", &self.dumb_only)
167            .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
168            .field("rebind_desired", &self.rebind_desired.is_some())
169            .field("tls", &self.tls.is_some())
170            .field("pages", &self.pages.is_some())
171            .field("disable_lfs", &self.disable_lfs)
172            .field("multi_repo_root", &self.multi_repo_root)
173            .field("header_timeout", &self.header_timeout)
174            .finish()
175    }
176}
177
178/// Bind `addr` and serve `git_dir` over smart HTTP until `stop` is set or accept fails.
179pub fn serve_http(
180    git_dir: impl AsRef<Path>,
181    addr: SocketAddr,
182    stop: Arc<AtomicBool>,
183) -> Result<(), ServerError> {
184    serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
185}
186
187pub fn serve_http_with_opts(
188    git_dir: impl AsRef<Path>,
189    addr: SocketAddr,
190    stop: Arc<AtomicBool>,
191    opts: ServeHttpOptions,
192) -> Result<(), ServerError> {
193    let git_dir = git_dir.as_ref().to_path_buf();
194    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
195    let mut listener = TcpListener::bind(addr)?;
196    listener.set_nonblocking(true)?;
197    let mut current = addr;
198    // A successful rebind keeps prior listeners accepting for this bounded
199    // overlap. Accepted handlers are independently owned and always drain.
200    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
201    let mut last_accept_err_log: Option<Instant> = None;
202    while !stop.load(Ordering::SeqCst) {
203        if let Some(slot) = &opts.rebind_desired {
204            if let Ok(mut g) = slot.lock() {
205                if let Some(new_addr) = g.take() {
206                    if new_addr != current {
207                        match TcpListener::bind(new_addr) {
208                            Ok(l) => {
209                                if let Err(e) = l.set_nonblocking(true) {
210                                    eprintln!(
211                                        "arks serve-http: live rebind Partial bind ok but \
212                                         nonblocking fail ({e}); keeping {current}"
213                                    );
214                                    *g = Some(new_addr);
215                                } else {
216                                    eprintln!(
217                                        "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
218                                         prior listener draining for 5s"
219                                    );
220                                    let old = std::mem::replace(&mut listener, l);
221                                    draining.push((
222                                        old,
223                                        current,
224                                        Instant::now() + Duration::from_secs(5),
225                                    ));
226                                    current = new_addr;
227                                }
228                            }
229                            Err(e) => {
230                                eprintln!(
231                                    "arks serve-http: live rebind Partial fail {current} → \
232                                     {new_addr} ({e}); keeping prior listen"
233                                );
234                            }
235                        }
236                    }
237                }
238            }
239        }
240        draining.retain(|(_, old_addr, deadline)| {
241            if Instant::now() < *deadline {
242                true
243            } else {
244                eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
245                false
246            }
247        });
248        match listener.accept() {
249            Ok((stream, _)) => {
250                dispatch_accepted_stream(stream, &git_dir, &opts);
251            }
252            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
253                thread::sleep(std::time::Duration::from_millis(1));
254            }
255            Err(e) if is_transient_accept_error(&e) => {
256                if last_accept_err_log
257                    .map(|t| t.elapsed() >= Duration::from_secs(1))
258                    .unwrap_or(true)
259                {
260                    eprintln!(
261                        "arks serve-http: transient accept error on {current} ({e}); backing off"
262                    );
263                    last_accept_err_log = Some(Instant::now());
264                }
265                thread::sleep(std::time::Duration::from_millis(25));
266            }
267            Err(e) => return Err(e.into()),
268        }
269        for (old_listener, _, _) in &draining {
270            match old_listener.accept() {
271                Ok((stream, _)) => {
272                    dispatch_accepted_stream(stream, &git_dir, &opts);
273                }
274                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
275                Err(e) => {
276                    if last_accept_err_log
277                        .map(|t| t.elapsed() >= Duration::from_secs(1))
278                        .unwrap_or(true)
279                    {
280                        eprintln!("arks serve-http: draining listener accept error: {e}");
281                        last_accept_err_log = Some(Instant::now());
282                    }
283                }
284            }
285        }
286    }
287    // Graceful shutdown: wait for in-flight HTTP/Git requests to finish (up to 10s).
288    let drain_secs = std::env::var("ARKS_SHUTDOWN_DRAIN_SECS")
289        .ok()
290        .and_then(|v| v.trim().parse::<u64>().ok())
291        .unwrap_or(10);
292    let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
293    while active_http_connections() > 0 && Instant::now() < drain_deadline {
294        thread::sleep(Duration::from_millis(25));
295    }
296    Ok(())
297}
298
299/// Bind an ephemeral port; return (bound addr, join handle, stop flag).
300pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
301    spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
302}
303
304pub fn spawn_loopback_with_opts(
305    git_dir: PathBuf,
306    opts: ServeHttpOptions,
307) -> Result<LoopbackHttp, ServerError> {
308    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
309    let listener = TcpListener::bind("127.0.0.1:0")?;
310    let addr = listener.local_addr()?;
311    listener.set_nonblocking(true)?;
312    let stop = Arc::new(AtomicBool::new(false));
313    let stop2 = stop.clone();
314    let handle = thread::spawn(move || {
315        let mut last_accept_err_log: Option<Instant> = None;
316        while !stop2.load(Ordering::SeqCst) {
317            match listener.accept() {
318                Ok((stream, _)) => {
319                    dispatch_accepted_stream(stream, &git_dir, &opts);
320                }
321                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
322                    thread::sleep(std::time::Duration::from_millis(1));
323                }
324                Err(e) if is_transient_accept_error(&e) => {
325                    if last_accept_err_log
326                        .map(|t| t.elapsed() >= Duration::from_secs(1))
327                        .unwrap_or(true)
328                    {
329                        eprintln!(
330                            "arks serve-http: transient loopback accept error ({e}); backing off"
331                        );
332                        last_accept_err_log = Some(Instant::now());
333                    }
334                    thread::sleep(std::time::Duration::from_millis(25));
335                }
336                Err(e) => return Err(e.into()),
337            }
338        }
339        Ok(())
340    });
341    Ok((addr, stop, handle))
342}
343
344fn send_fast_503(stream: &mut TcpStream) {
345    let _ = stream.set_nonblocking(false);
346    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
347    let resp = HttpResponse {
348        status: 503,
349        content_type: "text/plain; charset=utf-8".into(),
350        body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
351        www_authenticate: None,
352        extra_headers: vec![("Retry-After".into(), "1".into())],
353    };
354    let _ = write_http_response(stream, &resp);
355    let _ = stream.shutdown(std::net::Shutdown::Write);
356}
357
358fn send_fast_408_with_reason<S: HttpStream>(stream: &mut S, reason: &'static [u8]) {
359    let resp = HttpResponse {
360        status: 408,
361        content_type: "text/plain; charset=utf-8".into(),
362        body: reason.to_vec(),
363        www_authenticate: None,
364        extra_headers: Vec::new(),
365    };
366    let _ = write_http_response(stream, &resp);
367    stream.shutdown_write();
368}
369
370fn send_fast_408<S: HttpStream>(stream: &mut S) {
371    send_fast_408_with_reason(stream, b"Request Timeout: HTTP header deadline exceeded\n");
372}
373
374/// Read HTTP body bytes until `buf.len() >= total_needed` under a cumulative `body_timeout`
375/// deadline so Slow-POST dribbles cannot hold worker threads indefinitely (`SEC-11`).
376/// Returns `Ok(true)` when body reading finished (or peer closed), or `Ok(false)` on timeout.
377fn read_http_body_with_deadline<S: HttpStream>(
378    stream: &mut S,
379    buf: &mut Vec<u8>,
380    tmp: &mut [u8],
381    total_needed: usize,
382    body_timeout: Duration,
383) -> Result<bool, ServerError> {
384    if buf.len() >= total_needed {
385        return Ok(true);
386    }
387    let body_deadline = Instant::now() + body_timeout;
388    while buf.len() < total_needed {
389        let now = Instant::now();
390        if now >= body_deadline {
391            return Ok(false);
392        }
393        let rem = body_deadline
394            .saturating_duration_since(now)
395            .max(Duration::from_millis(1));
396        stream.set_stream_read_timeout(rem);
397        match stream.read(tmp) {
398            Ok(0) => break,
399            Ok(n) => {
400                buf.extend_from_slice(&tmp[..n]);
401                if buf.len() < total_needed && Instant::now() >= body_deadline {
402                    return Ok(false);
403                }
404            }
405            Err(e)
406                if matches!(
407                    e.kind(),
408                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
409                ) =>
410            {
411                return Ok(false);
412            }
413            Err(e) => return Err(e.into()),
414        }
415    }
416    Ok(true)
417}
418
419fn is_mutating_git_lfs_dav_request(req: &HttpRequest) -> bool {
420    let method = req.method.to_ascii_uppercase();
421    let is_receive_pack =
422        req.path.ends_with("/git-receive-pack") || req.path.contains("/git-receive-pack");
423    if is_receive_pack && !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS") {
424        return true;
425    }
426    if crate::lfs::is_lfs_path(&req.path) && method == "PUT" {
427        return true;
428    }
429    matches!(
430        method.as_str(),
431        "PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
432    )
433}
434
435/// Reject cross-origin mutating Git/LFS/WebDAV writes when browser pages are co-hosted (`INT-S03`).
436pub(crate) fn check_cross_origin_write(
437    opts: &ServeHttpOptions,
438    req: &HttpRequest,
439) -> Option<HttpResponse> {
440    if opts.pages.is_none() || !is_mutating_git_lfs_dav_request(req) {
441        return None;
442    }
443    let Some(origin) = req
444        .origin
445        .as_deref()
446        .map(str::trim)
447        .filter(|o| !o.is_empty())
448    else {
449        if req
450            .sec_fetch_site
451            .as_deref()
452            .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
453        {
454            return Some(HttpResponse {
455                status: 403,
456                content_type: "text/plain; charset=utf-8".into(),
457                body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
458                www_authenticate: None,
459                extra_headers: Vec::new(),
460            });
461        }
462        return None;
463    };
464    let origin_host = origin
465        .strip_prefix("http://")
466        .or_else(|| origin.strip_prefix("https://"))
467        .unwrap_or(origin)
468        .split('/')
469        .next()
470        .unwrap_or("")
471        .trim();
472    let matches_host = req
473        .host
474        .as_deref()
475        .map(str::trim)
476        .filter(|h| !h.is_empty())
477        .is_some_and(|h| origin_host.eq_ignore_ascii_case(h));
478    if matches_host {
479        None
480    } else {
481        Some(HttpResponse {
482            status: 403,
483            content_type: "text/plain; charset=utf-8".into(),
484            body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
485            www_authenticate: None,
486            extra_headers: Vec::new(),
487        })
488    }
489}
490
491/// Atomically reserve a concurrency slot and dispatch a worker thread (fail-closed on saturation
492/// or OS thread exhaustion — never panics and never spawns above `ARKS_HTTP_MAX_CONCURRENCY`).
493fn dispatch_accepted_stream(mut stream: TcpStream, git_dir: &Path, opts: &ServeHttpOptions) {
494    let Some(guard) = try_reserve_http_slot() else {
495        send_fast_503(&mut stream);
496        return;
497    };
498    let dir = git_dir.to_path_buf();
499    let opts = opts.clone();
500    if let Err(e) = thread::Builder::new()
501        .name("arks-http-worker".into())
502        .spawn(move || {
503            let _ = handle_connection(stream, &dir, &opts, guard);
504        })
505    {
506        // Dropping the closure automatically drops `guard` (freeing the slot) and `stream`.
507        eprintln!("arks serve-http: worker thread spawn failed ({e}); rejecting connection");
508        thread::sleep(Duration::from_millis(10));
509    }
510}
511
512/// Scheme label for listen banners (`http` or `https`).
513pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
514    if opts.tls.is_some() { "https" } else { "http" }
515}
516
517const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
518const KEEP_ALIVE_IDLE_SECS: u64 = 5;
519
520trait HttpStream: Read + Write {
521    fn set_stream_read_timeout(&mut self, timeout: Duration);
522    fn shutdown_write(&mut self);
523}
524
525impl HttpStream for TcpStream {
526    fn set_stream_read_timeout(&mut self, timeout: Duration) {
527        let _ = self.set_read_timeout(Some(timeout));
528    }
529    fn shutdown_write(&mut self) {
530        let _ = self.shutdown(std::net::Shutdown::Write);
531    }
532}
533
534impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
535    fn set_stream_read_timeout(&mut self, timeout: Duration) {
536        let _ = self.sock.set_read_timeout(Some(timeout));
537    }
538    fn shutdown_write(&mut self) {
539        let _ = self.sock.shutdown(std::net::Shutdown::Write);
540    }
541}
542
543fn handle_connection(
544    mut stream: TcpStream,
545    git_dir: &Path,
546    opts: &ServeHttpOptions,
547    _guard: ActiveConnGuard,
548) -> Result<(), ServerError> {
549    let _ = SERVER_START.get_or_init(Instant::now);
550    // Listener is nonblocking; accepted sockets may inherit that on Windows.
551    stream.set_nonblocking(false)?;
552    let _ = stream.set_nodelay(true);
553    stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
554    stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
555    if let Some(tls_cfg) = &opts.tls {
556        let conn = rustls::ServerConnection::new(tls_cfg.clone())
557            .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
558        let mut tls = rustls::StreamOwned::new(conn, stream);
559        // Complete handshake before HTTP parse.
560        tls.conn
561            .complete_io(&mut tls.sock)
562            .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
563        handle_connection_io(&mut tls, git_dir, opts)
564    } else {
565        handle_connection_io(&mut stream, git_dir, opts)
566    }
567}
568
569fn handle_connection_io<S: HttpStream>(
570    stream: &mut S,
571    git_dir: &Path,
572    opts: &ServeHttpOptions,
573) -> Result<(), ServerError> {
574    let mut buf = Vec::with_capacity(4096);
575    let mut tmp = [0u8; 8192];
576    let header_timeout = opts.header_timeout.unwrap_or_else(max_http_header_timeout);
577    for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
578        let mut header_deadline = if req_idx == 0 {
579            Some(Instant::now() + header_timeout)
580        } else {
581            stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
582            None
583        };
584        let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
585        // Read headers in O(N) by scanning only newly arrived bytes (plus 3-byte overlap),
586        // bounded by a cumulative header deadline to defeat Slowloris dribbles.
587        while header_end.is_none() {
588            if let Some(dl) = header_deadline {
589                let now = Instant::now();
590                if now >= dl {
591                    send_fast_408(stream);
592                    return Ok(());
593                }
594                let rem = dl
595                    .saturating_duration_since(now)
596                    .max(Duration::from_millis(1));
597                stream.set_stream_read_timeout(rem);
598            }
599            let prev_len = buf.len();
600            match stream.read(&mut tmp) {
601                Ok(0) => {
602                    if req_idx > 0 && buf.is_empty() {
603                        return Ok(());
604                    }
605                    break;
606                }
607                Ok(n) => {
608                    if header_deadline.is_none() {
609                        header_deadline = Some(Instant::now() + header_timeout);
610                    }
611                    buf.extend_from_slice(&tmp[..n]);
612                    let search_from = prev_len.saturating_sub(3);
613                    if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
614                    {
615                        header_end = Some(search_from + rel);
616                        break;
617                    }
618                    if buf.len() > 1024 * 1024 {
619                        return Err(ServerError::Protocol("headers too large".into()));
620                    }
621                    if header_deadline.is_some_and(|dl| Instant::now() >= dl) {
622                        send_fast_408(stream);
623                        return Ok(());
624                    }
625                }
626                Err(e)
627                    if req_idx > 0
628                        && buf.is_empty()
629                        && matches!(
630                            e.kind(),
631                            std::io::ErrorKind::WouldBlock
632                                | std::io::ErrorKind::TimedOut
633                                | std::io::ErrorKind::ConnectionReset
634                                | std::io::ErrorKind::UnexpectedEof
635                        ) =>
636                {
637                    return Ok(());
638                }
639                Err(e)
640                    if header_deadline.is_some()
641                        && matches!(
642                            e.kind(),
643                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
644                        ) =>
645                {
646                    send_fast_408(stream);
647                    return Ok(());
648                }
649                Err(e) => return Err(e.into()),
650            }
651        }
652        let Some(header_end) = header_end else {
653            if req_idx > 0 && buf.is_empty() {
654                return Ok(());
655            }
656            return Err(ServerError::Protocol("incomplete headers".into()));
657        };
658        // Restore full body-streaming read timeout once HTTP headers are complete.
659        stream.set_stream_read_timeout(Duration::from_secs(30));
660        HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
661        let header_bytes = &buf[..header_end];
662        let header_text = std::str::from_utf8(header_bytes)
663            .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
664        let mut lines = header_text.split("\r\n");
665        let request_line = lines
666            .next()
667            .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
668        let mut parts = request_line.split_whitespace();
669        let method = parts
670            .next()
671            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
672            .to_string();
673        let target = parts
674            .next()
675            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
676        let http_version = parts.next().unwrap_or("HTTP/1.1");
677        let (path, query) = match target.split_once('?') {
678            Some((p, q)) => (p.to_string(), q.to_string()),
679            None => (target.to_string(), String::new()),
680        };
681        let mut content_length_opt: Option<usize> = None;
682        let mut has_transfer_encoding = false;
683        let mut header_smuggle_error: Option<&'static str> = None;
684        let mut expect_continue = false;
685        let mut content_encoding = String::new();
686        let mut connection_close = false;
687        let mut connection_keep_alive = false;
688        let mut git_protocol = None;
689        let mut authorization = None;
690        let mut destination = None;
691        let mut lock_token = None;
692        let mut host = None;
693        let mut cookie = None;
694        let mut origin = None;
695        let mut forwarded_proto = None;
696        let mut sec_fetch_site = None;
697        for line in lines {
698            let lower = line.to_ascii_lowercase();
699            if let Some(v) = lower.strip_prefix("content-length:") {
700                match v.trim().parse::<usize>() {
701                    Ok(parsed) => {
702                        if let Some(prev) = content_length_opt {
703                            if prev != parsed {
704                                header_smuggle_error = Some("conflicting Content-Length headers");
705                            }
706                        } else {
707                            content_length_opt = Some(parsed);
708                        }
709                    }
710                    Err(_) => {
711                        header_smuggle_error = Some("invalid Content-Length header");
712                    }
713                }
714            }
715            if lower.starts_with("transfer-encoding:") {
716                has_transfer_encoding = true;
717            }
718            if let Some(v) = lower.strip_prefix("connection:") {
719                if v.contains("close") {
720                    connection_close = true;
721                }
722                if v.contains("keep-alive") {
723                    connection_keep_alive = true;
724                }
725            }
726            if lower.starts_with("host:") {
727                if let Some((_, v)) = line.split_once(':') {
728                    host = Some(v.trim().to_string());
729                }
730            }
731            if lower.starts_with("cookie:") {
732                if let Some((_, v)) = line.split_once(':') {
733                    cookie = Some(v.trim().to_string());
734                }
735            }
736            if lower.starts_with("origin:") {
737                if let Some((_, v)) = line.split_once(':') {
738                    origin = Some(v.trim().to_string());
739                }
740            }
741            if lower.starts_with("x-forwarded-proto:") {
742                if let Some((_, v)) = line.split_once(':') {
743                    forwarded_proto = Some(v.trim().to_string());
744                }
745            }
746            if lower.starts_with("sec-fetch-site:") {
747                if let Some((_, v)) = line.split_once(':') {
748                    sec_fetch_site = Some(v.trim().to_string());
749                }
750            }
751            if lower.starts_with("expect:") && lower.contains("100-continue") {
752                // git/curl POST often waits for 100 before sending the pack body
753                // (gitprotocol-http / HTTP/1.1). Without this, clients see empty replies.
754                expect_continue = true;
755            }
756            if let Some(v) = lower.strip_prefix("content-encoding:") {
757                content_encoding = v.trim().to_string();
758            }
759            // gitprotocol-v2: clients send `Git-Protocol: version=2`.
760            if lower.starts_with("git-protocol:") {
761                if let Some((_, v)) = line.split_once(':') {
762                    git_protocol = Some(v.trim().to_string());
763                }
764            }
765            if lower.starts_with("authorization:") {
766                if let Some((_, v)) = line.split_once(':') {
767                    authorization = Some(v.trim().to_string());
768                }
769            }
770            // WebDAV (RFC 4918) — dumb HTTP push (git-http-push).
771            if lower.starts_with("destination:") {
772                if let Some((_, v)) = line.split_once(':') {
773                    destination = Some(v.trim().to_string());
774                }
775            }
776            if lower.starts_with("lock-token:") {
777                if let Some((_, v)) = line.split_once(':') {
778                    lock_token = Some(v.trim().to_string());
779                }
780            }
781            if lower.starts_with("if:") && lock_token.is_none() {
782                // git-http-push sends `If: (<opaquelocktoken:…>)` with the lock.
783                if let Some((_, v)) = line.split_once(':') {
784                    let v = v.trim();
785                    if let Some(start) = v.find("opaquelocktoken:") {
786                        let rest = &v[start..];
787                        let end = rest
788                            .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
789                            .unwrap_or(rest.len());
790                        lock_token = Some(rest[..end].to_string());
791                    }
792                }
793            }
794        }
795        if header_smuggle_error.is_none() && has_transfer_encoding && content_length_opt.is_some() {
796            header_smuggle_error = Some("ambiguous Transfer-Encoding and Content-Length headers");
797        }
798        if let Some(reason) = header_smuggle_error {
799            let resp = HttpResponse {
800                status: 400,
801                content_type: "text/plain; charset=utf-8".into(),
802                body: format!("Bad Request: {reason}\n").into_bytes(),
803                www_authenticate: None,
804                extra_headers: Vec::new(),
805            };
806            return write_http_response(stream, &resp);
807        }
808        let content_length = content_length_opt.unwrap_or(0);
809        let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
810            connection_keep_alive && !connection_close
811        } else {
812            !connection_close
813        };
814        let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
815            Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
816        } else {
817            None
818        };
819        let body_start = header_end + 4;
820        if path == "/healthz" || path == "/readyz" {
821            let body = b"{\"status\":\"ok\"}\n";
822            let resp = HttpResponse {
823                status: 200,
824                content_type: "application/json; charset=utf-8".into(),
825                body: body.to_vec(),
826                www_authenticate: None,
827                extra_headers: vec![("Cache-Control".into(), "no-store".into())],
828            };
829            buf.drain(..body_start.min(buf.len()));
830            write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
831            if keep_alive_rem.is_some() {
832                continue;
833            }
834            return Ok(());
835        }
836        if path == "/metrics" {
837            let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
838            let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
839            let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
840            let metrics = format!(
841                "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
842                 # TYPE arks_http_requests_total counter\n\
843                 arks_http_requests_total {total}\n\
844                 # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
845                 # TYPE arks_http_active_connections gauge\n\
846                 arks_http_active_connections {active}\n\
847                 # HELP arks_uptime_seconds Server process uptime in seconds.\n\
848                 # TYPE arks_uptime_seconds gauge\n\
849                 arks_uptime_seconds {uptime}\n"
850            );
851            let resp = HttpResponse {
852                status: 200,
853                content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
854                body: metrics.into_bytes(),
855                www_authenticate: None,
856                extra_headers: vec![("Cache-Control".into(), "no-store".into())],
857            };
858            buf.drain(..body_start.min(buf.len()));
859            write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
860            if keep_alive_rem.is_some() {
861                continue;
862            }
863            return Ok(());
864        }
865        let max_body = max_http_body_bytes();
866        if content_length > max_body {
867            let resp = HttpResponse {
868                status: 413,
869                content_type: "text/plain; charset=utf-8".into(),
870                body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
871                www_authenticate: None,
872                extra_headers: Vec::new(),
873            };
874            return write_http_response(stream, &resp);
875        }
876        if expect_continue && content_length > 0 {
877            if let Some(cfg) = &opts.basic_auth
878                && !cfg.check_authorization(authorization.as_deref())
879            {
880                let resp = HttpResponse {
881                    status: 401,
882                    content_type: "text/plain; charset=utf-8".into(),
883                    body: b"unauthorized\n".to_vec(),
884                    www_authenticate: Some(cfg.challenge_header()),
885                    extra_headers: Vec::new(),
886                };
887                return write_http_response(stream, &resp);
888            }
889            stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
890            stream.flush()?;
891        }
892        let total_needed = body_start.saturating_add(content_length);
893        if !read_http_body_with_deadline(
894            stream,
895            &mut buf,
896            &mut tmp,
897            total_needed,
898            max_http_body_timeout(),
899        )? {
900            send_fast_408_with_reason(stream, b"Request Timeout: HTTP body deadline exceeded\n");
901            return Ok(());
902        }
903        let avail_end = total_needed.min(buf.len());
904        let mut body = buf[body_start..avail_end].to_vec();
905        buf.drain(..avail_end);
906        // Stock git/curl may gzip the upload-pack / receive-pack POST once the prior
907        // advertisement is large (observed ~32+ refs). Accept Content-Encoding: gzip
908        // and gzip magic even if the header is omitted — except for raw binary LFS PUTs!
909        let is_lfs = crate::lfs::is_lfs_path(&path);
910        let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
911        if content_encoding.contains("gzip") || gzip_magic {
912            use flate2::read::GzDecoder;
913            use std::io::Read as _;
914            let decoder = GzDecoder::new(body.as_slice());
915            let mut decoded = Vec::new();
916            decoder
917                .take((max_body as u64).saturating_add(1))
918                .read_to_end(&mut decoded)
919                .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
920            if decoded.len() > max_body {
921                let resp = HttpResponse {
922                    status: 413,
923                    content_type: "text/plain; charset=utf-8".into(),
924                    body: format!(
925                        "Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
926                    )
927                    .into_bytes(),
928                    www_authenticate: None,
929                    extra_headers: Vec::new(),
930                };
931                return write_http_response(stream, &resp);
932            }
933            body = decoded;
934        }
935
936        let mut req = HttpRequest {
937            method,
938            path: path.clone(),
939            query: query.clone(),
940            body,
941            git_protocol,
942            authorization,
943            destination,
944            lock_token,
945            host,
946            cookie,
947            origin,
948            forwarded_proto: forwarded_proto.or_else(|| {
949                if opts.tls.is_some() {
950                    Some("https".into())
951                } else {
952                    None
953                }
954            }),
955            sec_fetch_site,
956        };
957        // Enforce operator `--basic-auth` BEFORE `opts.pages` on BOTH single-repo and
958        // multi-repo modes so Web UI, REST API, and Git RPC are uniformly gated
959        // (`/healthz`, `/readyz`, `/metrics` were already served above).
960        let resp = if let Some(cfg) = &opts.basic_auth
961            && !cfg.check_authorization(req.authorization.as_deref())
962        {
963            HttpResponse {
964                status: 401,
965                content_type: "text/plain; charset=utf-8".into(),
966                body: b"unauthorized\n".to_vec(),
967                www_authenticate: Some(cfg.challenge_header()),
968                extra_headers: Vec::new(),
969            }
970        } else if let Some(forbidden) = check_cross_origin_write(opts, &req) {
971            forbidden
972        } else if opts.multi_repo_root {
973            match opts.pages.as_ref().and_then(|p| p(&req)) {
974                Some(r) => r,
975                None => HttpResponse {
976                    status: 404,
977                    content_type: "text/plain; charset=utf-8".into(),
978                    body: b"repository or path not found\n".to_vec(),
979                    www_authenticate: None,
980                    extra_headers: Vec::new(),
981                },
982            }
983        } else {
984            let mut repo =
985                Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
986            // dumb_only: strip service= so discovery uses dumb info/refs (smart clients fall back).
987            if opts.dumb_only
988                && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
989            {
990                req.query = String::new();
991            }
992            let is_git_rpc = req.path.contains("/git-upload-pack")
993                || req.path.contains("/git-receive-pack")
994                || req.path.contains("/info/refs");
995            let page = match &opts.pages {
996                Some(pages)
997                    if matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE")
998                        && !is_lfs
999                        && !is_git_rpc =>
1000                {
1001                    pages(&req)
1002                }
1003                _ => None,
1004            };
1005            let scheme = if req.is_https() || opts.tls.is_some() {
1006                "https"
1007            } else {
1008                "http"
1009            };
1010            let is_dav_write = crate::dav::is_dav_method(&req.method)
1011                && !req.method.eq_ignore_ascii_case("PROPFIND");
1012            let is_git_write = req.path.contains("/git-receive-pack")
1013                || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
1014                || (req.path.contains("/info/lfs/") && req.method.eq_ignore_ascii_case("PUT"))
1015                || is_dav_write;
1016            let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
1017                crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
1018            } else {
1019                None
1020            };
1021            match page.or(auth_denied).map(Ok).unwrap_or_else(|| {
1022                handle_smart_http_auth_opts(
1023                    &mut repo,
1024                    &req,
1025                    opts.basic_auth.as_ref(),
1026                    !opts.disable_lfs,
1027                    scheme,
1028                )
1029            }) {
1030                Ok(r) => r,
1031                Err(e) => {
1032                    // Fail closed with an HTTP error body (never silent empty close).
1033                    // Never log raw request body bytes or hex dumps (`SEC-12`).
1034                    let msg = e.to_string();
1035                    eprintln!(
1036                        "arks serve-http error path={path} body_len={} : {msg}",
1037                        req.body.len()
1038                    );
1039                    HttpResponse {
1040                        status: 500,
1041                        content_type: "text/plain".into(),
1042                        body: msg.into_bytes(),
1043                        www_authenticate: None,
1044                        extra_headers: Vec::new(),
1045                    }
1046                }
1047            }
1048        };
1049        let keep_alive = if matches!(resp.status, 408 | 413 | 503) {
1050            None
1051        } else {
1052            keep_alive_rem
1053        };
1054        write_http_response_with_options(stream, &resp, req.is_https(), keep_alive)?;
1055        if keep_alive.is_none() {
1056            return Ok(());
1057        }
1058    }
1059    Ok(())
1060}
1061
1062fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
1063    write_http_response_with_options(stream, resp, false, None)
1064}
1065
1066fn write_http_response_with_options<S: Write>(
1067    stream: &mut S,
1068    resp: &HttpResponse,
1069    is_https: bool,
1070    keep_alive_remaining: Option<usize>,
1071) -> Result<(), ServerError> {
1072    let status_text = match resp.status {
1073        200 => "OK",
1074        201 => "Created",
1075        204 => "No Content",
1076        207 => "Multi-Status",
1077        302 => "Found",
1078        303 => "See Other",
1079        400 => "Bad Request",
1080        401 => "Unauthorized",
1081        403 => "Forbidden",
1082        404 => "Not Found",
1083        405 => "Method Not Allowed",
1084        408 => "Request Timeout",
1085        409 => "Conflict",
1086        412 => "Precondition Failed",
1087        413 => "Payload Too Large",
1088        422 => "Unprocessable Entity",
1089        423 => "Locked",
1090        429 => "Too Many Requests",
1091        500 => "Internal Server Error",
1092        501 => "Not Implemented",
1093        503 => "Service Unavailable",
1094        _ => "Error",
1095    };
1096    let conn_header = match keep_alive_remaining {
1097        Some(rem) => format!(
1098            "Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
1099        ),
1100        None => "Connection: close\r\n".to_string(),
1101    };
1102    let mut header = format!(
1103        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
1104        resp.status,
1105        status_text,
1106        resp.content_type,
1107        resp.body.len(),
1108        conn_header
1109    );
1110    if let Some(ref wa) = resp.www_authenticate {
1111        header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
1112    }
1113    let mut has_xfo = false;
1114    let mut has_rp = false;
1115    let mut has_hsts = false;
1116    for (k, v) in &resp.extra_headers {
1117        if k.eq_ignore_ascii_case("x-frame-options") {
1118            has_xfo = true;
1119        } else if k.eq_ignore_ascii_case("referrer-policy") {
1120            has_rp = true;
1121        } else if k.eq_ignore_ascii_case("strict-transport-security") {
1122            has_hsts = true;
1123        }
1124        header.push_str(&format!("{k}: {v}\r\n"));
1125    }
1126    if resp.content_type.starts_with("text/html") {
1127        if !has_xfo {
1128            header.push_str("X-Frame-Options: DENY\r\n");
1129        }
1130        if !has_rp {
1131            header.push_str("Referrer-Policy: same-origin\r\n");
1132        }
1133    }
1134    if is_https && !has_hsts {
1135        header.push_str("Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n");
1136    }
1137    header.push_str("\r\n");
1138    if resp.body.len() <= 64 * 1024 {
1139        let mut combined = Vec::with_capacity(header.len() + resp.body.len());
1140        combined.extend_from_slice(header.as_bytes());
1141        combined.extend_from_slice(&resp.body);
1142        stream.write_all(&combined)?;
1143    } else {
1144        stream.write_all(header.as_bytes())?;
1145        stream.write_all(&resp.body)?;
1146    }
1147    stream.flush()?;
1148    Ok(())
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153    use super::*;
1154    use crate::auth::basic_authorization_header;
1155    use sha2::{Digest, Sha256};
1156    use tempfile::TempDir;
1157
1158    fn raw_http_exchange(addr: SocketAddr, request: &str) -> String {
1159        let mut sock = TcpStream::connect(addr).unwrap();
1160        sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
1161        sock.write_all(request.as_bytes()).unwrap();
1162        let mut out = Vec::new();
1163        let _ = sock.read_to_end(&mut out);
1164        String::from_utf8_lossy(&out).into_owned()
1165    }
1166
1167    fn seed_empty_bare(dir: &Path) {
1168        std::fs::create_dir_all(dir.join("objects")).unwrap();
1169        std::fs::create_dir_all(dir.join("refs/heads")).unwrap();
1170        std::fs::write(dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
1171    }
1172
1173    #[test]
1174    fn basic_auth_gates_pages_on_single_and_multi_repo_while_exempting_health_and_metrics() {
1175        let dir = TempDir::new().unwrap();
1176        seed_empty_bare(dir.path());
1177        let auth_hdr = basic_authorization_header("alice", "s3cret");
1178
1179        for multi_repo_root in [false, true] {
1180            let page_hits = Arc::new(AtomicUsize::new(0));
1181            let hits_cb = Arc::clone(&page_hits);
1182            let pages: PageHandler = Arc::new(move |req: &HttpRequest| {
1183                hits_cb.fetch_add(1, Ordering::SeqCst);
1184                Some(HttpResponse {
1185                    status: 200,
1186                    content_type: "text/plain; charset=utf-8".into(),
1187                    body: format!("page:{}\n", req.path).into_bytes(),
1188                    www_authenticate: None,
1189                    extra_headers: Vec::new(),
1190                })
1191            });
1192            let opts = ServeHttpOptions {
1193                basic_auth: Some(BasicAuthConfig::single("alice", "s3cret")),
1194                pages: Some(pages),
1195                multi_repo_root,
1196                ..ServeHttpOptions::default()
1197            };
1198            let (addr, stop, handle) =
1199                spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
1200
1201            // Unauthenticated Web UI and REST API routes MUST return 401 before invoking pages.
1202            for path in ["/", "/api/v1/issues"] {
1203                let req =
1204                    format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
1205                let resp = raw_http_exchange(addr, &req);
1206                assert!(
1207                    resp.starts_with("HTTP/1.1 401 Unauthorized"),
1208                    "multi_repo={multi_repo_root} path={path} must require Basic Auth: {resp}"
1209                );
1210                assert!(resp.contains("WWW-Authenticate: Basic realm=\"arks\""));
1211            }
1212            assert_eq!(
1213                page_hits.load(Ordering::SeqCst),
1214                0,
1215                "pages handler must never run before Basic Auth succeeds (multi_repo={multi_repo_root})"
1216            );
1217
1218            // Health and metrics endpoints remain exempt.
1219            for exempt in ["/healthz", "/readyz", "/metrics"] {
1220                let req =
1221                    format!("GET {exempt} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
1222                let resp = raw_http_exchange(addr, &req);
1223                assert!(
1224                    resp.starts_with("HTTP/1.1 200 OK"),
1225                    "exempt endpoint {exempt} must succeed without auth: {resp}"
1226                );
1227            }
1228
1229            // Authenticated request reaches pages cleanly.
1230            let authed_req = format!(
1231                "GET / HTTP/1.1\r\nHost: {addr}\r\nAuthorization: {auth_hdr}\r\nConnection: close\r\n\r\n"
1232            );
1233            let authed_resp = raw_http_exchange(addr, &authed_req);
1234            assert!(
1235                authed_resp.starts_with("HTTP/1.1 200 OK") && authed_resp.contains("page:/"),
1236                "authenticated request must reach pages: {authed_resp}"
1237            );
1238            assert_eq!(page_hits.load(Ordering::SeqCst), 1);
1239
1240            stop.store(true, Ordering::SeqCst);
1241            handle.join().unwrap().unwrap();
1242        }
1243    }
1244
1245    #[test]
1246    fn cross_origin_write_rejected_when_pages_enabled() {
1247        let dir = TempDir::new().unwrap();
1248        seed_empty_bare(dir.path());
1249        let pages: PageHandler = Arc::new(|_req: &HttpRequest| None);
1250        let opts = ServeHttpOptions {
1251            pages: Some(pages.clone()),
1252            ..ServeHttpOptions::default()
1253        };
1254
1255        // Unit-level checks across all mutating Git / LFS / WebDAV verbs.
1256        for (method, path) in [
1257            ("POST", "/git-receive-pack"),
1258            ("POST", "/demo.git/git-receive-pack"),
1259            ("PUT", "/info/lfs/objects/deadbeef"),
1260            ("PUT", "/refs/heads/main"),
1261            ("MOVE", "/objects/ab/cdef"),
1262            ("DELETE", "/refs/heads/topic"),
1263            ("LOCK", "/refs/heads/main"),
1264            ("UNLOCK", "/refs/heads/main"),
1265        ] {
1266            let mut cross = HttpRequest::new(method, path, "", Vec::new());
1267            cross.host = Some("127.0.0.1:8080".into());
1268            cross.origin = Some("https://evil.example".into());
1269            let resp = check_cross_origin_write(&opts, &cross)
1270                .expect("cross-origin mutating write must be rejected");
1271            assert_eq!(resp.status, 403, "{method} {path} must return 403");
1272            assert!(
1273                String::from_utf8_lossy(&resp.body).contains("cross-origin write rejected"),
1274                "{}",
1275                String::from_utf8_lossy(&resp.body)
1276            );
1277
1278            let mut same = cross.clone();
1279            same.origin = Some("http://127.0.0.1:8080".into());
1280            assert!(
1281                check_cross_origin_write(&opts, &same).is_none(),
1282                "same-origin {method} {path} must be allowed"
1283            );
1284
1285            let mut no_origin = cross.clone();
1286            no_origin.origin = None;
1287            assert!(
1288                check_cross_origin_write(&opts, &no_origin).is_none(),
1289                "missing Origin without Sec-Fetch-Site on {method} {path} must be allowed"
1290            );
1291
1292            let mut cross_fetch_site = no_origin.clone();
1293            cross_fetch_site.sec_fetch_site = Some("cross-site".into());
1294            let resp = check_cross_origin_write(&opts, &cross_fetch_site)
1295                .expect("Sec-Fetch-Site: cross-site without Origin must be rejected");
1296            assert_eq!(resp.status, 403, "{method} {path} must return 403");
1297
1298            let mut same_fetch_site = no_origin;
1299            same_fetch_site.sec_fetch_site = Some("same-origin".into());
1300            assert!(
1301                check_cross_origin_write(&opts, &same_fetch_site).is_none(),
1302                "Sec-Fetch-Site: same-origin without Origin on {method} {path} must be allowed"
1303            );
1304        }
1305
1306        // Live loopback enforcement when pages is enabled.
1307        let (addr, stop, handle) =
1308            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
1309        let req = format!(
1310            "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"
1311        );
1312        let resp = raw_http_exchange(addr, &req);
1313        assert!(
1314            resp.starts_with("HTTP/1.1 403 Forbidden")
1315                && resp.contains("cross-origin write rejected"),
1316            "live loopback must reject cross-origin receive-pack with 403: {resp}"
1317        );
1318        stop.store(true, Ordering::SeqCst);
1319        handle.join().unwrap().unwrap();
1320    }
1321
1322    #[test]
1323    fn webdav_writes_require_forge_auth_and_lfs_honors_forwarded_proto_https() {
1324        let dir = TempDir::new().unwrap();
1325        seed_empty_bare(dir.path());
1326
1327        let reader_pat = "arks_pat_reader_test_token";
1328        let reader_hash = {
1329            let digest = Sha256::digest(reader_pat.as_bytes());
1330            let mut s = String::with_capacity(64);
1331            for b in digest {
1332                s.push_str(&format!("{b:02x}"));
1333            }
1334            s
1335        };
1336
1337        let mut store = crate::web_ui::store::ForgeStore::load(dir.path());
1338        store.users.push(crate::web_ui::store::UserAccount {
1339            username: "reader1".into(),
1340            password_hash: "x".into(),
1341            role: "reader".into(),
1342            ssh_keys: Vec::new(),
1343            created_at: 1,
1344            totp_secret_b32: None,
1345            recovery_codes: Vec::new(),
1346        });
1347        store.pats.push(crate::web_ui::store::PatRecord {
1348            id: 1,
1349            username: "reader1".into(),
1350            name: "read".into(),
1351            token_hash: reader_hash,
1352            prefix: "arks_pat_r".into(),
1353            created_at: 1,
1354        });
1355        store.save(dir.path()).unwrap();
1356
1357        let (addr, stop, handle) =
1358            spawn_loopback_with_opts(dir.path().to_path_buf(), ServeHttpOptions::default())
1359                .unwrap();
1360
1361        // Unauthenticated mutating WebDAV verbs must receive 401 when ForgeStore has users.
1362        for (method, path) in [
1363            ("PUT", "/refs/heads/main"),
1364            ("MKCOL", "/objects/ab"),
1365            ("LOCK", "/refs/heads/main"),
1366            ("DELETE", "/refs/heads/main"),
1367        ] {
1368            let req = format!(
1369                "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1370            );
1371            let resp = raw_http_exchange(addr, &req);
1372            assert!(
1373                resp.starts_with("HTTP/1.1 401 Unauthorized"),
1374                "unauthenticated WebDAV {method} {path} must return 401: {resp}"
1375            );
1376        }
1377
1378        // Reader PAT must receive 403 Forbidden on mutating WebDAV writes.
1379        let reader_put = format!(
1380            "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"
1381        );
1382        let reader_resp = raw_http_exchange(addr, &reader_put);
1383        assert!(
1384            reader_resp.starts_with("HTTP/1.1 403 Forbidden"),
1385            "reader role must be denied WebDAV PUT with 403: {reader_resp}"
1386        );
1387
1388        // PROPFIND remains read-only discovery on public repos (207 Multi-Status).
1389        let propfind = format!(
1390            "PROPFIND / HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1391        );
1392        let prop_resp = raw_http_exchange(addr, &propfind);
1393        assert!(
1394            prop_resp.starts_with("HTTP/1.1 207 Multi-Status"),
1395            "PROPFIND discovery on public repo must return 207: {prop_resp}"
1396        );
1397
1398        // Reverse-proxy `X-Forwarded-Proto: https` must produce `https://` LFS batch hrefs.
1399        let batch_body = format!(
1400            r#"{{"operation":"upload","objects":[{{"oid":"{}","size":4}}]}}"#,
1401            "a".repeat(64)
1402        );
1403        let lfs_req = format!(
1404            "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{}",
1405            batch_body.len(),
1406            batch_body
1407        );
1408        let lfs_resp = raw_http_exchange(addr, &lfs_req);
1409        assert!(
1410            lfs_resp.starts_with("HTTP/1.1 200 OK")
1411                && lfs_resp.contains("https://proxy.example.invalid/info/lfs/objects/"),
1412            "LFS batch must honor X-Forwarded-Proto: https: {lfs_resp}"
1413        );
1414
1415        stop.store(true, Ordering::SeqCst);
1416        handle.join().unwrap().unwrap();
1417    }
1418
1419    #[test]
1420    fn slow_post_body_dribble_hits_cumulative_deadline() {
1421        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1422        let addr = listener.local_addr().unwrap();
1423
1424        let client = thread::spawn(move || {
1425            let mut sock = TcpStream::connect(addr).unwrap();
1426            for _ in 0..8 {
1427                if sock.write_all(b"x").is_err() {
1428                    break;
1429                }
1430                thread::sleep(Duration::from_millis(60));
1431            }
1432        });
1433
1434        let (mut srv, _) = listener.accept().unwrap();
1435        let mut buf = Vec::new();
1436        let mut tmp = [0u8; 64];
1437        let completed = read_http_body_with_deadline(
1438            &mut srv,
1439            &mut buf,
1440            &mut tmp,
1441            1024,
1442            Duration::from_millis(200),
1443        )
1444        .unwrap();
1445        assert!(
1446            !completed,
1447            "Slow-POST dribble must time out against cumulative body deadline"
1448        );
1449        drop(srv);
1450        client.join().unwrap();
1451    }
1452}