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 GIT_UPLOAD_PACK_TOTAL: AtomicU64 = AtomicU64::new(0);
23static GIT_RECEIVE_PACK_TOTAL: AtomicU64 = AtomicU64::new(0);
24static LFS_BYTES_TOTAL: AtomicU64 = AtomicU64::new(0);
25static SERVER_START: OnceLock<Instant> = OnceLock::new();
26static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);
27
28/// Mark the process as shutting down so `/readyz` flips to 503 during drain (O-1).
29pub fn mark_shutting_down() {
30    SHUTTING_DOWN.store(true, Ordering::SeqCst);
31}
32
33/// Returns `true` once graceful shutdown has been initiated.
34pub fn is_shutting_down() -> bool {
35    SHUTTING_DOWN.load(Ordering::SeqCst)
36}
37
38/// Real readiness probe check for `/readyz` and `/healthz` (SO-PROBE-1).
39fn check_server_readiness(git_dir: &Path, opts: &ServeHttpOptions) -> Result<(), &'static str> {
40    if is_shutting_down()
41        || opts
42            .shutdown_flag
43            .as_ref()
44            .is_some_and(|f| f.load(Ordering::SeqCst))
45    {
46        return Err("shutting_down");
47    }
48    let meta = std::fs::metadata(git_dir).map_err(|_| "data_dir_missing")?;
49    if !meta.is_dir() || meta.permissions().readonly() {
50        return Err("data_dir_unwritable");
51    }
52    if !opts.multi_repo_root {
53        let store = crate::web_ui::store::ForgeStore::load_shared(git_dir);
54        if store.corrupt {
55            return Err("store_corrupt");
56        }
57    }
58    Ok(())
59}
60
61/// Gate `/metrics` to loopback peers or a valid `Authorization: Bearer <metrics_token>` (SO-MET-1).
62fn metrics_authorized(
63    peer_ip: std::net::IpAddr,
64    authorization: Option<&str>,
65    opts: &ServeHttpOptions,
66) -> bool {
67    use subtle::ConstantTimeEq as _;
68    let token = opts
69        .metrics_token
70        .clone()
71        .or_else(|| crate::ops::resolve_secret_env("ARKS_METRICS_TOKEN"))
72        .filter(|t| !t.trim().is_empty());
73    if let (Some(expected), Some(auth)) = (token.as_deref(), authorization) {
74        if let Some(presented) = auth
75            .strip_prefix("Bearer ")
76            .or_else(|| auth.strip_prefix("bearer "))
77        {
78            let a = expected.as_bytes();
79            let b = presented.trim().as_bytes();
80            if a.len() == b.len() && bool::from(a.ct_eq(b)) {
81                return true;
82            }
83        }
84    }
85    peer_ip.is_loopback() && !opts.metrics_require_token
86}
87
88fn max_http_body_bytes() -> usize {
89    std::env::var("ARKS_HTTP_MAX_BODY_BYTES")
90        .ok()
91        .and_then(|v| v.trim().parse::<usize>().ok())
92        .filter(|&n| n > 0)
93        .unwrap_or(64 * 1024 * 1024)
94}
95
96fn max_http_concurrency() -> usize {
97    std::env::var("ARKS_HTTP_MAX_CONCURRENCY")
98        .ok()
99        .and_then(|v| v.trim().parse::<usize>().ok())
100        .filter(|&n| n > 0)
101        .unwrap_or(128)
102}
103
104fn max_http_header_timeout() -> Duration {
105    let secs = std::env::var("ARKS_HTTP_HEADER_TIMEOUT_SECS")
106        .ok()
107        .and_then(|v| v.trim().parse::<u64>().ok())
108        .filter(|&n| n > 0)
109        .unwrap_or(10);
110    Duration::from_secs(secs)
111}
112
113fn max_http_body_timeout() -> Duration {
114    let secs = std::env::var("ARKS_HTTP_BODY_TIMEOUT_SECS")
115        .ok()
116        .and_then(|v| v.trim().parse::<u64>().ok())
117        .filter(|&n| n > 0)
118        .unwrap_or(60);
119    Duration::from_secs(secs)
120}
121
122/// Returns true for transient `accept()` errors (FD exhaustion `EMFILE`/`ENFILE`,
123/// aborted handshake, or interrupt) where the listener must back off rather than exit.
124pub(crate) fn is_transient_accept_error(err: &std::io::Error) -> bool {
125    if matches!(
126        err.kind(),
127        std::io::ErrorKind::WouldBlock
128            | std::io::ErrorKind::Interrupted
129            | std::io::ErrorKind::ConnectionAborted
130            | std::io::ErrorKind::ConnectionReset
131    ) {
132        return true;
133    }
134    #[cfg(unix)]
135    {
136        // ENOMEM (12), ENFILE (23), EMFILE (24), macOS ENOBUFS (55), Linux ENOBUFS (105).
137        if matches!(err.raw_os_error(), Some(12 | 23 | 24 | 55 | 105)) {
138            return true;
139        }
140    }
141    #[cfg(windows)]
142    {
143        // WSAEMFILE (10024), WSAECONNRESET (10054), WSAENOBUFS (10055).
144        if matches!(err.raw_os_error(), Some(10024 | 10054 | 10055)) {
145            return true;
146        }
147    }
148    false
149}
150
151pub(crate) struct ActiveConnGuard;
152impl Drop for ActiveConnGuard {
153    fn drop(&mut self) {
154        HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Release);
155    }
156}
157
158/// Atomically reserve an HTTP concurrency slot up to `limit` before spawning a worker thread.
159pub(crate) fn try_reserve_http_slot_with_limit(limit: usize) -> Option<ActiveConnGuard> {
160    let mut cur = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire);
161    loop {
162        if cur >= limit {
163            return None;
164        }
165        match HTTP_ACTIVE_CONNECTIONS.compare_exchange_weak(
166            cur,
167            cur + 1,
168            Ordering::AcqRel,
169            Ordering::Acquire,
170        ) {
171            Ok(_) => return Some(ActiveConnGuard),
172            Err(observed) => cur = observed,
173        }
174    }
175}
176
177/// Atomically reserve an HTTP concurrency slot before spawning a worker thread.
178fn try_reserve_http_slot() -> Option<ActiveConnGuard> {
179    try_reserve_http_slot_with_limit(max_http_concurrency())
180}
181
182/// Returns the number of currently active in-flight HTTP requests (for graceful drain).
183#[allow(dead_code)]
184pub fn active_http_connections() -> usize {
185    HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire)
186}
187
188type LoopbackHttp = (
189    SocketAddr,
190    Arc<AtomicBool>,
191    thread::JoinHandle<Result<(), ServerError>>,
192);
193
194/// Shared slot: when set to `Some(addr)`, the HTTP accept loop performs a
195/// bounded dual-bind rebind. B7 is Claimed for the evidenced HTTP scenario;
196/// SSH/forge rebind and OpenSSH-class interop are separate gates.
197pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
198
199/// Optional page handler consulted for `GET` requests before git HTTP; it
200/// answers `Some(response)` for the paths it owns and `None` for the rest
201/// (used by `instaweb` for its repository browser pages).
202pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
203
204#[derive(Clone, Default)]
205pub struct ServeHttpOptions {
206    /// When true, answer `info/refs` (even with `service=`) as dumb text/plain so
207    /// smart clients fall back to dumb HTTP (gitprotocol-http). Used by G29.
208    pub dumb_only: bool,
209    /// Optional in-process HTTP Basic (G36). Unset = unauthenticated (G15).
210    pub basic_auth: Option<BasicAuthConfig>,
211    /// Optional live listen rebind target (Partial; polled in accept loop).
212    pub rebind_desired: Option<ListenRebindSlot>,
213    /// Optional rustls server config for in-process TLS terminate (B9).
214    pub tls: Option<Arc<ServerConfig>>,
215    /// Optional browser pages served beside git HTTP.
216    pub pages: Option<PageHandler>,
217    /// When true, disable the built-in `/info/lfs` Batch + Basic Transfer server (`--no-lfs`).
218    pub disable_lfs: bool,
219    /// When true, `git_dir` is a multi-repository root directory and `pages` handles all routes
220    /// (Web UI + `/<repo>.git/...` Smart HTTP/LFS) without opening a single repo at `git_dir`.
221    pub multi_repo_root: bool,
222    /// Optional cumulative HTTP header-read deadline override (falls back to
223    /// `ARKS_HTTP_HEADER_TIMEOUT_SECS`, default 10s).
224    pub header_timeout: Option<Duration>,
225    /// Optional trusted reverse-proxy CIDR configuration (falls back to
226    /// `ARKS_TRUSTED_PROXIES`, default loopback-only).
227    pub trusted_proxies: Option<crate::proxy::TrustedProxyConfig>,
228    /// Optional per-server shutdown flag (used alongside global `SHUTTING_DOWN` for `/readyz`).
229    pub shutdown_flag: Option<Arc<AtomicBool>>,
230    /// Optional Bearer token authorizing `/metrics` from non-loopback peers
231    /// (falls back to `ARKS_METRICS_TOKEN`).
232    pub metrics_token: Option<String>,
233    /// When true, `/metrics` requires the Bearer token even from loopback peers (used in tests
234    /// and strict deployments).
235    pub metrics_require_token: bool,
236}
237
238impl std::fmt::Debug for ServeHttpOptions {
239    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240        f.debug_struct("ServeHttpOptions")
241            .field("dumb_only", &self.dumb_only)
242            .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
243            .field("rebind_desired", &self.rebind_desired.is_some())
244            .field("tls", &self.tls.is_some())
245            .field("pages", &self.pages.is_some())
246            .field("disable_lfs", &self.disable_lfs)
247            .field("multi_repo_root", &self.multi_repo_root)
248            .field("header_timeout", &self.header_timeout)
249            .field("trusted_proxies", &self.trusted_proxies.is_some())
250            .field("shutdown_flag", &self.shutdown_flag.is_some())
251            .field("metrics_token", &self.metrics_token.is_some())
252            .field("metrics_require_token", &self.metrics_require_token)
253            .finish()
254    }
255}
256
257/// Bind `addr` and serve `git_dir` over smart HTTP until `stop` is set or accept fails.
258pub fn serve_http(
259    git_dir: impl AsRef<Path>,
260    addr: SocketAddr,
261    stop: Arc<AtomicBool>,
262) -> Result<(), ServerError> {
263    serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
264}
265
266pub fn serve_http_with_opts(
267    git_dir: impl AsRef<Path>,
268    addr: SocketAddr,
269    stop: Arc<AtomicBool>,
270    opts: ServeHttpOptions,
271) -> Result<(), ServerError> {
272    let git_dir = git_dir.as_ref().to_path_buf();
273    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
274    let mut listener = TcpListener::bind(addr)?;
275    listener.set_nonblocking(true)?;
276    let mut current = addr;
277    // A successful rebind keeps prior listeners accepting for this bounded
278    // overlap. Accepted handlers are independently owned and always drain.
279    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
280    let mut last_accept_err_log: Option<Instant> = None;
281    while !stop.load(Ordering::SeqCst) {
282        if let Some(slot) = &opts.rebind_desired {
283            if let Ok(mut g) = slot.lock() {
284                if let Some(new_addr) = g.take() {
285                    if new_addr != current {
286                        match TcpListener::bind(new_addr) {
287                            Ok(l) => {
288                                if let Err(e) = l.set_nonblocking(true) {
289                                    eprintln!(
290                                        "arks serve-http: live rebind Partial bind ok but \
291                                         nonblocking fail ({e}); keeping {current}"
292                                    );
293                                    *g = Some(new_addr);
294                                } else {
295                                    eprintln!(
296                                        "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
297                                         prior listener draining for 5s"
298                                    );
299                                    let old = std::mem::replace(&mut listener, l);
300                                    draining.push((
301                                        old,
302                                        current,
303                                        Instant::now() + Duration::from_secs(5),
304                                    ));
305                                    current = new_addr;
306                                }
307                            }
308                            Err(e) => {
309                                eprintln!(
310                                    "arks serve-http: live rebind Partial fail {current} → \
311                                     {new_addr} ({e}); keeping prior listen"
312                                );
313                            }
314                        }
315                    }
316                }
317            }
318        }
319        draining.retain(|(_, old_addr, deadline)| {
320            if Instant::now() < *deadline {
321                true
322            } else {
323                eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
324                false
325            }
326        });
327        match listener.accept() {
328            Ok((stream, _)) => {
329                dispatch_accepted_stream(stream, &git_dir, &opts);
330            }
331            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
332                thread::sleep(std::time::Duration::from_millis(1));
333            }
334            Err(e) if is_transient_accept_error(&e) => {
335                if last_accept_err_log
336                    .map(|t| t.elapsed() >= Duration::from_secs(1))
337                    .unwrap_or(true)
338                {
339                    eprintln!(
340                        "arks serve-http: transient accept error on {current} ({e}); backing off"
341                    );
342                    last_accept_err_log = Some(Instant::now());
343                }
344                thread::sleep(std::time::Duration::from_millis(25));
345            }
346            Err(e) => return Err(e.into()),
347        }
348        for (old_listener, _, _) in &draining {
349            match old_listener.accept() {
350                Ok((stream, _)) => {
351                    dispatch_accepted_stream(stream, &git_dir, &opts);
352                }
353                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
354                Err(e) => {
355                    if last_accept_err_log
356                        .map(|t| t.elapsed() >= Duration::from_secs(1))
357                        .unwrap_or(true)
358                    {
359                        eprintln!("arks serve-http: draining listener accept error: {e}");
360                        last_accept_err_log = Some(Instant::now());
361                    }
362                }
363            }
364        }
365    }
366    // Graceful shutdown (O-1): stop accepting and wait for in-flight requests to finish
367    // up to `ARKS_SHUTDOWN_GRACE_SECS` (default 30s; legacy alias `ARKS_SHUTDOWN_DRAIN_SECS`).
368    drop(listener);
369    drop(draining);
370    let drain_secs = std::env::var("ARKS_SHUTDOWN_GRACE_SECS")
371        .or_else(|_| std::env::var("ARKS_SHUTDOWN_DRAIN_SECS"))
372        .ok()
373        .and_then(|v| v.trim().parse::<u64>().ok())
374        .unwrap_or(30);
375    let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
376    while active_http_connections() > 0 && Instant::now() < drain_deadline {
377        thread::sleep(Duration::from_millis(25));
378    }
379    Ok(())
380}
381
382/// Bind an ephemeral port; return (bound addr, join handle, stop flag).
383pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
384    spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
385}
386
387pub fn spawn_loopback_with_opts(
388    git_dir: PathBuf,
389    opts: ServeHttpOptions,
390) -> Result<LoopbackHttp, ServerError> {
391    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
392    let listener = TcpListener::bind("127.0.0.1:0")?;
393    let addr = listener.local_addr()?;
394    listener.set_nonblocking(true)?;
395    let stop = Arc::new(AtomicBool::new(false));
396    let stop2 = stop.clone();
397    let handle = thread::spawn(move || {
398        let mut last_accept_err_log: Option<Instant> = None;
399        while !stop2.load(Ordering::SeqCst) {
400            match listener.accept() {
401                Ok((stream, _)) => {
402                    dispatch_accepted_stream(stream, &git_dir, &opts);
403                }
404                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
405                    thread::sleep(std::time::Duration::from_millis(1));
406                }
407                Err(e) if is_transient_accept_error(&e) => {
408                    if last_accept_err_log
409                        .map(|t| t.elapsed() >= Duration::from_secs(1))
410                        .unwrap_or(true)
411                    {
412                        eprintln!(
413                            "arks serve-http: transient loopback accept error ({e}); backing off"
414                        );
415                        last_accept_err_log = Some(Instant::now());
416                    }
417                    thread::sleep(std::time::Duration::from_millis(25));
418                }
419                Err(e) => return Err(e.into()),
420            }
421        }
422        Ok(())
423    });
424    Ok((addr, stop, handle))
425}
426
427fn send_fast_503(stream: &mut TcpStream) {
428    let _ = stream.set_nonblocking(false);
429    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
430    let resp = HttpResponse {
431        status: 503,
432        content_type: "text/plain; charset=utf-8".into(),
433        body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
434        www_authenticate: None,
435        extra_headers: vec![("Retry-After".into(), "1".into())],
436    };
437    let _ = write_http_response(stream, &resp);
438    let _ = stream.shutdown(std::net::Shutdown::Write);
439}
440
441fn send_fast_408_with_reason<S: HttpStream>(stream: &mut S, reason: &'static [u8]) {
442    let resp = HttpResponse {
443        status: 408,
444        content_type: "text/plain; charset=utf-8".into(),
445        body: reason.to_vec(),
446        www_authenticate: None,
447        extra_headers: Vec::new(),
448    };
449    let _ = write_http_response(stream, &resp);
450    stream.shutdown_write();
451}
452
453fn send_fast_408<S: HttpStream>(stream: &mut S) {
454    send_fast_408_with_reason(stream, b"Request Timeout: HTTP header deadline exceeded\n");
455}
456
457/// Read HTTP body bytes until `buf.len() >= total_needed` under a cumulative `body_timeout`
458/// deadline so Slow-POST dribbles cannot hold worker threads indefinitely (`SEC-11`).
459/// Returns `Ok(true)` when body reading finished (or peer closed), or `Ok(false)` on timeout.
460fn read_http_body_with_deadline<S: HttpStream>(
461    stream: &mut S,
462    buf: &mut Vec<u8>,
463    tmp: &mut [u8],
464    total_needed: usize,
465    body_timeout: Duration,
466) -> Result<bool, ServerError> {
467    if buf.len() >= total_needed {
468        return Ok(true);
469    }
470    let body_deadline = Instant::now() + body_timeout;
471    while buf.len() < total_needed {
472        let now = Instant::now();
473        if now >= body_deadline {
474            return Ok(false);
475        }
476        let rem = body_deadline
477            .saturating_duration_since(now)
478            .max(Duration::from_millis(1));
479        stream.set_stream_read_timeout(rem);
480        match stream.read(tmp) {
481            Ok(0) => break,
482            Ok(n) => {
483                buf.extend_from_slice(&tmp[..n]);
484                if buf.len() < total_needed && Instant::now() >= body_deadline {
485                    return Ok(false);
486                }
487            }
488            Err(e)
489                if matches!(
490                    e.kind(),
491                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
492                ) =>
493            {
494                return Ok(false);
495            }
496            Err(e) => return Err(e.into()),
497        }
498    }
499    Ok(true)
500}
501
502fn is_mutating_git_lfs_dav_request(req: &HttpRequest) -> bool {
503    let method = req.method.to_ascii_uppercase();
504    let is_receive_pack =
505        req.path.ends_with("/git-receive-pack") || req.path.contains("/git-receive-pack");
506    if is_receive_pack && !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS") {
507        return true;
508    }
509    if crate::lfs::is_lfs_path(&req.path) && method == "PUT" {
510        return true;
511    }
512    matches!(
513        method.as_str(),
514        "PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
515    )
516}
517
518/// Reject cross-origin mutating Git/LFS/WebDAV writes when browser pages are co-hosted (`INT-S03`).
519pub(crate) fn check_cross_origin_write(
520    opts: &ServeHttpOptions,
521    req: &HttpRequest,
522) -> Option<HttpResponse> {
523    if opts.pages.is_none() || !is_mutating_git_lfs_dav_request(req) {
524        return None;
525    }
526    let Some(origin) = req
527        .origin
528        .as_deref()
529        .map(str::trim)
530        .filter(|o| !o.is_empty())
531    else {
532        if req
533            .sec_fetch_site
534            .as_deref()
535            .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
536        {
537            return Some(HttpResponse {
538                status: 403,
539                content_type: "text/plain; charset=utf-8".into(),
540                body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
541                www_authenticate: None,
542                extra_headers: Vec::new(),
543            });
544        }
545        return None;
546    };
547    let origin_host = origin
548        .strip_prefix("http://")
549        .or_else(|| origin.strip_prefix("https://"))
550        .unwrap_or(origin)
551        .split('/')
552        .next()
553        .unwrap_or("")
554        .trim();
555    let matches_host = req
556        .host
557        .as_deref()
558        .map(str::trim)
559        .filter(|h| !h.is_empty())
560        .is_some_and(|h| origin_host.eq_ignore_ascii_case(h));
561    if matches_host {
562        None
563    } else {
564        Some(HttpResponse {
565            status: 403,
566            content_type: "text/plain; charset=utf-8".into(),
567            body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
568            www_authenticate: None,
569            extra_headers: Vec::new(),
570        })
571    }
572}
573
574/// Atomically reserve a concurrency slot and dispatch a worker thread (fail-closed on saturation
575/// or OS thread exhaustion — never panics and never spawns above `ARKS_HTTP_MAX_CONCURRENCY`).
576fn dispatch_accepted_stream(mut stream: TcpStream, git_dir: &Path, opts: &ServeHttpOptions) {
577    let Some(guard) = try_reserve_http_slot() else {
578        send_fast_503(&mut stream);
579        return;
580    };
581    let dir = git_dir.to_path_buf();
582    let opts = opts.clone();
583    if let Err(e) = thread::Builder::new()
584        .name("arks-http-worker".into())
585        .spawn(move || {
586            let _ = handle_connection(stream, &dir, &opts, guard);
587        })
588    {
589        // Dropping the closure automatically drops `guard` (freeing the slot) and `stream`.
590        eprintln!("arks serve-http: worker thread spawn failed ({e}); rejecting connection");
591        thread::sleep(Duration::from_millis(10));
592    }
593}
594
595/// Scheme label for listen banners (`http` or `https`).
596pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
597    if opts.tls.is_some() { "https" } else { "http" }
598}
599
600const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
601const KEEP_ALIVE_IDLE_SECS: u64 = 5;
602
603trait HttpStream: Read + Write {
604    fn set_stream_read_timeout(&mut self, timeout: Duration);
605    fn shutdown_write(&mut self);
606}
607
608impl HttpStream for TcpStream {
609    fn set_stream_read_timeout(&mut self, timeout: Duration) {
610        let _ = self.set_read_timeout(Some(timeout));
611    }
612    fn shutdown_write(&mut self) {
613        let _ = self.shutdown(std::net::Shutdown::Write);
614    }
615}
616
617impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
618    fn set_stream_read_timeout(&mut self, timeout: Duration) {
619        let _ = self.sock.set_read_timeout(Some(timeout));
620    }
621    fn shutdown_write(&mut self) {
622        let _ = self.sock.shutdown(std::net::Shutdown::Write);
623    }
624}
625
626fn handle_connection(
627    mut stream: TcpStream,
628    git_dir: &Path,
629    opts: &ServeHttpOptions,
630    _guard: ActiveConnGuard,
631) -> Result<(), ServerError> {
632    let _ = SERVER_START.get_or_init(Instant::now);
633    // Listener is nonblocking; accepted sockets may inherit that on Windows.
634    stream.set_nonblocking(false)?;
635    let _ = stream.set_nodelay(true);
636    stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
637    stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
638    let peer_ip = stream
639        .peer_addr()
640        .map(|a| a.ip())
641        .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
642    if let Some(tls_cfg) = &opts.tls {
643        let conn = rustls::ServerConnection::new(tls_cfg.clone())
644            .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
645        let mut tls = rustls::StreamOwned::new(conn, stream);
646        // Complete handshake before HTTP parse.
647        tls.conn
648            .complete_io(&mut tls.sock)
649            .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
650        handle_connection_io(&mut tls, peer_ip, git_dir, opts)
651    } else {
652        handle_connection_io(&mut stream, peer_ip, git_dir, opts)
653    }
654}
655
656fn handle_connection_io<S: HttpStream>(
657    stream: &mut S,
658    peer_ip: std::net::IpAddr,
659    git_dir: &Path,
660    opts: &ServeHttpOptions,
661) -> Result<(), ServerError> {
662    let mut buf = Vec::with_capacity(4096);
663    let mut tmp = [0u8; 8192];
664    let header_timeout = opts.header_timeout.unwrap_or_else(max_http_header_timeout);
665    for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
666        let mut header_deadline = if req_idx == 0 {
667            Some(Instant::now() + header_timeout)
668        } else {
669            stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
670            None
671        };
672        let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
673        // Read headers in O(N) by scanning only newly arrived bytes (plus 3-byte overlap),
674        // bounded by a cumulative header deadline to defeat Slowloris dribbles.
675        while header_end.is_none() {
676            if let Some(dl) = header_deadline {
677                let now = Instant::now();
678                if now >= dl {
679                    send_fast_408(stream);
680                    return Ok(());
681                }
682                let rem = dl
683                    .saturating_duration_since(now)
684                    .max(Duration::from_millis(1));
685                stream.set_stream_read_timeout(rem);
686            }
687            let prev_len = buf.len();
688            match stream.read(&mut tmp) {
689                Ok(0) => {
690                    if req_idx > 0 && buf.is_empty() {
691                        return Ok(());
692                    }
693                    break;
694                }
695                Ok(n) => {
696                    if header_deadline.is_none() {
697                        header_deadline = Some(Instant::now() + header_timeout);
698                    }
699                    buf.extend_from_slice(&tmp[..n]);
700                    let search_from = prev_len.saturating_sub(3);
701                    if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
702                    {
703                        header_end = Some(search_from + rel);
704                        break;
705                    }
706                    if buf.len() > 1024 * 1024 {
707                        return Err(ServerError::Protocol("headers too large".into()));
708                    }
709                    if header_deadline.is_some_and(|dl| Instant::now() >= dl) {
710                        send_fast_408(stream);
711                        return Ok(());
712                    }
713                }
714                Err(e)
715                    if req_idx > 0
716                        && buf.is_empty()
717                        && matches!(
718                            e.kind(),
719                            std::io::ErrorKind::WouldBlock
720                                | std::io::ErrorKind::TimedOut
721                                | std::io::ErrorKind::ConnectionReset
722                                | std::io::ErrorKind::UnexpectedEof
723                        ) =>
724                {
725                    return Ok(());
726                }
727                Err(e)
728                    if header_deadline.is_some()
729                        && matches!(
730                            e.kind(),
731                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
732                        ) =>
733                {
734                    send_fast_408(stream);
735                    return Ok(());
736                }
737                Err(e) => return Err(e.into()),
738            }
739        }
740        let Some(header_end) = header_end else {
741            if req_idx > 0 && buf.is_empty() {
742                return Ok(());
743            }
744            return Err(ServerError::Protocol("incomplete headers".into()));
745        };
746        // Restore full body-streaming read timeout once HTTP headers are complete.
747        stream.set_stream_read_timeout(Duration::from_secs(30));
748        HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
749        let header_bytes = &buf[..header_end];
750        let header_text = std::str::from_utf8(header_bytes)
751            .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
752        let mut lines = header_text.split("\r\n");
753        let request_line = lines
754            .next()
755            .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
756        let mut parts = request_line.split_whitespace();
757        let method = parts
758            .next()
759            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
760            .to_string();
761        let target = parts
762            .next()
763            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
764        let http_version = parts.next().unwrap_or("HTTP/1.1");
765        let (path, query) = match target.split_once('?') {
766            Some((p, q)) => (p.to_string(), q.to_string()),
767            None => (target.to_string(), String::new()),
768        };
769        let mut content_length_opt: Option<usize> = None;
770        let mut has_transfer_encoding = false;
771        let mut header_smuggle_error: Option<&'static str> = None;
772        let mut expect_continue = false;
773        let mut content_encoding = String::new();
774        let mut connection_close = false;
775        let mut connection_keep_alive = false;
776        let mut git_protocol = None;
777        let mut authorization = None;
778        let mut destination = None;
779        let mut lock_token = None;
780        let mut host = None;
781        let mut cookie = None;
782        let mut origin = None;
783        let mut forwarded_proto = None;
784        let mut sec_fetch_site = None;
785        let mut headers: Vec<(String, String)> = Vec::new();
786        for line in lines {
787            if let Some((k, v)) = line.split_once(':') {
788                let key = k.trim();
789                if !key.is_empty() && headers.len() < 128 {
790                    headers.push((key.to_ascii_lowercase(), v.trim().to_string()));
791                }
792            }
793            let lower = line.to_ascii_lowercase();
794            if let Some(v) = lower.strip_prefix("content-length:") {
795                match v.trim().parse::<usize>() {
796                    Ok(parsed) => {
797                        if let Some(prev) = content_length_opt {
798                            if prev != parsed {
799                                header_smuggle_error = Some("conflicting Content-Length headers");
800                            }
801                        } else {
802                            content_length_opt = Some(parsed);
803                        }
804                    }
805                    Err(_) => {
806                        header_smuggle_error = Some("invalid Content-Length header");
807                    }
808                }
809            }
810            if lower.starts_with("transfer-encoding:") {
811                has_transfer_encoding = true;
812            }
813            if let Some(v) = lower.strip_prefix("connection:") {
814                if v.contains("close") {
815                    connection_close = true;
816                }
817                if v.contains("keep-alive") {
818                    connection_keep_alive = true;
819                }
820            }
821            if lower.starts_with("host:") {
822                if let Some((_, v)) = line.split_once(':') {
823                    host = Some(v.trim().to_string());
824                }
825            }
826            if lower.starts_with("cookie:") {
827                if let Some((_, v)) = line.split_once(':') {
828                    cookie = Some(v.trim().to_string());
829                }
830            }
831            if lower.starts_with("origin:") {
832                if let Some((_, v)) = line.split_once(':') {
833                    origin = Some(v.trim().to_string());
834                }
835            }
836            if lower.starts_with("x-forwarded-proto:") {
837                if let Some((_, v)) = line.split_once(':') {
838                    forwarded_proto = Some(v.trim().to_string());
839                }
840            }
841            if lower.starts_with("sec-fetch-site:") {
842                if let Some((_, v)) = line.split_once(':') {
843                    sec_fetch_site = Some(v.trim().to_string());
844                }
845            }
846            if lower.starts_with("expect:") && lower.contains("100-continue") {
847                // git/curl POST often waits for 100 before sending the pack body
848                // (gitprotocol-http / HTTP/1.1). Without this, clients see empty replies.
849                expect_continue = true;
850            }
851            if let Some(v) = lower.strip_prefix("content-encoding:") {
852                content_encoding = v.trim().to_string();
853            }
854            // gitprotocol-v2: clients send `Git-Protocol: version=2`.
855            if lower.starts_with("git-protocol:") {
856                if let Some((_, v)) = line.split_once(':') {
857                    git_protocol = Some(v.trim().to_string());
858                }
859            }
860            if lower.starts_with("authorization:") {
861                if let Some((_, v)) = line.split_once(':') {
862                    authorization = Some(v.trim().to_string());
863                }
864            }
865            // WebDAV (RFC 4918) — dumb HTTP push (git-http-push).
866            if lower.starts_with("destination:") {
867                if let Some((_, v)) = line.split_once(':') {
868                    destination = Some(v.trim().to_string());
869                }
870            }
871            if lower.starts_with("lock-token:") {
872                if let Some((_, v)) = line.split_once(':') {
873                    lock_token = Some(v.trim().to_string());
874                }
875            }
876            if lower.starts_with("if:") && lock_token.is_none() {
877                // git-http-push sends `If: (<opaquelocktoken:…>)` with the lock.
878                if let Some((_, v)) = line.split_once(':') {
879                    let v = v.trim();
880                    if let Some(start) = v.find("opaquelocktoken:") {
881                        let rest = &v[start..];
882                        let end = rest
883                            .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
884                            .unwrap_or(rest.len());
885                        lock_token = Some(rest[..end].to_string());
886                    }
887                }
888            }
889        }
890        if header_smuggle_error.is_none() && has_transfer_encoding && content_length_opt.is_some() {
891            header_smuggle_error = Some("ambiguous Transfer-Encoding and Content-Length headers");
892        }
893        if let Some(reason) = header_smuggle_error {
894            let resp = HttpResponse {
895                status: 400,
896                content_type: "text/plain; charset=utf-8".into(),
897                body: format!("Bad Request: {reason}\n").into_bytes(),
898                www_authenticate: None,
899                extra_headers: Vec::new(),
900            };
901            return write_http_response(stream, &resp);
902        }
903        let content_length = content_length_opt.unwrap_or(0);
904        let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
905            connection_keep_alive && !connection_close
906        } else {
907            !connection_close
908        };
909        let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
910            Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
911        } else {
912            None
913        };
914        let body_start = header_end + 4;
915        let is_head = method == "HEAD";
916        if path == "/livez" {
917            let resp = if method == "OPTIONS" {
918                HttpResponse {
919                    status: 204,
920                    content_type: "text/plain; charset=utf-8".into(),
921                    body: Vec::new(),
922                    www_authenticate: None,
923                    extra_headers: vec![
924                        ("Allow".into(), "GET, HEAD, OPTIONS".into()),
925                        ("Cache-Control".into(), "no-store".into()),
926                    ],
927                }
928            } else {
929                HttpResponse {
930                    status: 200,
931                    content_type: "application/json; charset=utf-8".into(),
932                    body: b"{\"status\":\"alive\"}\n".to_vec(),
933                    www_authenticate: None,
934                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
935                }
936            };
937            buf.drain(..body_start.min(buf.len()));
938            write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
939            if keep_alive_rem.is_some() {
940                continue;
941            }
942            return Ok(());
943        }
944        if path == "/healthz" || path == "/readyz" {
945            let resp = if method == "OPTIONS" {
946                HttpResponse {
947                    status: 204,
948                    content_type: "text/plain; charset=utf-8".into(),
949                    body: Vec::new(),
950                    www_authenticate: None,
951                    extra_headers: vec![
952                        ("Allow".into(), "GET, HEAD, OPTIONS".into()),
953                        ("Cache-Control".into(), "no-store".into()),
954                    ],
955                }
956            } else {
957                match check_server_readiness(git_dir, opts) {
958                    Ok(()) => HttpResponse {
959                        status: 200,
960                        content_type: "application/json; charset=utf-8".into(),
961                        body: b"{\"status\":\"ok\"}\n".to_vec(),
962                        www_authenticate: None,
963                        extra_headers: vec![("Cache-Control".into(), "no-store".into())],
964                    },
965                    Err(reason) => HttpResponse {
966                        status: 503,
967                        content_type: "application/json; charset=utf-8".into(),
968                        body: format!("{{\"status\":\"not_ready\",\"reason\":\"{reason}\"}}\n")
969                            .into_bytes(),
970                        www_authenticate: None,
971                        extra_headers: vec![("Cache-Control".into(), "no-store".into())],
972                    },
973                }
974            };
975            buf.drain(..body_start.min(buf.len()));
976            write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
977            if keep_alive_rem.is_some() {
978                continue;
979            }
980            return Ok(());
981        }
982        if path == "/metrics" {
983            let resp = if !metrics_authorized(peer_ip, authorization.as_deref(), opts) {
984                HttpResponse {
985                    status: 404,
986                    content_type: "text/plain; charset=utf-8".into(),
987                    body: b"not found\n".to_vec(),
988                    www_authenticate: None,
989                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
990                }
991            } else if method == "OPTIONS" {
992                HttpResponse {
993                    status: 204,
994                    content_type: "text/plain; charset=utf-8".into(),
995                    body: Vec::new(),
996                    www_authenticate: None,
997                    extra_headers: vec![
998                        ("Allow".into(), "GET, HEAD, OPTIONS".into()),
999                        ("Cache-Control".into(), "no-store".into()),
1000                    ],
1001                }
1002            } else {
1003                let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
1004                let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
1005                let upload = GIT_UPLOAD_PACK_TOTAL.load(Ordering::Relaxed);
1006                let receive = GIT_RECEIVE_PACK_TOTAL.load(Ordering::Relaxed);
1007                let lfs_bytes = LFS_BYTES_TOTAL.load(Ordering::Relaxed);
1008                let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
1009                let ver = env!("CARGO_PKG_VERSION");
1010                let metrics = format!(
1011                    "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
1012                     # TYPE arks_http_requests_total counter\n\
1013                     arks_http_requests_total {total}\n\
1014                     # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
1015                     # TYPE arks_http_active_connections gauge\n\
1016                     arks_http_active_connections {active}\n\
1017                     # HELP arks_uptime_seconds Server process uptime in seconds.\n\
1018                     # TYPE arks_uptime_seconds gauge\n\
1019                     arks_uptime_seconds {uptime}\n\
1020                     # HELP arks_git_upload_pack_total Total Git upload-pack RPC requests.\n\
1021                     # TYPE arks_git_upload_pack_total counter\n\
1022                     arks_git_upload_pack_total {upload}\n\
1023                     # HELP arks_git_receive_pack_total Total Git receive-pack RPC requests.\n\
1024                     # TYPE arks_git_receive_pack_total counter\n\
1025                     arks_git_receive_pack_total {receive}\n\
1026                     # HELP arks_lfs_bytes_total Total Git LFS bytes transferred.\n\
1027                     # TYPE arks_lfs_bytes_total counter\n\
1028                     arks_lfs_bytes_total {lfs_bytes}\n\
1029                     # HELP arks_build_info Build version information.\n\
1030                     # TYPE arks_build_info gauge\n\
1031                     arks_build_info{{version=\"{ver}\"}} 1\n"
1032                );
1033                HttpResponse {
1034                    status: 200,
1035                    content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
1036                    body: metrics.into_bytes(),
1037                    www_authenticate: None,
1038                    extra_headers: vec![("Cache-Control".into(), "no-store".into())],
1039                }
1040            };
1041            buf.drain(..body_start.min(buf.len()));
1042            write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
1043            if keep_alive_rem.is_some() {
1044                continue;
1045            }
1046            return Ok(());
1047        }
1048        let max_body = max_http_body_bytes();
1049        if content_length > max_body {
1050            let resp = HttpResponse {
1051                status: 413,
1052                content_type: "text/plain; charset=utf-8".into(),
1053                body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
1054                www_authenticate: None,
1055                extra_headers: Vec::new(),
1056            };
1057            return write_http_response(stream, &resp);
1058        }
1059        if expect_continue && content_length > 0 {
1060            if let Some(cfg) = &opts.basic_auth
1061                && !cfg.check_authorization(authorization.as_deref())
1062            {
1063                let resp = HttpResponse {
1064                    status: 401,
1065                    content_type: "text/plain; charset=utf-8".into(),
1066                    body: b"unauthorized\n".to_vec(),
1067                    www_authenticate: Some(cfg.challenge_header()),
1068                    extra_headers: Vec::new(),
1069                };
1070                return write_http_response(stream, &resp);
1071            }
1072            stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
1073            stream.flush()?;
1074        }
1075        let total_needed = body_start.saturating_add(content_length);
1076        if !read_http_body_with_deadline(
1077            stream,
1078            &mut buf,
1079            &mut tmp,
1080            total_needed,
1081            max_http_body_timeout(),
1082        )? {
1083            send_fast_408_with_reason(stream, b"Request Timeout: HTTP body deadline exceeded\n");
1084            return Ok(());
1085        }
1086        let avail_end = total_needed.min(buf.len());
1087        let mut body = buf[body_start..avail_end].to_vec();
1088        buf.drain(..avail_end);
1089        // Stock git/curl may gzip the upload-pack / receive-pack POST once the prior
1090        // advertisement is large (observed ~32+ refs). Accept Content-Encoding: gzip
1091        // and gzip magic even if the header is omitted — except for raw binary LFS PUTs!
1092        let is_lfs = crate::lfs::is_lfs_path(&path);
1093        let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
1094        if content_encoding.contains("gzip") || gzip_magic {
1095            use flate2::read::GzDecoder;
1096            use std::io::Read as _;
1097            let decoder = GzDecoder::new(body.as_slice());
1098            let mut decoded = Vec::new();
1099            decoder
1100                .take((max_body as u64).saturating_add(1))
1101                .read_to_end(&mut decoded)
1102                .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
1103            if decoded.len() > max_body {
1104                let resp = HttpResponse {
1105                    status: 413,
1106                    content_type: "text/plain; charset=utf-8".into(),
1107                    body: format!(
1108                        "Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
1109                    )
1110                    .into_bytes(),
1111                    www_authenticate: None,
1112                    extra_headers: Vec::new(),
1113                };
1114                return write_http_response(stream, &resp);
1115            }
1116            body = decoded;
1117        }
1118
1119        let proxy_cfg = opts
1120            .trusted_proxies
1121            .clone()
1122            .unwrap_or_else(crate::proxy::TrustedProxyConfig::from_env);
1123        // Strip any client-supplied internal header before injecting resolved client IP.
1124        headers.retain(|(k, _)| !k.eq_ignore_ascii_case("x-arks-client-ip"));
1125        let resolved = crate::proxy::resolve_client(peer_ip, &headers, &proxy_cfg);
1126        headers.push(("x-arks-client-ip".into(), resolved.ip.to_string()));
1127        let effective_host = resolved.host.or(host);
1128        let effective_proto = resolved.proto.or_else(|| {
1129            if opts.tls.is_some() {
1130                Some("https".into())
1131            } else {
1132                None
1133            }
1134        });
1135        let _ = forwarded_proto;
1136
1137        let mut req = HttpRequest {
1138            method,
1139            path: path.clone(),
1140            query: query.clone(),
1141            body,
1142            git_protocol,
1143            authorization,
1144            destination,
1145            lock_token,
1146            host: effective_host,
1147            cookie,
1148            origin,
1149            forwarded_proto: effective_proto,
1150            sec_fetch_site,
1151            headers,
1152        };
1153        // Enforce operator `--basic-auth` BEFORE `opts.pages` on BOTH single-repo and
1154        // multi-repo modes so Web UI, REST API, and Git RPC are uniformly gated
1155        // (`/healthz`, `/readyz`, `/metrics` were already served above).
1156        if req.path.contains("/git-upload-pack") {
1157            GIT_UPLOAD_PACK_TOTAL.fetch_add(1, Ordering::Relaxed);
1158        } else if req.path.contains("/git-receive-pack") {
1159            GIT_RECEIVE_PACK_TOTAL.fetch_add(1, Ordering::Relaxed);
1160        } else if is_lfs {
1161            LFS_BYTES_TOTAL.fetch_add(req.body.len() as u64, Ordering::Relaxed);
1162        }
1163        let resp = if let Some(cfg) = &opts.basic_auth
1164            && !cfg.check_authorization(req.authorization.as_deref())
1165        {
1166            HttpResponse {
1167                status: 401,
1168                content_type: "text/plain; charset=utf-8".into(),
1169                body: b"unauthorized\n".to_vec(),
1170                www_authenticate: Some(cfg.challenge_header()),
1171                extra_headers: Vec::new(),
1172            }
1173        } else if let Some(forbidden) = check_cross_origin_write(opts, &req) {
1174            forbidden
1175        } else if opts.multi_repo_root {
1176            match opts.pages.as_ref().and_then(|p| p(&req)) {
1177                Some(r) => r,
1178                None => HttpResponse {
1179                    status: 404,
1180                    content_type: "text/plain; charset=utf-8".into(),
1181                    body: b"repository or path not found\n".to_vec(),
1182                    www_authenticate: None,
1183                    extra_headers: Vec::new(),
1184                },
1185            }
1186        } else {
1187            let mut repo =
1188                Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
1189            // dumb_only: strip service= so discovery uses dumb info/refs (smart clients fall back).
1190            if opts.dumb_only
1191                && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
1192            {
1193                req.query = String::new();
1194            }
1195            let is_git_rpc = req.path.contains("/git-upload-pack")
1196                || req.path.contains("/git-receive-pack")
1197                || req.path.contains("/info/refs");
1198            let page = match &opts.pages {
1199                Some(pages)
1200                    if matches!(
1201                        req.method.as_str(),
1202                        "GET" | "HEAD" | "OPTIONS" | "POST" | "PATCH" | "DELETE"
1203                    ) && !is_lfs
1204                        && !is_git_rpc =>
1205                {
1206                    pages(&req)
1207                }
1208                _ => None,
1209            };
1210            let scheme = if req.is_https() || opts.tls.is_some() {
1211                "https"
1212            } else {
1213                "http"
1214            };
1215            let is_dav_write = crate::dav::is_dav_method(&req.method)
1216                && !req.method.eq_ignore_ascii_case("PROPFIND");
1217            let is_git_write = req.path.contains("/git-receive-pack")
1218                || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
1219                || (req.path.contains("/info/lfs/") && req.method.eq_ignore_ascii_case("PUT"))
1220                || (req.path.contains("/info/lfs/locks")
1221                    && req.method.eq_ignore_ascii_case("POST"))
1222                || is_dav_write;
1223            let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
1224                crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
1225            } else {
1226                None
1227            };
1228            let lfs_lock_resp = if page.is_none()
1229                && auth_denied.is_none()
1230                && !opts.disable_lfs
1231                && req.path.contains("/info/lfs/locks")
1232            {
1233                let store = crate::web_ui::store::ForgeStore::load_shared(git_dir);
1234                let actor = crate::web_ui::auth_api::resolve_actor(&store, &req);
1235                let actor_ref = actor.as_ref().map(|(u, r)| (u.as_str(), r.as_str()));
1236                crate::lfs_locks::handle_lfs_locks(git_dir, &req, actor_ref)
1237            } else {
1238                None
1239            };
1240            match page
1241                .or(auth_denied)
1242                .or(lfs_lock_resp)
1243                .map(Ok)
1244                .unwrap_or_else(|| {
1245                    handle_smart_http_auth_opts(
1246                        &mut repo,
1247                        &req,
1248                        opts.basic_auth.as_ref(),
1249                        !opts.disable_lfs,
1250                        scheme,
1251                    )
1252                }) {
1253                Ok(r) => r,
1254                Err(e) => {
1255                    // Fail closed with an HTTP error body (never silent empty close).
1256                    // Never log raw request body bytes or hex dumps (`SEC-12`).
1257                    let msg = e.to_string();
1258                    eprintln!(
1259                        "arks serve-http error path={path} body_len={} : {msg}",
1260                        req.body.len()
1261                    );
1262                    HttpResponse {
1263                        status: 500,
1264                        content_type: "text/plain".into(),
1265                        body: msg.into_bytes(),
1266                        www_authenticate: None,
1267                        extra_headers: Vec::new(),
1268                    }
1269                }
1270            }
1271        };
1272        let mut resp = resp;
1273        let trace = crate::ops::RequestTrace::from_request(&req);
1274        trace.attach_headers(&mut resp);
1275        if !is_head {
1276            maybe_gzip_response(&mut resp, &req);
1277        }
1278        crate::ops::maybe_emit_json_access_log(&trace, &req, resp.status, 0);
1279        let keep_alive = if matches!(resp.status, 408 | 413 | 503) {
1280            None
1281        } else {
1282            keep_alive_rem
1283        };
1284        write_http_response_full(stream, &resp, req.is_https(), keep_alive, is_head)?;
1285        if keep_alive.is_none() {
1286            return Ok(());
1287        }
1288    }
1289    Ok(())
1290}
1291
1292fn is_compressible_content_type(ct: &str) -> bool {
1293    let mime = ct
1294        .split(';')
1295        .next()
1296        .unwrap_or("")
1297        .trim()
1298        .to_ascii_lowercase();
1299    mime.starts_with("text/")
1300        || mime == "application/json"
1301        || mime == "application/problem+json"
1302        || mime == "application/javascript"
1303        || mime == "application/manifest+json"
1304        || mime == "application/linkset+json"
1305        || mime == "application/atom+xml"
1306        || mime == "image/svg+xml"
1307}
1308
1309fn maybe_gzip_response(resp: &mut HttpResponse, req: &HttpRequest) {
1310    if resp.body.len() < 1024
1311        || matches!(resp.status, 204 | 304)
1312        || crate::web::core::headers::is_git_wire_path(&req.path)
1313        || crate::dav::is_dav_method(&req.method)
1314        || !is_compressible_content_type(&resp.content_type)
1315    {
1316        return;
1317    }
1318    let accepts_gzip = req
1319        .header("accept-encoding")
1320        .is_some_and(|ae| ae.to_ascii_lowercase().contains("gzip"));
1321    if !accepts_gzip {
1322        return;
1323    }
1324    if resp
1325        .extra_headers
1326        .iter()
1327        .any(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
1328    {
1329        return;
1330    }
1331    let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
1332    if enc.write_all(&resp.body).is_ok()
1333        && let Ok(compressed) = enc.finish()
1334        && compressed.len() < resp.body.len()
1335    {
1336        resp.body = compressed;
1337        resp.extra_headers
1338            .push(("Content-Encoding".into(), "gzip".into()));
1339        if let Some((_, v)) = resp
1340            .extra_headers
1341            .iter_mut()
1342            .find(|(k, _)| k.eq_ignore_ascii_case("vary"))
1343        {
1344            if !v.to_ascii_lowercase().contains("accept-encoding") {
1345                v.push_str(", Accept-Encoding");
1346            }
1347        } else {
1348            resp.extra_headers
1349                .push(("Vary".into(), "Accept-Encoding".into()));
1350        }
1351    }
1352}
1353
1354fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
1355    write_http_response_full(stream, resp, false, None, false)
1356}
1357
1358#[cfg(test)]
1359fn write_http_response_with_options<S: Write>(
1360    stream: &mut S,
1361    resp: &HttpResponse,
1362    is_https: bool,
1363    keep_alive_remaining: Option<usize>,
1364) -> Result<(), ServerError> {
1365    write_http_response_full(stream, resp, is_https, keep_alive_remaining, false)
1366}
1367
1368fn write_http_response_full<S: Write>(
1369    stream: &mut S,
1370    resp: &HttpResponse,
1371    is_https: bool,
1372    keep_alive_remaining: Option<usize>,
1373    is_head: bool,
1374) -> Result<(), ServerError> {
1375    let status_text = match resp.status {
1376        200 => "OK",
1377        201 => "Created",
1378        204 => "No Content",
1379        207 => "Multi-Status",
1380        302 => "Found",
1381        303 => "See Other",
1382        304 => "Not Modified",
1383        400 => "Bad Request",
1384        401 => "Unauthorized",
1385        403 => "Forbidden",
1386        404 => "Not Found",
1387        405 => "Method Not Allowed",
1388        408 => "Request Timeout",
1389        409 => "Conflict",
1390        412 => "Precondition Failed",
1391        413 => "Payload Too Large",
1392        415 => "Unsupported Media Type",
1393        422 => "Unprocessable Entity",
1394        423 => "Locked",
1395        428 => "Precondition Required",
1396        429 => "Too Many Requests",
1397        500 => "Internal Server Error",
1398        501 => "Not Implemented",
1399        503 => "Service Unavailable",
1400        507 => "Insufficient Storage",
1401        _ => "Error",
1402    };
1403    let conn_header = match keep_alive_remaining {
1404        Some(rem) => format!(
1405            "Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
1406        ),
1407        None => "Connection: close\r\n".to_string(),
1408    };
1409    let mut header = format!(
1410        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
1411        resp.status,
1412        status_text,
1413        resp.content_type,
1414        resp.body.len(),
1415        conn_header
1416    );
1417    if let Some(ref wa) = resp.www_authenticate {
1418        header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
1419    }
1420    let mut has_csp = false;
1421    let mut has_pp = false;
1422    let mut has_coop = false;
1423    let mut has_corp = false;
1424    let mut has_xcto = false;
1425    let mut has_xfo = false;
1426    let mut has_rp = false;
1427    let mut has_hsts = false;
1428    let is_html = resp.content_type.starts_with("text/html");
1429    for (k, v) in &resp.extra_headers {
1430        if k.eq_ignore_ascii_case("content-security-policy") {
1431            has_csp = true;
1432            if is_html && is_https && !v.contains("upgrade-insecure-requests") {
1433                header.push_str(&format!("{k}: {v}; upgrade-insecure-requests\r\n"));
1434                continue;
1435            }
1436        } else if k.eq_ignore_ascii_case("permissions-policy") {
1437            has_pp = true;
1438        } else if k.eq_ignore_ascii_case("cross-origin-opener-policy") {
1439            has_coop = true;
1440        } else if k.eq_ignore_ascii_case("cross-origin-resource-policy") {
1441            has_corp = true;
1442        } else if k.eq_ignore_ascii_case("x-content-type-options") {
1443            has_xcto = true;
1444        } else if k.eq_ignore_ascii_case("x-frame-options") {
1445            has_xfo = true;
1446        } else if k.eq_ignore_ascii_case("referrer-policy") {
1447            has_rp = true;
1448        } else if k.eq_ignore_ascii_case("strict-transport-security") {
1449            has_hsts = true;
1450        }
1451        header.push_str(&format!("{k}: {v}\r\n"));
1452    }
1453    if is_html {
1454        if !has_csp {
1455            let csp = if is_https {
1456                crate::web::core::headers::WEB_UI_CSP_HTTPS
1457            } else {
1458                crate::web::core::headers::WEB_UI_CSP
1459            };
1460            header.push_str(&format!("Content-Security-Policy: {csp}\r\n"));
1461        }
1462        if !has_pp {
1463            header.push_str(&format!(
1464                "Permissions-Policy: {}\r\n",
1465                crate::web::core::headers::PERMISSIONS_POLICY
1466            ));
1467        }
1468        if !has_coop {
1469            header.push_str(&format!(
1470                "Cross-Origin-Opener-Policy: {}\r\n",
1471                crate::web::core::headers::COOP
1472            ));
1473        }
1474        if !has_corp {
1475            header.push_str(&format!(
1476                "Cross-Origin-Resource-Policy: {}\r\n",
1477                crate::web::core::headers::CORP
1478            ));
1479        }
1480        if !has_xcto {
1481            header.push_str(&format!(
1482                "X-Content-Type-Options: {}\r\n",
1483                crate::web::core::headers::X_CONTENT_TYPE_OPTIONS
1484            ));
1485        }
1486        if !has_xfo {
1487            header.push_str(&format!(
1488                "X-Frame-Options: {}\r\n",
1489                crate::web::core::headers::X_FRAME_OPTIONS
1490            ));
1491        }
1492        if !has_rp {
1493            header.push_str(&format!(
1494                "Referrer-Policy: {}\r\n",
1495                crate::web::core::headers::REFERRER_POLICY
1496            ));
1497        }
1498    }
1499    if is_https && !has_hsts {
1500        header.push_str(&format!(
1501            "Strict-Transport-Security: {}\r\n",
1502            crate::web::core::headers::HSTS
1503        ));
1504    }
1505    header.push_str("\r\n");
1506    if is_head || resp.status == 204 || resp.status == 304 {
1507        stream.write_all(header.as_bytes())?;
1508    } else if resp.body.len() <= 64 * 1024 {
1509        let mut combined = Vec::with_capacity(header.len() + resp.body.len());
1510        combined.extend_from_slice(header.as_bytes());
1511        combined.extend_from_slice(&resp.body);
1512        stream.write_all(&combined)?;
1513    } else {
1514        stream.write_all(header.as_bytes())?;
1515        stream.write_all(&resp.body)?;
1516    }
1517    stream.flush()?;
1518    Ok(())
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523    use super::*;
1524    use crate::auth::basic_authorization_header;
1525    use sha2::{Digest, Sha256};
1526    use tempfile::TempDir;
1527
1528    fn raw_http_exchange(addr: SocketAddr, request: &str) -> String {
1529        let mut sock = TcpStream::connect(addr).unwrap();
1530        sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
1531        sock.write_all(request.as_bytes()).unwrap();
1532        let mut out = Vec::new();
1533        let _ = sock.read_to_end(&mut out);
1534        String::from_utf8_lossy(&out).into_owned()
1535    }
1536
1537    fn seed_empty_bare(dir: &Path) {
1538        std::fs::create_dir_all(dir.join("objects")).unwrap();
1539        std::fs::create_dir_all(dir.join("refs/heads")).unwrap();
1540        std::fs::write(dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
1541    }
1542
1543    #[test]
1544    fn basic_auth_gates_pages_on_single_and_multi_repo_while_exempting_health_and_metrics() {
1545        let dir = TempDir::new().unwrap();
1546        seed_empty_bare(dir.path());
1547        let auth_hdr = basic_authorization_header("alice", "s3cret");
1548
1549        for multi_repo_root in [false, true] {
1550            let page_hits = Arc::new(AtomicUsize::new(0));
1551            let hits_cb = Arc::clone(&page_hits);
1552            let pages: PageHandler = Arc::new(move |req: &HttpRequest| {
1553                hits_cb.fetch_add(1, Ordering::SeqCst);
1554                Some(HttpResponse {
1555                    status: 200,
1556                    content_type: "text/plain; charset=utf-8".into(),
1557                    body: format!("page:{}\n", req.path).into_bytes(),
1558                    www_authenticate: None,
1559                    extra_headers: Vec::new(),
1560                })
1561            });
1562            let opts = ServeHttpOptions {
1563                basic_auth: Some(BasicAuthConfig::single("alice", "s3cret")),
1564                pages: Some(pages),
1565                multi_repo_root,
1566                ..ServeHttpOptions::default()
1567            };
1568            let (addr, stop, handle) =
1569                spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
1570
1571            // Unauthenticated Web UI and REST API routes MUST return 401 before invoking pages.
1572            for path in ["/", "/api/v1/issues"] {
1573                let req =
1574                    format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
1575                let resp = raw_http_exchange(addr, &req);
1576                assert!(
1577                    resp.starts_with("HTTP/1.1 401 Unauthorized"),
1578                    "multi_repo={multi_repo_root} path={path} must require Basic Auth: {resp}"
1579                );
1580                assert!(resp.contains("WWW-Authenticate: Basic realm=\"arks\""));
1581            }
1582            assert_eq!(
1583                page_hits.load(Ordering::SeqCst),
1584                0,
1585                "pages handler must never run before Basic Auth succeeds (multi_repo={multi_repo_root})"
1586            );
1587
1588            // Health and metrics endpoints remain exempt.
1589            for exempt in ["/healthz", "/readyz", "/metrics"] {
1590                let req =
1591                    format!("GET {exempt} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
1592                let resp = raw_http_exchange(addr, &req);
1593                assert!(
1594                    resp.starts_with("HTTP/1.1 200 OK"),
1595                    "exempt endpoint {exempt} must succeed without auth: {resp}"
1596                );
1597            }
1598
1599            // Authenticated request reaches pages cleanly.
1600            let authed_req = format!(
1601                "GET / HTTP/1.1\r\nHost: {addr}\r\nAuthorization: {auth_hdr}\r\nConnection: close\r\n\r\n"
1602            );
1603            let authed_resp = raw_http_exchange(addr, &authed_req);
1604            assert!(
1605                authed_resp.starts_with("HTTP/1.1 200 OK") && authed_resp.contains("page:/"),
1606                "authenticated request must reach pages: {authed_resp}"
1607            );
1608            assert_eq!(page_hits.load(Ordering::SeqCst), 1);
1609
1610            stop.store(true, Ordering::SeqCst);
1611            handle.join().unwrap().unwrap();
1612        }
1613    }
1614
1615    #[test]
1616    fn cross_origin_write_rejected_when_pages_enabled() {
1617        let dir = TempDir::new().unwrap();
1618        seed_empty_bare(dir.path());
1619        let pages: PageHandler = Arc::new(|_req: &HttpRequest| None);
1620        let opts = ServeHttpOptions {
1621            pages: Some(pages.clone()),
1622            ..ServeHttpOptions::default()
1623        };
1624
1625        // Unit-level checks across all mutating Git / LFS / WebDAV verbs.
1626        for (method, path) in [
1627            ("POST", "/git-receive-pack"),
1628            ("POST", "/demo.git/git-receive-pack"),
1629            ("PUT", "/info/lfs/objects/deadbeef"),
1630            ("PUT", "/refs/heads/main"),
1631            ("MOVE", "/objects/ab/cdef"),
1632            ("DELETE", "/refs/heads/topic"),
1633            ("LOCK", "/refs/heads/main"),
1634            ("UNLOCK", "/refs/heads/main"),
1635        ] {
1636            let mut cross = HttpRequest::new(method, path, "", Vec::new());
1637            cross.host = Some("127.0.0.1:8080".into());
1638            cross.origin = Some("https://evil.example".into());
1639            let resp = check_cross_origin_write(&opts, &cross)
1640                .expect("cross-origin mutating write must be rejected");
1641            assert_eq!(resp.status, 403, "{method} {path} must return 403");
1642            assert!(
1643                String::from_utf8_lossy(&resp.body).contains("cross-origin write rejected"),
1644                "{}",
1645                String::from_utf8_lossy(&resp.body)
1646            );
1647
1648            let mut same = cross.clone();
1649            same.origin = Some("http://127.0.0.1:8080".into());
1650            assert!(
1651                check_cross_origin_write(&opts, &same).is_none(),
1652                "same-origin {method} {path} must be allowed"
1653            );
1654
1655            let mut no_origin = cross.clone();
1656            no_origin.origin = None;
1657            assert!(
1658                check_cross_origin_write(&opts, &no_origin).is_none(),
1659                "missing Origin without Sec-Fetch-Site on {method} {path} must be allowed"
1660            );
1661
1662            let mut cross_fetch_site = no_origin.clone();
1663            cross_fetch_site.sec_fetch_site = Some("cross-site".into());
1664            let resp = check_cross_origin_write(&opts, &cross_fetch_site)
1665                .expect("Sec-Fetch-Site: cross-site without Origin must be rejected");
1666            assert_eq!(resp.status, 403, "{method} {path} must return 403");
1667
1668            let mut same_fetch_site = no_origin;
1669            same_fetch_site.sec_fetch_site = Some("same-origin".into());
1670            assert!(
1671                check_cross_origin_write(&opts, &same_fetch_site).is_none(),
1672                "Sec-Fetch-Site: same-origin without Origin on {method} {path} must be allowed"
1673            );
1674        }
1675
1676        // Live loopback enforcement when pages is enabled.
1677        let (addr, stop, handle) =
1678            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
1679        let req = format!(
1680            "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"
1681        );
1682        let resp = raw_http_exchange(addr, &req);
1683        assert!(
1684            resp.starts_with("HTTP/1.1 403 Forbidden")
1685                && resp.contains("cross-origin write rejected"),
1686            "live loopback must reject cross-origin receive-pack with 403: {resp}"
1687        );
1688        stop.store(true, Ordering::SeqCst);
1689        handle.join().unwrap().unwrap();
1690    }
1691
1692    #[test]
1693    fn webdav_writes_require_forge_auth_and_lfs_honors_forwarded_proto_https() {
1694        let dir = TempDir::new().unwrap();
1695        seed_empty_bare(dir.path());
1696
1697        let reader_pat = "arks_pat_reader_test_token";
1698        let reader_hash = {
1699            let digest = Sha256::digest(reader_pat.as_bytes());
1700            let mut s = String::with_capacity(64);
1701            for b in digest {
1702                s.push_str(&format!("{b:02x}"));
1703            }
1704            s
1705        };
1706
1707        let mut store = crate::web_ui::store::ForgeStore::load(dir.path());
1708        store.users.push(crate::web_ui::store::UserAccount {
1709            username: "reader1".into(),
1710            password_hash: "x".into(),
1711            role: "reader".into(),
1712            ssh_keys: Vec::new(),
1713            created_at: 1,
1714            totp_secret_b32: None,
1715            recovery_codes: Vec::new(),
1716            external_ids: Vec::new(),
1717        });
1718        store.pats.push(crate::web_ui::store::PatRecord {
1719            id: 1,
1720            username: "reader1".into(),
1721            name: "read".into(),
1722            token_hash: reader_hash,
1723            prefix: "arks_pat_r".into(),
1724            created_at: 1,
1725            scopes: Vec::new(),
1726            expires_at: None,
1727            last_used_at: None,
1728        });
1729        store.save(dir.path()).unwrap();
1730
1731        let (addr, stop, handle) =
1732            spawn_loopback_with_opts(dir.path().to_path_buf(), ServeHttpOptions::default())
1733                .unwrap();
1734
1735        // Unauthenticated mutating WebDAV verbs must receive 401 when ForgeStore has users.
1736        for (method, path) in [
1737            ("PUT", "/refs/heads/main"),
1738            ("MKCOL", "/objects/ab"),
1739            ("LOCK", "/refs/heads/main"),
1740            ("DELETE", "/refs/heads/main"),
1741        ] {
1742            let req = format!(
1743                "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1744            );
1745            let resp = raw_http_exchange(addr, &req);
1746            assert!(
1747                resp.starts_with("HTTP/1.1 401 Unauthorized"),
1748                "unauthenticated WebDAV {method} {path} must return 401: {resp}"
1749            );
1750        }
1751
1752        // Reader PAT must receive 403 Forbidden on mutating WebDAV writes.
1753        let reader_put = format!(
1754            "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"
1755        );
1756        let reader_resp = raw_http_exchange(addr, &reader_put);
1757        assert!(
1758            reader_resp.starts_with("HTTP/1.1 403 Forbidden"),
1759            "reader role must be denied WebDAV PUT with 403: {reader_resp}"
1760        );
1761
1762        // PROPFIND remains read-only discovery on public repos (207 Multi-Status).
1763        let propfind = format!(
1764            "PROPFIND / HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1765        );
1766        let prop_resp = raw_http_exchange(addr, &propfind);
1767        assert!(
1768            prop_resp.starts_with("HTTP/1.1 207 Multi-Status"),
1769            "PROPFIND discovery on public repo must return 207: {prop_resp}"
1770        );
1771
1772        // Reverse-proxy `X-Forwarded-Proto: https` must produce `https://` LFS batch hrefs.
1773        let batch_body = format!(
1774            r#"{{"operation":"upload","objects":[{{"oid":"{}","size":4}}]}}"#,
1775            "a".repeat(64)
1776        );
1777        let lfs_req = format!(
1778            "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{}",
1779            batch_body.len(),
1780            batch_body
1781        );
1782        let lfs_resp = raw_http_exchange(addr, &lfs_req);
1783        assert!(
1784            lfs_resp.starts_with("HTTP/1.1 200 OK")
1785                && lfs_resp.contains("https://proxy.example.invalid/info/lfs/objects/"),
1786            "LFS batch must honor X-Forwarded-Proto: https: {lfs_resp}"
1787        );
1788
1789        stop.store(true, Ordering::SeqCst);
1790        handle.join().unwrap().unwrap();
1791    }
1792
1793    #[test]
1794    fn slow_post_body_dribble_hits_cumulative_deadline() {
1795        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1796        let addr = listener.local_addr().unwrap();
1797
1798        let client = thread::spawn(move || {
1799            let mut sock = TcpStream::connect(addr).unwrap();
1800            for _ in 0..8 {
1801                if sock.write_all(b"x").is_err() {
1802                    break;
1803                }
1804                thread::sleep(Duration::from_millis(60));
1805            }
1806        });
1807
1808        let (mut srv, _) = listener.accept().unwrap();
1809        let mut buf = Vec::new();
1810        let mut tmp = [0u8; 64];
1811        let completed = read_http_body_with_deadline(
1812            &mut srv,
1813            &mut buf,
1814            &mut tmp,
1815            1024,
1816            Duration::from_millis(200),
1817        )
1818        .unwrap();
1819        assert!(
1820            !completed,
1821            "Slow-POST dribble must time out against cumulative body deadline"
1822        );
1823        drop(srv);
1824        client.join().unwrap();
1825    }
1826
1827    #[test]
1828    fn html_security_headers_applied_to_html_and_excluded_from_git_wire() {
1829        let html_resp = HttpResponse {
1830            status: 200,
1831            content_type: "text/html; charset=utf-8".into(),
1832            body: b"<h1>ok</h1>".to_vec(),
1833            www_authenticate: None,
1834            extra_headers: Vec::new(),
1835        };
1836        let mut wire_http = Vec::new();
1837        write_http_response_with_options(&mut wire_http, &html_resp, false, None).unwrap();
1838        let http_str = String::from_utf8(wire_http).unwrap();
1839        assert!(http_str.contains("Content-Security-Policy: default-src 'self'"));
1840        assert!(http_str.contains("frame-ancestors 'none'"));
1841        assert!(http_str.contains("Permissions-Policy: camera=()"));
1842        assert!(http_str.contains("Cross-Origin-Opener-Policy: same-origin"));
1843        assert!(http_str.contains("Cross-Origin-Resource-Policy: same-origin"));
1844        assert!(http_str.contains("X-Content-Type-Options: nosniff"));
1845        assert!(http_str.contains("X-Frame-Options: DENY"));
1846        assert!(http_str.contains("Referrer-Policy: strict-origin-when-cross-origin"));
1847        assert!(!http_str.contains("upgrade-insecure-requests"));
1848
1849        let mut wire_https = Vec::new();
1850        write_http_response_with_options(&mut wire_https, &html_resp, true, None).unwrap();
1851        let https_str = String::from_utf8(wire_https).unwrap();
1852        assert!(https_str.contains("upgrade-insecure-requests"));
1853        assert!(https_str.contains("Strict-Transport-Security:"));
1854
1855        let git_resp = HttpResponse {
1856            status: 200,
1857            content_type: "application/x-git-upload-pack-advertisement".into(),
1858            body: b"001e# service=git-upload-pack\n0000".to_vec(),
1859            www_authenticate: None,
1860            extra_headers: Vec::new(),
1861        };
1862        let mut wire_git = Vec::new();
1863        write_http_response_with_options(&mut wire_git, &git_resp, false, None).unwrap();
1864        let git_str = String::from_utf8(wire_git).unwrap();
1865        assert!(!git_str.contains("Content-Security-Policy:"));
1866        assert!(!git_str.contains("Permissions-Policy:"));
1867        assert!(!git_str.contains("Cross-Origin-Opener-Policy:"));
1868        assert!(!git_str.contains("X-Frame-Options:"));
1869    }
1870
1871    #[test]
1872    fn head_and_options_semantics_follow_rfc9110() {
1873        let resp = HttpResponse {
1874            status: 200,
1875            content_type: "text/html; charset=utf-8".into(),
1876            body: b"<h1>hello</h1>".to_vec(),
1877            www_authenticate: None,
1878            extra_headers: Vec::new(),
1879        };
1880        let mut head_wire = Vec::new();
1881        write_http_response_full(&mut head_wire, &resp, false, None, true).unwrap();
1882        let head_str = String::from_utf8(head_wire).unwrap();
1883        assert!(head_str.starts_with("HTTP/1.1 200 OK\r\n"));
1884        assert!(head_str.contains("Content-Length: 14\r\n"));
1885        assert!(
1886            head_str.ends_with("\r\n\r\n"),
1887            "HEAD wire response must carry empty body: {head_str}"
1888        );
1889
1890        let dir = TempDir::new().unwrap();
1891        seed_empty_bare(dir.path());
1892        let repo_dir = dir.path().to_path_buf();
1893        let pages: PageHandler =
1894            Arc::new(move |req: &HttpRequest| crate::web_ui::handle_web_ui(&repo_dir, req));
1895        let opts = ServeHttpOptions {
1896            pages: Some(pages),
1897            ..ServeHttpOptions::default()
1898        };
1899        let (addr, stop, handle) =
1900            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
1901
1902        let head_health = raw_http_exchange(
1903            addr,
1904            "HEAD /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1905        );
1906        assert!(head_health.starts_with("HTTP/1.1 200 OK\r\n"));
1907        assert!(head_health.ends_with("\r\n\r\n"));
1908
1909        let opt_health = raw_http_exchange(
1910            addr,
1911            "OPTIONS /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1912        );
1913        assert!(opt_health.starts_with("HTTP/1.1 204 No Content\r\n"));
1914        assert!(opt_health.contains("Allow: GET, HEAD, OPTIONS\r\n"));
1915
1916        let head_root = raw_http_exchange(
1917            addr,
1918            "HEAD / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1919        );
1920        assert!(head_root.starts_with("HTTP/1.1 200 OK\r\n"), "{head_root}");
1921        assert!(head_root.ends_with("\r\n\r\n"));
1922
1923        let opt_root = raw_http_exchange(
1924            addr,
1925            "OPTIONS / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1926        );
1927        assert!(
1928            opt_root.starts_with("HTTP/1.1 204 No Content\r\n"),
1929            "{opt_root}"
1930        );
1931        assert!(
1932            opt_root.contains("Allow: GET, HEAD, OPTIONS\r\n"),
1933            "{opt_root}"
1934        );
1935
1936        stop.store(true, Ordering::SeqCst);
1937        handle.join().unwrap().unwrap();
1938    }
1939
1940    #[test]
1941    fn livez_readyz_and_gated_metrics_follow_o2() {
1942        let dir = TempDir::new().unwrap();
1943        seed_empty_bare(dir.path());
1944        let shutdown_flag = Arc::new(AtomicBool::new(false));
1945        let opts = ServeHttpOptions {
1946            shutdown_flag: Some(shutdown_flag.clone()),
1947            metrics_token: Some("secret-metrics-tok".into()),
1948            metrics_require_token: true,
1949            ..ServeHttpOptions::default()
1950        };
1951        let (addr, stop, handle) =
1952            spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
1953
1954        let live = raw_http_exchange(
1955            addr,
1956            "GET /livez HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1957        );
1958        assert!(live.starts_with("HTTP/1.1 200 OK\r\n"), "{live}");
1959        assert!(live.contains("\"alive\""));
1960
1961        let ready_ok = raw_http_exchange(
1962            addr,
1963            "GET /readyz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1964        );
1965        assert!(ready_ok.starts_with("HTTP/1.1 200 OK\r\n"), "{ready_ok}");
1966
1967        // Metrics without token -> 404 when gated.
1968        let met_denied = raw_http_exchange(
1969            addr,
1970            "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1971        );
1972        assert!(
1973            met_denied.starts_with("HTTP/1.1 404 Not Found\r\n"),
1974            "{met_denied}"
1975        );
1976
1977        // Metrics with valid Bearer token -> 200 with full Prometheus series.
1978        let met_ok = raw_http_exchange(
1979            addr,
1980            "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer secret-metrics-tok\r\nConnection: close\r\n\r\n",
1981        );
1982        assert!(met_ok.starts_with("HTTP/1.1 200 OK\r\n"), "{met_ok}");
1983        assert!(met_ok.contains("arks_git_upload_pack_total"));
1984        assert!(met_ok.contains("arks_git_receive_pack_total"));
1985        assert!(met_ok.contains("arks_lfs_bytes_total"));
1986        assert!(met_ok.contains("arks_build_info{version="));
1987
1988        // Flipping shutdown_flag makes /readyz return 503 while /livez stays 200.
1989        shutdown_flag.store(true, Ordering::SeqCst);
1990        let ready_down = raw_http_exchange(
1991            addr,
1992            "GET /readyz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
1993        );
1994        assert!(
1995            ready_down.starts_with("HTTP/1.1 503 Service Unavailable\r\n"),
1996            "{ready_down}"
1997        );
1998        assert!(ready_down.contains("shutting_down"));
1999
2000        let live_still = raw_http_exchange(
2001            addr,
2002            "GET /livez HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
2003        );
2004        assert!(live_still.starts_with("HTTP/1.1 200 OK\r\n"));
2005
2006        stop.store(true, Ordering::SeqCst);
2007        handle.join().unwrap().unwrap();
2008    }
2009
2010    #[test]
2011    fn gzip_compression_applies_to_html_and_excludes_git_wire() {
2012        let html_body = "<div>".to_string() + &"hello arks ".repeat(300) + "</div>";
2013        let mut html_resp = HttpResponse {
2014            status: 200,
2015            content_type: "text/html; charset=utf-8".into(),
2016            body: html_body.as_bytes().to_vec(),
2017            www_authenticate: None,
2018            extra_headers: vec![("Vary".into(), "HX-Request, Cookie".into())],
2019        };
2020        let req = HttpRequest::new("GET", "/issues", "", Vec::new())
2021            .with_header("Accept-Encoding", "gzip, deflate");
2022        maybe_gzip_response(&mut html_resp, &req);
2023        assert!(
2024            html_resp
2025                .extra_headers
2026                .contains(&("Content-Encoding".into(), "gzip".into()))
2027        );
2028        assert!(html_resp.body.len() < html_body.len());
2029        let mut dec = flate2::read::GzDecoder::new(html_resp.body.as_slice());
2030        let mut roundtrip = String::new();
2031        dec.read_to_string(&mut roundtrip).unwrap();
2032        assert_eq!(roundtrip, html_body);
2033
2034        // Git wire path must NEVER be gzipped.
2035        let mut git_resp = HttpResponse {
2036            status: 200,
2037            content_type: "text/plain".into(),
2038            body: vec![b'a'; 4096],
2039            www_authenticate: None,
2040            extra_headers: Vec::new(),
2041        };
2042        let git_req = HttpRequest::new("GET", "/repo.git/info/refs", "", Vec::new())
2043            .with_header("Accept-Encoding", "gzip");
2044        maybe_gzip_response(&mut git_resp, &git_req);
2045        assert!(
2046            !git_resp
2047                .extra_headers
2048                .iter()
2049                .any(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
2050        );
2051    }
2052}