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