use crate::auth::BasicAuthConfig;
use crate::error::ServerError;
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use arks_repo::Repository;
use rustls::ServerConfig;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
static HTTP_REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
static HTTP_ACTIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
static GIT_UPLOAD_PACK_TOTAL: AtomicU64 = AtomicU64::new(0);
static GIT_RECEIVE_PACK_TOTAL: AtomicU64 = AtomicU64::new(0);
static LFS_BYTES_TOTAL: AtomicU64 = AtomicU64::new(0);
static SERVER_START: OnceLock<Instant> = OnceLock::new();
static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);
pub fn mark_shutting_down() {
SHUTTING_DOWN.store(true, Ordering::SeqCst);
}
pub fn is_shutting_down() -> bool {
SHUTTING_DOWN.load(Ordering::SeqCst)
}
fn check_server_readiness(git_dir: &Path, opts: &ServeHttpOptions) -> Result<(), &'static str> {
if is_shutting_down()
|| opts
.shutdown_flag
.as_ref()
.is_some_and(|f| f.load(Ordering::SeqCst))
{
return Err("shutting_down");
}
let meta = std::fs::metadata(git_dir).map_err(|_| "data_dir_missing")?;
if !meta.is_dir() || meta.permissions().readonly() {
return Err("data_dir_unwritable");
}
if !opts.multi_repo_root {
let store = crate::web_ui::store::ForgeStore::load_shared(git_dir);
if store.corrupt {
return Err("store_corrupt");
}
}
Ok(())
}
fn metrics_authorized(
peer_ip: std::net::IpAddr,
authorization: Option<&str>,
opts: &ServeHttpOptions,
) -> bool {
use subtle::ConstantTimeEq as _;
let token = opts
.metrics_token
.clone()
.or_else(|| crate::ops::resolve_secret_env("ARKS_METRICS_TOKEN"))
.filter(|t| !t.trim().is_empty());
if let (Some(expected), Some(auth)) = (token.as_deref(), authorization) {
if let Some(presented) = auth
.strip_prefix("Bearer ")
.or_else(|| auth.strip_prefix("bearer "))
{
let a = expected.as_bytes();
let b = presented.trim().as_bytes();
if a.len() == b.len() && bool::from(a.ct_eq(b)) {
return true;
}
}
}
peer_ip.is_loopback() && !opts.metrics_require_token
}
fn max_http_body_bytes() -> usize {
std::env::var("ARKS_HTTP_MAX_BODY_BYTES")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
.filter(|&n| n > 0)
.unwrap_or(64 * 1024 * 1024)
}
fn max_http_concurrency() -> usize {
std::env::var("ARKS_HTTP_MAX_CONCURRENCY")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
.filter(|&n| n > 0)
.unwrap_or(128)
}
fn max_http_header_timeout() -> Duration {
let secs = std::env::var("ARKS_HTTP_HEADER_TIMEOUT_SECS")
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
.filter(|&n| n > 0)
.unwrap_or(10);
Duration::from_secs(secs)
}
fn max_http_body_timeout() -> Duration {
let secs = std::env::var("ARKS_HTTP_BODY_TIMEOUT_SECS")
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
.filter(|&n| n > 0)
.unwrap_or(60);
Duration::from_secs(secs)
}
pub(crate) fn is_transient_accept_error(err: &std::io::Error) -> bool {
if matches!(
err.kind(),
std::io::ErrorKind::WouldBlock
| std::io::ErrorKind::Interrupted
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::ConnectionReset
) {
return true;
}
#[cfg(unix)]
{
if matches!(err.raw_os_error(), Some(12 | 23 | 24 | 55 | 105)) {
return true;
}
}
#[cfg(windows)]
{
if matches!(err.raw_os_error(), Some(10024 | 10054 | 10055)) {
return true;
}
}
false
}
pub(crate) struct ActiveConnGuard;
impl Drop for ActiveConnGuard {
fn drop(&mut self) {
HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Release);
}
}
pub(crate) fn try_reserve_http_slot_with_limit(limit: usize) -> Option<ActiveConnGuard> {
let mut cur = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire);
loop {
if cur >= limit {
return None;
}
match HTTP_ACTIVE_CONNECTIONS.compare_exchange_weak(
cur,
cur + 1,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return Some(ActiveConnGuard),
Err(observed) => cur = observed,
}
}
}
fn try_reserve_http_slot() -> Option<ActiveConnGuard> {
try_reserve_http_slot_with_limit(max_http_concurrency())
}
#[allow(dead_code)]
pub fn active_http_connections() -> usize {
HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire)
}
type LoopbackHttp = (
SocketAddr,
Arc<AtomicBool>,
thread::JoinHandle<Result<(), ServerError>>,
);
pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
#[derive(Clone, Default)]
pub struct ServeHttpOptions {
pub dumb_only: bool,
pub basic_auth: Option<BasicAuthConfig>,
pub rebind_desired: Option<ListenRebindSlot>,
pub tls: Option<Arc<ServerConfig>>,
pub pages: Option<PageHandler>,
pub disable_lfs: bool,
pub multi_repo_root: bool,
pub header_timeout: Option<Duration>,
pub trusted_proxies: Option<crate::proxy::TrustedProxyConfig>,
pub shutdown_flag: Option<Arc<AtomicBool>>,
pub metrics_token: Option<String>,
pub metrics_require_token: bool,
pub github_app_webhook: Option<Arc<crate::github_app_webhook::GithubAppWebhookState>>,
}
impl std::fmt::Debug for ServeHttpOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServeHttpOptions")
.field("dumb_only", &self.dumb_only)
.field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
.field("rebind_desired", &self.rebind_desired.is_some())
.field("tls", &self.tls.is_some())
.field("pages", &self.pages.is_some())
.field("disable_lfs", &self.disable_lfs)
.field("multi_repo_root", &self.multi_repo_root)
.field("header_timeout", &self.header_timeout)
.field("trusted_proxies", &self.trusted_proxies.is_some())
.field("shutdown_flag", &self.shutdown_flag.is_some())
.field("metrics_token", &self.metrics_token.is_some())
.field("metrics_require_token", &self.metrics_require_token)
.field("github_app_webhook", &self.github_app_webhook.is_some())
.finish()
}
}
pub fn serve_http(
git_dir: impl AsRef<Path>,
addr: SocketAddr,
stop: Arc<AtomicBool>,
) -> Result<(), ServerError> {
serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
}
pub fn serve_http_with_opts(
git_dir: impl AsRef<Path>,
addr: SocketAddr,
stop: Arc<AtomicBool>,
opts: ServeHttpOptions,
) -> Result<(), ServerError> {
let git_dir = git_dir.as_ref().to_path_buf();
let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
let mut listener = TcpListener::bind(addr)?;
listener.set_nonblocking(true)?;
let mut current = addr;
let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
let mut last_accept_err_log: Option<Instant> = None;
while !stop.load(Ordering::SeqCst) {
if let Some(slot) = &opts.rebind_desired {
if let Ok(mut g) = slot.lock() {
if let Some(new_addr) = g.take() {
if new_addr != current {
match TcpListener::bind(new_addr) {
Ok(l) => {
if let Err(e) = l.set_nonblocking(true) {
eprintln!(
"arks serve-http: live rebind Partial bind ok but \
nonblocking fail ({e}); keeping {current}"
);
*g = Some(new_addr);
} else {
eprintln!(
"arks serve-http: live rebind dual-bind {current} → {new_addr}; \
prior listener draining for 5s"
);
let old = std::mem::replace(&mut listener, l);
draining.push((
old,
current,
Instant::now() + Duration::from_secs(5),
));
current = new_addr;
}
}
Err(e) => {
eprintln!(
"arks serve-http: live rebind Partial fail {current} → \
{new_addr} ({e}); keeping prior listen"
);
}
}
}
}
}
}
draining.retain(|(_, old_addr, deadline)| {
if Instant::now() < *deadline {
true
} else {
eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
false
}
});
match listener.accept() {
Ok((stream, _)) => {
dispatch_accepted_stream(stream, &git_dir, &opts);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(std::time::Duration::from_millis(1));
}
Err(e) if is_transient_accept_error(&e) => {
if last_accept_err_log
.map(|t| t.elapsed() >= Duration::from_secs(1))
.unwrap_or(true)
{
eprintln!(
"arks serve-http: transient accept error on {current} ({e}); backing off"
);
last_accept_err_log = Some(Instant::now());
}
thread::sleep(std::time::Duration::from_millis(25));
}
Err(e) => return Err(e.into()),
}
for (old_listener, _, _) in &draining {
match old_listener.accept() {
Ok((stream, _)) => {
dispatch_accepted_stream(stream, &git_dir, &opts);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => {
if last_accept_err_log
.map(|t| t.elapsed() >= Duration::from_secs(1))
.unwrap_or(true)
{
eprintln!("arks serve-http: draining listener accept error: {e}");
last_accept_err_log = Some(Instant::now());
}
}
}
}
}
drop(listener);
drop(draining);
let drain_secs = std::env::var("ARKS_SHUTDOWN_GRACE_SECS")
.or_else(|_| std::env::var("ARKS_SHUTDOWN_DRAIN_SECS"))
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
.unwrap_or(30);
let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
while active_http_connections() > 0 && Instant::now() < drain_deadline {
thread::sleep(Duration::from_millis(25));
}
Ok(())
}
pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
}
pub fn spawn_loopback_with_opts(
git_dir: PathBuf,
opts: ServeHttpOptions,
) -> Result<LoopbackHttp, ServerError> {
let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
let listener = TcpListener::bind("127.0.0.1:0")?;
let addr = listener.local_addr()?;
listener.set_nonblocking(true)?;
let stop = Arc::new(AtomicBool::new(false));
let stop2 = stop.clone();
let handle = thread::spawn(move || {
let mut last_accept_err_log: Option<Instant> = None;
while !stop2.load(Ordering::SeqCst) {
match listener.accept() {
Ok((stream, _)) => {
dispatch_accepted_stream(stream, &git_dir, &opts);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(std::time::Duration::from_millis(1));
}
Err(e) if is_transient_accept_error(&e) => {
if last_accept_err_log
.map(|t| t.elapsed() >= Duration::from_secs(1))
.unwrap_or(true)
{
eprintln!(
"arks serve-http: transient loopback accept error ({e}); backing off"
);
last_accept_err_log = Some(Instant::now());
}
thread::sleep(std::time::Duration::from_millis(25));
}
Err(e) => return Err(e.into()),
}
}
Ok(())
});
Ok((addr, stop, handle))
}
fn send_fast_503(stream: &mut TcpStream) {
let _ = stream.set_nonblocking(false);
let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
let resp = HttpResponse {
status: 503,
content_type: "text/plain; charset=utf-8".into(),
body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Retry-After".into(), "1".into())],
};
let _ = write_http_response(stream, &resp);
let _ = stream.shutdown(std::net::Shutdown::Write);
}
fn send_fast_408_with_reason<S: HttpStream>(stream: &mut S, reason: &'static [u8]) {
let resp = HttpResponse {
status: 408,
content_type: "text/plain; charset=utf-8".into(),
body: reason.to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
let _ = write_http_response(stream, &resp);
stream.shutdown_write();
}
fn send_fast_408<S: HttpStream>(stream: &mut S) {
send_fast_408_with_reason(stream, b"Request Timeout: HTTP header deadline exceeded\n");
}
fn read_http_body_with_deadline<S: HttpStream>(
stream: &mut S,
buf: &mut Vec<u8>,
tmp: &mut [u8],
total_needed: usize,
body_timeout: Duration,
) -> Result<bool, ServerError> {
if buf.len() >= total_needed {
return Ok(true);
}
let body_deadline = Instant::now() + body_timeout;
while buf.len() < total_needed {
let now = Instant::now();
if now >= body_deadline {
return Ok(false);
}
let rem = body_deadline
.saturating_duration_since(now)
.max(Duration::from_millis(1));
stream.set_stream_read_timeout(rem);
match stream.read(tmp) {
Ok(0) => break,
Ok(n) => {
buf.extend_from_slice(&tmp[..n]);
if buf.len() < total_needed && Instant::now() >= body_deadline {
return Ok(false);
}
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) =>
{
return Ok(false);
}
Err(e) => return Err(e.into()),
}
}
Ok(true)
}
fn is_mutating_git_lfs_dav_request(req: &HttpRequest) -> bool {
let method = req.method.to_ascii_uppercase();
let is_receive_pack =
req.path.ends_with("/git-receive-pack") || req.path.contains("/git-receive-pack");
if is_receive_pack && !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS") {
return true;
}
if crate::lfs::is_lfs_path(&req.path) && method == "PUT" {
return true;
}
matches!(
method.as_str(),
"PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
)
}
pub(crate) fn check_cross_origin_write(
opts: &ServeHttpOptions,
req: &HttpRequest,
) -> Option<HttpResponse> {
if opts.pages.is_none() || !is_mutating_git_lfs_dav_request(req) {
return None;
}
let Some(origin) = req
.origin
.as_deref()
.map(str::trim)
.filter(|o| !o.is_empty())
else {
if req
.sec_fetch_site
.as_deref()
.is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
{
return Some(HttpResponse {
status: 403,
content_type: "text/plain; charset=utf-8".into(),
body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
});
}
return None;
};
let origin_host = origin
.strip_prefix("http://")
.or_else(|| origin.strip_prefix("https://"))
.unwrap_or(origin)
.split('/')
.next()
.unwrap_or("")
.trim();
let matches_host = req
.host
.as_deref()
.map(str::trim)
.filter(|h| !h.is_empty())
.is_some_and(|h| origin_host.eq_ignore_ascii_case(h));
if matches_host {
None
} else {
Some(HttpResponse {
status: 403,
content_type: "text/plain; charset=utf-8".into(),
body: b"403 Forbidden: cross-origin write rejected\n".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
})
}
}
fn dispatch_accepted_stream(mut stream: TcpStream, git_dir: &Path, opts: &ServeHttpOptions) {
let Some(guard) = try_reserve_http_slot() else {
send_fast_503(&mut stream);
return;
};
let dir = git_dir.to_path_buf();
let opts = opts.clone();
if let Err(e) = thread::Builder::new()
.name("arks-http-worker".into())
.spawn(move || {
let _ = handle_connection(stream, &dir, &opts, guard);
})
{
eprintln!("arks serve-http: worker thread spawn failed ({e}); rejecting connection");
thread::sleep(Duration::from_millis(10));
}
}
pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
if opts.tls.is_some() { "https" } else { "http" }
}
const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
const KEEP_ALIVE_IDLE_SECS: u64 = 5;
trait HttpStream: Read + Write {
fn set_stream_read_timeout(&mut self, timeout: Duration);
fn shutdown_write(&mut self);
}
impl HttpStream for TcpStream {
fn set_stream_read_timeout(&mut self, timeout: Duration) {
let _ = self.set_read_timeout(Some(timeout));
}
fn shutdown_write(&mut self) {
let _ = self.shutdown(std::net::Shutdown::Write);
}
}
impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
fn set_stream_read_timeout(&mut self, timeout: Duration) {
let _ = self.sock.set_read_timeout(Some(timeout));
}
fn shutdown_write(&mut self) {
let _ = self.sock.shutdown(std::net::Shutdown::Write);
}
}
fn handle_connection(
mut stream: TcpStream,
git_dir: &Path,
opts: &ServeHttpOptions,
_guard: ActiveConnGuard,
) -> Result<(), ServerError> {
let _ = SERVER_START.get_or_init(Instant::now);
stream.set_nonblocking(false)?;
let _ = stream.set_nodelay(true);
stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
let peer_ip = stream
.peer_addr()
.map(|a| a.ip())
.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
if let Some(tls_cfg) = &opts.tls {
let conn = rustls::ServerConnection::new(tls_cfg.clone())
.map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
let mut tls = rustls::StreamOwned::new(conn, stream);
tls.conn
.complete_io(&mut tls.sock)
.map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
handle_connection_io(&mut tls, peer_ip, git_dir, opts)
} else {
handle_connection_io(&mut stream, peer_ip, git_dir, opts)
}
}
fn handle_connection_io<S: HttpStream>(
stream: &mut S,
peer_ip: std::net::IpAddr,
git_dir: &Path,
opts: &ServeHttpOptions,
) -> Result<(), ServerError> {
let mut buf = Vec::with_capacity(4096);
let mut tmp = [0u8; 8192];
let header_timeout = opts.header_timeout.unwrap_or_else(max_http_header_timeout);
for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
let mut header_deadline = if req_idx == 0 {
Some(Instant::now() + header_timeout)
} else {
stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
None
};
let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
while header_end.is_none() {
if let Some(dl) = header_deadline {
let now = Instant::now();
if now >= dl {
send_fast_408(stream);
return Ok(());
}
let rem = dl
.saturating_duration_since(now)
.max(Duration::from_millis(1));
stream.set_stream_read_timeout(rem);
}
let prev_len = buf.len();
match stream.read(&mut tmp) {
Ok(0) => {
if req_idx > 0 && buf.is_empty() {
return Ok(());
}
break;
}
Ok(n) => {
if header_deadline.is_none() {
header_deadline = Some(Instant::now() + header_timeout);
}
buf.extend_from_slice(&tmp[..n]);
let search_from = prev_len.saturating_sub(3);
if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
{
header_end = Some(search_from + rel);
break;
}
if buf.len() > 1024 * 1024 {
return Err(ServerError::Protocol("headers too large".into()));
}
if header_deadline.is_some_and(|dl| Instant::now() >= dl) {
send_fast_408(stream);
return Ok(());
}
}
Err(e)
if req_idx > 0
&& buf.is_empty()
&& matches!(
e.kind(),
std::io::ErrorKind::WouldBlock
| std::io::ErrorKind::TimedOut
| std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::UnexpectedEof
) =>
{
return Ok(());
}
Err(e)
if header_deadline.is_some()
&& matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) =>
{
send_fast_408(stream);
return Ok(());
}
Err(e) => return Err(e.into()),
}
}
let Some(header_end) = header_end else {
if req_idx > 0 && buf.is_empty() {
return Ok(());
}
return Err(ServerError::Protocol("incomplete headers".into()));
};
stream.set_stream_read_timeout(Duration::from_secs(30));
HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
let header_bytes = &buf[..header_end];
let header_text = std::str::from_utf8(header_bytes)
.map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
let mut lines = header_text.split("\r\n");
let request_line = lines
.next()
.ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
let mut parts = request_line.split_whitespace();
let method = parts
.next()
.ok_or_else(|| ServerError::Protocol("bad request line".into()))?
.to_string();
let target = parts
.next()
.ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
let http_version = parts.next().unwrap_or("HTTP/1.1");
let (path, query) = match target.split_once('?') {
Some((p, q)) => (p.to_string(), q.to_string()),
None => (target.to_string(), String::new()),
};
let mut content_length_opt: Option<usize> = None;
let mut has_transfer_encoding = false;
let mut header_smuggle_error: Option<&'static str> = None;
let mut expect_continue = false;
let mut content_encoding = String::new();
let mut connection_close = false;
let mut connection_keep_alive = false;
let mut git_protocol = None;
let mut authorization = None;
let mut destination = None;
let mut lock_token = None;
let mut host = None;
let mut cookie = None;
let mut origin = None;
let mut forwarded_proto = None;
let mut sec_fetch_site = None;
let mut headers: Vec<(String, String)> = Vec::new();
for line in lines {
if let Some((k, v)) = line.split_once(':') {
let key = k.trim();
if !key.is_empty() && headers.len() < 128 {
headers.push((key.to_ascii_lowercase(), v.trim().to_string()));
}
}
let lower = line.to_ascii_lowercase();
if let Some(v) = lower.strip_prefix("content-length:") {
match v.trim().parse::<usize>() {
Ok(parsed) => {
if let Some(prev) = content_length_opt {
if prev != parsed {
header_smuggle_error = Some("conflicting Content-Length headers");
}
} else {
content_length_opt = Some(parsed);
}
}
Err(_) => {
header_smuggle_error = Some("invalid Content-Length header");
}
}
}
if lower.starts_with("transfer-encoding:") {
has_transfer_encoding = true;
}
if let Some(v) = lower.strip_prefix("connection:") {
if v.contains("close") {
connection_close = true;
}
if v.contains("keep-alive") {
connection_keep_alive = true;
}
}
if lower.starts_with("host:") {
if let Some((_, v)) = line.split_once(':') {
host = Some(v.trim().to_string());
}
}
if lower.starts_with("cookie:") {
if let Some((_, v)) = line.split_once(':') {
cookie = Some(v.trim().to_string());
}
}
if lower.starts_with("origin:") {
if let Some((_, v)) = line.split_once(':') {
origin = Some(v.trim().to_string());
}
}
if lower.starts_with("x-forwarded-proto:") {
if let Some((_, v)) = line.split_once(':') {
forwarded_proto = Some(v.trim().to_string());
}
}
if lower.starts_with("sec-fetch-site:") {
if let Some((_, v)) = line.split_once(':') {
sec_fetch_site = Some(v.trim().to_string());
}
}
if lower.starts_with("expect:") && lower.contains("100-continue") {
expect_continue = true;
}
if let Some(v) = lower.strip_prefix("content-encoding:") {
content_encoding = v.trim().to_string();
}
if lower.starts_with("git-protocol:") {
if let Some((_, v)) = line.split_once(':') {
git_protocol = Some(v.trim().to_string());
}
}
if lower.starts_with("authorization:") {
if let Some((_, v)) = line.split_once(':') {
authorization = Some(v.trim().to_string());
}
}
if lower.starts_with("destination:") {
if let Some((_, v)) = line.split_once(':') {
destination = Some(v.trim().to_string());
}
}
if lower.starts_with("lock-token:") {
if let Some((_, v)) = line.split_once(':') {
lock_token = Some(v.trim().to_string());
}
}
if lower.starts_with("if:") && lock_token.is_none() {
if let Some((_, v)) = line.split_once(':') {
let v = v.trim();
if let Some(start) = v.find("opaquelocktoken:") {
let rest = &v[start..];
let end = rest
.find(|c: char| c == ')' || c == '>' || c.is_whitespace())
.unwrap_or(rest.len());
lock_token = Some(rest[..end].to_string());
}
}
}
}
if header_smuggle_error.is_none() && has_transfer_encoding && content_length_opt.is_some() {
header_smuggle_error = Some("ambiguous Transfer-Encoding and Content-Length headers");
}
if let Some(reason) = header_smuggle_error {
let resp = HttpResponse {
status: 400,
content_type: "text/plain; charset=utf-8".into(),
body: format!("Bad Request: {reason}\n").into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
};
return write_http_response(stream, &resp);
}
let content_length = content_length_opt.unwrap_or(0);
let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
connection_keep_alive && !connection_close
} else {
!connection_close
};
let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
} else {
None
};
let body_start = header_end + 4;
let is_head = method == "HEAD";
if path == "/livez" {
let resp = if method == "OPTIONS" {
HttpResponse {
status: 204,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Allow".into(), "GET, HEAD, OPTIONS".into()),
("Cache-Control".into(), "no-store".into()),
],
}
} else {
HttpResponse {
status: 200,
content_type: "application/json; charset=utf-8".into(),
body: b"{\"status\":\"alive\"}\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Cache-Control".into(), "no-store".into())],
}
};
buf.drain(..body_start.min(buf.len()));
write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
if keep_alive_rem.is_some() {
continue;
}
return Ok(());
}
if path == "/healthz" || path == "/readyz" {
let resp = if method == "OPTIONS" {
HttpResponse {
status: 204,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Allow".into(), "GET, HEAD, OPTIONS".into()),
("Cache-Control".into(), "no-store".into()),
],
}
} else {
match check_server_readiness(git_dir, opts) {
Ok(()) => HttpResponse {
status: 200,
content_type: "application/json; charset=utf-8".into(),
body: b"{\"status\":\"ok\"}\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Cache-Control".into(), "no-store".into())],
},
Err(reason) => HttpResponse {
status: 503,
content_type: "application/json; charset=utf-8".into(),
body: format!("{{\"status\":\"not_ready\",\"reason\":\"{reason}\"}}\n")
.into_bytes(),
www_authenticate: None,
extra_headers: vec![("Cache-Control".into(), "no-store".into())],
},
}
};
buf.drain(..body_start.min(buf.len()));
write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
if keep_alive_rem.is_some() {
continue;
}
return Ok(());
}
if path == "/metrics" {
let resp = if !metrics_authorized(peer_ip, authorization.as_deref(), opts) {
HttpResponse {
status: 404,
content_type: "text/plain; charset=utf-8".into(),
body: b"not found\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Cache-Control".into(), "no-store".into())],
}
} else if method == "OPTIONS" {
HttpResponse {
status: 204,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Allow".into(), "GET, HEAD, OPTIONS".into()),
("Cache-Control".into(), "no-store".into()),
],
}
} else {
let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
let upload = GIT_UPLOAD_PACK_TOTAL.load(Ordering::Relaxed);
let receive = GIT_RECEIVE_PACK_TOTAL.load(Ordering::Relaxed);
let lfs_bytes = LFS_BYTES_TOTAL.load(Ordering::Relaxed);
let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
let ver = env!("CARGO_PKG_VERSION");
let metrics = format!(
"# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
# TYPE arks_http_requests_total counter\n\
arks_http_requests_total {total}\n\
# HELP arks_http_active_connections Currently active HTTP worker connections.\n\
# TYPE arks_http_active_connections gauge\n\
arks_http_active_connections {active}\n\
# HELP arks_uptime_seconds Server process uptime in seconds.\n\
# TYPE arks_uptime_seconds gauge\n\
arks_uptime_seconds {uptime}\n\
# HELP arks_git_upload_pack_total Total Git upload-pack RPC requests.\n\
# TYPE arks_git_upload_pack_total counter\n\
arks_git_upload_pack_total {upload}\n\
# HELP arks_git_receive_pack_total Total Git receive-pack RPC requests.\n\
# TYPE arks_git_receive_pack_total counter\n\
arks_git_receive_pack_total {receive}\n\
# HELP arks_lfs_bytes_total Total Git LFS bytes transferred.\n\
# TYPE arks_lfs_bytes_total counter\n\
arks_lfs_bytes_total {lfs_bytes}\n\
# HELP arks_build_info Build version information.\n\
# TYPE arks_build_info gauge\n\
arks_build_info{{version=\"{ver}\"}} 1\n"
);
HttpResponse {
status: 200,
content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
body: metrics.into_bytes(),
www_authenticate: None,
extra_headers: vec![("Cache-Control".into(), "no-store".into())],
}
};
buf.drain(..body_start.min(buf.len()));
write_http_response_full(stream, &resp, opts.tls.is_some(), keep_alive_rem, is_head)?;
if keep_alive_rem.is_some() {
continue;
}
return Ok(());
}
let max_body = max_http_body_bytes();
if content_length > max_body {
let resp = HttpResponse {
status: 413,
content_type: "text/plain; charset=utf-8".into(),
body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
};
return write_http_response(stream, &resp);
}
if expect_continue && content_length > 0 {
if let Some(cfg) = &opts.basic_auth
&& !cfg.check_authorization(authorization.as_deref())
{
let resp = HttpResponse {
status: 401,
content_type: "text/plain; charset=utf-8".into(),
body: b"unauthorized\n".to_vec(),
www_authenticate: Some(cfg.challenge_header()),
extra_headers: Vec::new(),
};
return write_http_response(stream, &resp);
}
stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
stream.flush()?;
}
let total_needed = body_start.saturating_add(content_length);
if !read_http_body_with_deadline(
stream,
&mut buf,
&mut tmp,
total_needed,
max_http_body_timeout(),
)? {
send_fast_408_with_reason(stream, b"Request Timeout: HTTP body deadline exceeded\n");
return Ok(());
}
let avail_end = total_needed.min(buf.len());
let mut body = buf[body_start..avail_end].to_vec();
buf.drain(..avail_end);
let is_lfs = crate::lfs::is_lfs_path(&path);
let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
if content_encoding.contains("gzip") || gzip_magic {
use flate2::read::GzDecoder;
use std::io::Read as _;
let decoder = GzDecoder::new(body.as_slice());
let mut decoded = Vec::new();
decoder
.take((max_body as u64).saturating_add(1))
.read_to_end(&mut decoded)
.map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
if decoded.len() > max_body {
let resp = HttpResponse {
status: 413,
content_type: "text/plain; charset=utf-8".into(),
body: format!(
"Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
)
.into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
};
return write_http_response(stream, &resp);
}
body = decoded;
}
let proxy_cfg = opts
.trusted_proxies
.clone()
.unwrap_or_else(crate::proxy::TrustedProxyConfig::from_env);
headers.retain(|(k, _)| !k.eq_ignore_ascii_case("x-arks-client-ip"));
let resolved = crate::proxy::resolve_client(peer_ip, &headers, &proxy_cfg);
headers.push(("x-arks-client-ip".into(), resolved.ip.to_string()));
let effective_host = resolved.host.or(host);
let effective_proto = resolved.proto.or_else(|| {
if opts.tls.is_some() {
Some("https".into())
} else {
None
}
});
let _ = forwarded_proto;
let mut req = HttpRequest {
method,
path: path.clone(),
query: query.clone(),
body,
git_protocol,
authorization,
destination,
lock_token,
host: effective_host,
cookie,
origin,
forwarded_proto: effective_proto,
sec_fetch_site,
headers,
};
if req.path.contains("/git-upload-pack") {
GIT_UPLOAD_PACK_TOTAL.fetch_add(1, Ordering::Relaxed);
} else if req.path.contains("/git-receive-pack") {
GIT_RECEIVE_PACK_TOTAL.fetch_add(1, Ordering::Relaxed);
} else if is_lfs {
LFS_BYTES_TOTAL.fetch_add(req.body.len() as u64, Ordering::Relaxed);
}
let resp = if let Some(gh) = &opts.github_app_webhook
&& req.path == gh.config.webhook_path
{
crate::github_app_webhook::handle_github_app_webhook(
gh,
&req.method,
&req.headers,
&req.body,
)
} else if let Some(cfg) = &opts.basic_auth
&& !cfg.check_authorization(req.authorization.as_deref())
{
HttpResponse {
status: 401,
content_type: "text/plain; charset=utf-8".into(),
body: b"unauthorized\n".to_vec(),
www_authenticate: Some(cfg.challenge_header()),
extra_headers: Vec::new(),
}
} else if let Some(forbidden) = check_cross_origin_write(opts, &req) {
forbidden
} else if opts.multi_repo_root {
match opts.pages.as_ref().and_then(|p| p(&req)) {
Some(r) => r,
None => HttpResponse {
status: 404,
content_type: "text/plain; charset=utf-8".into(),
body: b"repository or path not found\n".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
},
}
} else {
let mut repo =
Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
if opts.dumb_only
&& (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
{
req.query = String::new();
}
let is_git_rpc = req.path.contains("/git-upload-pack")
|| req.path.contains("/git-receive-pack")
|| req.path.contains("/info/refs");
let page = match &opts.pages {
Some(pages)
if matches!(
req.method.as_str(),
"GET" | "HEAD" | "OPTIONS" | "POST" | "PATCH" | "DELETE"
) && !is_lfs
&& !is_git_rpc =>
{
pages(&req)
}
_ => None,
};
let scheme = if req.is_https() || opts.tls.is_some() {
"https"
} else {
"http"
};
let is_dav_write = crate::dav::is_dav_method(&req.method)
&& !req.method.eq_ignore_ascii_case("PROPFIND");
let is_git_write = req.path.contains("/git-receive-pack")
|| (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
|| (req.path.contains("/info/lfs/") && req.method.eq_ignore_ascii_case("PUT"))
|| (req.path.contains("/info/lfs/locks")
&& req.method.eq_ignore_ascii_case("POST"))
|| is_dav_write;
let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
} else {
None
};
let lfs_lock_resp = if page.is_none()
&& auth_denied.is_none()
&& !opts.disable_lfs
&& req.path.contains("/info/lfs/locks")
{
let store = crate::web_ui::store::ForgeStore::load_shared(git_dir);
let actor = crate::web_ui::auth_api::resolve_actor(&store, &req);
let actor_ref = actor.as_ref().map(|(u, r)| (u.as_str(), r.as_str()));
crate::lfs_locks::handle_lfs_locks(git_dir, &req, actor_ref)
} else {
None
};
match page
.or(auth_denied)
.or(lfs_lock_resp)
.map(Ok)
.unwrap_or_else(|| {
handle_smart_http_auth_opts(
&mut repo,
&req,
opts.basic_auth.as_ref(),
!opts.disable_lfs,
scheme,
)
}) {
Ok(r) => r,
Err(e) => {
let msg = e.to_string();
eprintln!(
"arks serve-http error path={path} body_len={} : {msg}",
req.body.len()
);
HttpResponse {
status: 500,
content_type: "text/plain".into(),
body: msg.into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
}
}
}
};
let mut resp = resp;
let trace = crate::ops::RequestTrace::from_request(&req);
trace.attach_headers(&mut resp);
if !is_head {
maybe_gzip_response(&mut resp, &req);
}
crate::ops::maybe_emit_json_access_log(&trace, &req, resp.status, 0);
let keep_alive = if matches!(resp.status, 408 | 413 | 503) {
None
} else {
keep_alive_rem
};
write_http_response_full(stream, &resp, req.is_https(), keep_alive, is_head)?;
if keep_alive.is_none() {
return Ok(());
}
}
Ok(())
}
fn is_compressible_content_type(ct: &str) -> bool {
let mime = ct
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
mime.starts_with("text/")
|| mime == "application/json"
|| mime == "application/problem+json"
|| mime == "application/javascript"
|| mime == "application/manifest+json"
|| mime == "application/linkset+json"
|| mime == "application/atom+xml"
|| mime == "image/svg+xml"
}
fn maybe_gzip_response(resp: &mut HttpResponse, req: &HttpRequest) {
if resp.body.len() < 1024
|| matches!(resp.status, 204 | 304)
|| crate::web::core::headers::is_git_wire_path(&req.path)
|| crate::dav::is_dav_method(&req.method)
|| !is_compressible_content_type(&resp.content_type)
{
return;
}
let accepts_gzip = req
.header("accept-encoding")
.is_some_and(|ae| ae.to_ascii_lowercase().contains("gzip"));
if !accepts_gzip {
return;
}
if resp
.extra_headers
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
{
return;
}
let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
if enc.write_all(&resp.body).is_ok()
&& let Ok(compressed) = enc.finish()
&& compressed.len() < resp.body.len()
{
resp.body = compressed;
resp.extra_headers
.push(("Content-Encoding".into(), "gzip".into()));
if let Some((_, v)) = resp
.extra_headers
.iter_mut()
.find(|(k, _)| k.eq_ignore_ascii_case("vary"))
{
if !v.to_ascii_lowercase().contains("accept-encoding") {
v.push_str(", Accept-Encoding");
}
} else {
resp.extra_headers
.push(("Vary".into(), "Accept-Encoding".into()));
}
}
}
fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
write_http_response_full(stream, resp, false, None, false)
}
#[cfg(test)]
fn write_http_response_with_options<S: Write>(
stream: &mut S,
resp: &HttpResponse,
is_https: bool,
keep_alive_remaining: Option<usize>,
) -> Result<(), ServerError> {
write_http_response_full(stream, resp, is_https, keep_alive_remaining, false)
}
fn write_http_response_full<S: Write>(
stream: &mut S,
resp: &HttpResponse,
is_https: bool,
keep_alive_remaining: Option<usize>,
is_head: bool,
) -> Result<(), ServerError> {
let status_text = match resp.status {
200 => "OK",
201 => "Created",
204 => "No Content",
207 => "Multi-Status",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
408 => "Request Timeout",
409 => "Conflict",
412 => "Precondition Failed",
413 => "Payload Too Large",
415 => "Unsupported Media Type",
422 => "Unprocessable Entity",
423 => "Locked",
428 => "Precondition Required",
429 => "Too Many Requests",
500 => "Internal Server Error",
501 => "Not Implemented",
503 => "Service Unavailable",
507 => "Insufficient Storage",
_ => "Error",
};
let conn_header = match keep_alive_remaining {
Some(rem) => format!(
"Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
),
None => "Connection: close\r\n".to_string(),
};
let mut header = format!(
"HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
resp.status,
status_text,
resp.content_type,
resp.body.len(),
conn_header
);
if let Some(ref wa) = resp.www_authenticate {
header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
}
let mut has_csp = false;
let mut has_pp = false;
let mut has_coop = false;
let mut has_corp = false;
let mut has_xcto = false;
let mut has_xfo = false;
let mut has_rp = false;
let mut has_hsts = false;
let is_html = resp.content_type.starts_with("text/html");
for (k, v) in &resp.extra_headers {
if k.eq_ignore_ascii_case("content-security-policy") {
has_csp = true;
if is_html && is_https && !v.contains("upgrade-insecure-requests") {
header.push_str(&format!("{k}: {v}; upgrade-insecure-requests\r\n"));
continue;
}
} else if k.eq_ignore_ascii_case("permissions-policy") {
has_pp = true;
} else if k.eq_ignore_ascii_case("cross-origin-opener-policy") {
has_coop = true;
} else if k.eq_ignore_ascii_case("cross-origin-resource-policy") {
has_corp = true;
} else if k.eq_ignore_ascii_case("x-content-type-options") {
has_xcto = true;
} else if k.eq_ignore_ascii_case("x-frame-options") {
has_xfo = true;
} else if k.eq_ignore_ascii_case("referrer-policy") {
has_rp = true;
} else if k.eq_ignore_ascii_case("strict-transport-security") {
has_hsts = true;
}
header.push_str(&format!("{k}: {v}\r\n"));
}
if is_html {
if !has_csp {
let csp = if is_https {
crate::web::core::headers::WEB_UI_CSP_HTTPS
} else {
crate::web::core::headers::WEB_UI_CSP
};
header.push_str(&format!("Content-Security-Policy: {csp}\r\n"));
}
if !has_pp {
header.push_str(&format!(
"Permissions-Policy: {}\r\n",
crate::web::core::headers::PERMISSIONS_POLICY
));
}
if !has_coop {
header.push_str(&format!(
"Cross-Origin-Opener-Policy: {}\r\n",
crate::web::core::headers::COOP
));
}
if !has_corp {
header.push_str(&format!(
"Cross-Origin-Resource-Policy: {}\r\n",
crate::web::core::headers::CORP
));
}
if !has_xcto {
header.push_str(&format!(
"X-Content-Type-Options: {}\r\n",
crate::web::core::headers::X_CONTENT_TYPE_OPTIONS
));
}
if !has_xfo {
header.push_str(&format!(
"X-Frame-Options: {}\r\n",
crate::web::core::headers::X_FRAME_OPTIONS
));
}
if !has_rp {
header.push_str(&format!(
"Referrer-Policy: {}\r\n",
crate::web::core::headers::REFERRER_POLICY
));
}
}
if is_https && !has_hsts {
header.push_str(&format!(
"Strict-Transport-Security: {}\r\n",
crate::web::core::headers::HSTS
));
}
header.push_str("\r\n");
if is_head || resp.status == 204 || resp.status == 304 {
stream.write_all(header.as_bytes())?;
} else if resp.body.len() <= 64 * 1024 {
let mut combined = Vec::with_capacity(header.len() + resp.body.len());
combined.extend_from_slice(header.as_bytes());
combined.extend_from_slice(&resp.body);
stream.write_all(&combined)?;
} else {
stream.write_all(header.as_bytes())?;
stream.write_all(&resp.body)?;
}
stream.flush()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::basic_authorization_header;
use sha2::{Digest, Sha256};
use tempfile::TempDir;
fn raw_http_exchange(addr: SocketAddr, request: &str) -> String {
let mut sock = TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
sock.write_all(request.as_bytes()).unwrap();
let mut out = Vec::new();
let _ = sock.read_to_end(&mut out);
String::from_utf8_lossy(&out).into_owned()
}
fn seed_empty_bare(dir: &Path) {
std::fs::create_dir_all(dir.join("objects")).unwrap();
std::fs::create_dir_all(dir.join("refs/heads")).unwrap();
std::fs::write(dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
}
#[test]
fn basic_auth_gates_pages_on_single_and_multi_repo_while_exempting_health_and_metrics() {
let dir = TempDir::new().unwrap();
seed_empty_bare(dir.path());
let auth_hdr = basic_authorization_header("alice", "s3cret");
for multi_repo_root in [false, true] {
let page_hits = Arc::new(AtomicUsize::new(0));
let hits_cb = Arc::clone(&page_hits);
let pages: PageHandler = Arc::new(move |req: &HttpRequest| {
hits_cb.fetch_add(1, Ordering::SeqCst);
Some(HttpResponse {
status: 200,
content_type: "text/plain; charset=utf-8".into(),
body: format!("page:{}\n", req.path).into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
})
});
let opts = ServeHttpOptions {
basic_auth: Some(BasicAuthConfig::single("alice", "s3cret")),
pages: Some(pages),
multi_repo_root,
..ServeHttpOptions::default()
};
let (addr, stop, handle) =
spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
for path in ["/", "/api/v1/issues"] {
let req =
format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
let resp = raw_http_exchange(addr, &req);
assert!(
resp.starts_with("HTTP/1.1 401 Unauthorized"),
"multi_repo={multi_repo_root} path={path} must require Basic Auth: {resp}"
);
assert!(resp.contains("WWW-Authenticate: Basic realm=\"arks\""));
}
assert_eq!(
page_hits.load(Ordering::SeqCst),
0,
"pages handler must never run before Basic Auth succeeds (multi_repo={multi_repo_root})"
);
for exempt in ["/healthz", "/readyz", "/metrics"] {
let req =
format!("GET {exempt} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
let resp = raw_http_exchange(addr, &req);
assert!(
resp.starts_with("HTTP/1.1 200 OK"),
"exempt endpoint {exempt} must succeed without auth: {resp}"
);
}
let authed_req = format!(
"GET / HTTP/1.1\r\nHost: {addr}\r\nAuthorization: {auth_hdr}\r\nConnection: close\r\n\r\n"
);
let authed_resp = raw_http_exchange(addr, &authed_req);
assert!(
authed_resp.starts_with("HTTP/1.1 200 OK") && authed_resp.contains("page:/"),
"authenticated request must reach pages: {authed_resp}"
);
assert_eq!(page_hits.load(Ordering::SeqCst), 1);
stop.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
}
}
#[test]
fn cross_origin_write_rejected_when_pages_enabled() {
let dir = TempDir::new().unwrap();
seed_empty_bare(dir.path());
let pages: PageHandler = Arc::new(|_req: &HttpRequest| None);
let opts = ServeHttpOptions {
pages: Some(pages.clone()),
..ServeHttpOptions::default()
};
for (method, path) in [
("POST", "/git-receive-pack"),
("POST", "/demo.git/git-receive-pack"),
("PUT", "/info/lfs/objects/deadbeef"),
("PUT", "/refs/heads/main"),
("MOVE", "/objects/ab/cdef"),
("DELETE", "/refs/heads/topic"),
("LOCK", "/refs/heads/main"),
("UNLOCK", "/refs/heads/main"),
] {
let mut cross = HttpRequest::new(method, path, "", Vec::new());
cross.host = Some("127.0.0.1:8080".into());
cross.origin = Some("https://evil.example".into());
let resp = check_cross_origin_write(&opts, &cross)
.expect("cross-origin mutating write must be rejected");
assert_eq!(resp.status, 403, "{method} {path} must return 403");
assert!(
String::from_utf8_lossy(&resp.body).contains("cross-origin write rejected"),
"{}",
String::from_utf8_lossy(&resp.body)
);
let mut same = cross.clone();
same.origin = Some("http://127.0.0.1:8080".into());
assert!(
check_cross_origin_write(&opts, &same).is_none(),
"same-origin {method} {path} must be allowed"
);
let mut no_origin = cross.clone();
no_origin.origin = None;
assert!(
check_cross_origin_write(&opts, &no_origin).is_none(),
"missing Origin without Sec-Fetch-Site on {method} {path} must be allowed"
);
let mut cross_fetch_site = no_origin.clone();
cross_fetch_site.sec_fetch_site = Some("cross-site".into());
let resp = check_cross_origin_write(&opts, &cross_fetch_site)
.expect("Sec-Fetch-Site: cross-site without Origin must be rejected");
assert_eq!(resp.status, 403, "{method} {path} must return 403");
let mut same_fetch_site = no_origin;
same_fetch_site.sec_fetch_site = Some("same-origin".into());
assert!(
check_cross_origin_write(&opts, &same_fetch_site).is_none(),
"Sec-Fetch-Site: same-origin without Origin on {method} {path} must be allowed"
);
}
let (addr, stop, handle) =
spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
let req = format!(
"POST /git-receive-pack HTTP/1.1\r\nHost: {addr}\r\nOrigin: https://evil.example\r\nContent-Length: 4\r\nConnection: close\r\n\r\n0000"
);
let resp = raw_http_exchange(addr, &req);
assert!(
resp.starts_with("HTTP/1.1 403 Forbidden")
&& resp.contains("cross-origin write rejected"),
"live loopback must reject cross-origin receive-pack with 403: {resp}"
);
stop.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
}
#[test]
fn webdav_writes_require_forge_auth_and_lfs_honors_forwarded_proto_https() {
let dir = TempDir::new().unwrap();
seed_empty_bare(dir.path());
let reader_pat = "arks_pat_reader_test_token";
let reader_hash = {
let digest = Sha256::digest(reader_pat.as_bytes());
let mut s = String::with_capacity(64);
for b in digest {
s.push_str(&format!("{b:02x}"));
}
s
};
let mut store = crate::web_ui::store::ForgeStore::load(dir.path());
store.users.push(crate::web_ui::store::UserAccount {
username: "reader1".into(),
password_hash: "x".into(),
role: "reader".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
store.pats.push(crate::web_ui::store::PatRecord {
id: 1,
username: "reader1".into(),
name: "read".into(),
token_hash: reader_hash,
prefix: "arks_pat_r".into(),
created_at: 1,
scopes: Vec::new(),
expires_at: None,
last_used_at: None,
});
store.save(dir.path()).unwrap();
let (addr, stop, handle) =
spawn_loopback_with_opts(dir.path().to_path_buf(), ServeHttpOptions::default())
.unwrap();
for (method, path) in [
("PUT", "/refs/heads/main"),
("MKCOL", "/objects/ab"),
("LOCK", "/refs/heads/main"),
("DELETE", "/refs/heads/main"),
] {
let req = format!(
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let resp = raw_http_exchange(addr, &req);
assert!(
resp.starts_with("HTTP/1.1 401 Unauthorized"),
"unauthenticated WebDAV {method} {path} must return 401: {resp}"
);
}
let reader_put = format!(
"PUT /refs/heads/main HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {reader_pat}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let reader_resp = raw_http_exchange(addr, &reader_put);
assert!(
reader_resp.starts_with("HTTP/1.1 403 Forbidden"),
"reader role must be denied WebDAV PUT with 403: {reader_resp}"
);
let propfind = format!(
"PROPFIND / HTTP/1.1\r\nHost: {addr}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let prop_resp = raw_http_exchange(addr, &propfind);
assert!(
prop_resp.starts_with("HTTP/1.1 207 Multi-Status"),
"PROPFIND discovery on public repo must return 207: {prop_resp}"
);
let batch_body = format!(
r#"{{"operation":"upload","objects":[{{"oid":"{}","size":4}}]}}"#,
"a".repeat(64)
);
let lfs_req = format!(
"POST /info/lfs/objects/batch HTTP/1.1\r\nHost: proxy.example.invalid\r\nX-Forwarded-Proto: https\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
batch_body.len(),
batch_body
);
let lfs_resp = raw_http_exchange(addr, &lfs_req);
assert!(
lfs_resp.starts_with("HTTP/1.1 200 OK")
&& lfs_resp.contains("https://proxy.example.invalid/info/lfs/objects/"),
"LFS batch must honor X-Forwarded-Proto: https: {lfs_resp}"
);
stop.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
}
#[test]
fn slow_post_body_dribble_hits_cumulative_deadline() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let client = thread::spawn(move || {
let mut sock = TcpStream::connect(addr).unwrap();
for _ in 0..8 {
if sock.write_all(b"x").is_err() {
break;
}
thread::sleep(Duration::from_millis(60));
}
});
let (mut srv, _) = listener.accept().unwrap();
let mut buf = Vec::new();
let mut tmp = [0u8; 64];
let completed = read_http_body_with_deadline(
&mut srv,
&mut buf,
&mut tmp,
1024,
Duration::from_millis(200),
)
.unwrap();
assert!(
!completed,
"Slow-POST dribble must time out against cumulative body deadline"
);
drop(srv);
client.join().unwrap();
}
#[test]
fn html_security_headers_applied_to_html_and_excluded_from_git_wire() {
let html_resp = HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: b"<h1>ok</h1>".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
let mut wire_http = Vec::new();
write_http_response_with_options(&mut wire_http, &html_resp, false, None).unwrap();
let http_str = String::from_utf8(wire_http).unwrap();
assert!(http_str.contains("Content-Security-Policy: default-src 'self'"));
assert!(http_str.contains("frame-ancestors 'none'"));
assert!(http_str.contains("Permissions-Policy: camera=()"));
assert!(http_str.contains("Cross-Origin-Opener-Policy: same-origin"));
assert!(http_str.contains("Cross-Origin-Resource-Policy: same-origin"));
assert!(http_str.contains("X-Content-Type-Options: nosniff"));
assert!(http_str.contains("X-Frame-Options: DENY"));
assert!(http_str.contains("Referrer-Policy: strict-origin-when-cross-origin"));
assert!(!http_str.contains("upgrade-insecure-requests"));
let mut wire_https = Vec::new();
write_http_response_with_options(&mut wire_https, &html_resp, true, None).unwrap();
let https_str = String::from_utf8(wire_https).unwrap();
assert!(https_str.contains("upgrade-insecure-requests"));
assert!(https_str.contains("Strict-Transport-Security:"));
let git_resp = HttpResponse {
status: 200,
content_type: "application/x-git-upload-pack-advertisement".into(),
body: b"001e# service=git-upload-pack\n0000".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
let mut wire_git = Vec::new();
write_http_response_with_options(&mut wire_git, &git_resp, false, None).unwrap();
let git_str = String::from_utf8(wire_git).unwrap();
assert!(!git_str.contains("Content-Security-Policy:"));
assert!(!git_str.contains("Permissions-Policy:"));
assert!(!git_str.contains("Cross-Origin-Opener-Policy:"));
assert!(!git_str.contains("X-Frame-Options:"));
}
#[test]
fn head_and_options_semantics_follow_rfc9110() {
let resp = HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: b"<h1>hello</h1>".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
let mut head_wire = Vec::new();
write_http_response_full(&mut head_wire, &resp, false, None, true).unwrap();
let head_str = String::from_utf8(head_wire).unwrap();
assert!(head_str.starts_with("HTTP/1.1 200 OK\r\n"));
assert!(head_str.contains("Content-Length: 14\r\n"));
assert!(
head_str.ends_with("\r\n\r\n"),
"HEAD wire response must carry empty body: {head_str}"
);
let dir = TempDir::new().unwrap();
seed_empty_bare(dir.path());
let repo_dir = dir.path().to_path_buf();
let pages: PageHandler =
Arc::new(move |req: &HttpRequest| crate::web_ui::handle_web_ui(&repo_dir, req));
let opts = ServeHttpOptions {
pages: Some(pages),
..ServeHttpOptions::default()
};
let (addr, stop, handle) =
spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
let head_health = raw_http_exchange(
addr,
"HEAD /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(head_health.starts_with("HTTP/1.1 200 OK\r\n"));
assert!(head_health.ends_with("\r\n\r\n"));
let opt_health = raw_http_exchange(
addr,
"OPTIONS /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(opt_health.starts_with("HTTP/1.1 204 No Content\r\n"));
assert!(opt_health.contains("Allow: GET, HEAD, OPTIONS\r\n"));
let head_root = raw_http_exchange(
addr,
"HEAD / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(head_root.starts_with("HTTP/1.1 200 OK\r\n"), "{head_root}");
assert!(head_root.ends_with("\r\n\r\n"));
let opt_root = raw_http_exchange(
addr,
"OPTIONS / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(
opt_root.starts_with("HTTP/1.1 204 No Content\r\n"),
"{opt_root}"
);
assert!(
opt_root.contains("Allow: GET, HEAD, OPTIONS\r\n"),
"{opt_root}"
);
stop.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
}
#[test]
fn livez_readyz_and_gated_metrics_follow_o2() {
let dir = TempDir::new().unwrap();
seed_empty_bare(dir.path());
let shutdown_flag = Arc::new(AtomicBool::new(false));
let opts = ServeHttpOptions {
shutdown_flag: Some(shutdown_flag.clone()),
metrics_token: Some("secret-metrics-tok".into()),
metrics_require_token: true,
..ServeHttpOptions::default()
};
let (addr, stop, handle) =
spawn_loopback_with_opts(dir.path().to_path_buf(), opts).unwrap();
let live = raw_http_exchange(
addr,
"GET /livez HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(live.starts_with("HTTP/1.1 200 OK\r\n"), "{live}");
assert!(live.contains("\"alive\""));
let ready_ok = raw_http_exchange(
addr,
"GET /readyz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(ready_ok.starts_with("HTTP/1.1 200 OK\r\n"), "{ready_ok}");
let met_denied = raw_http_exchange(
addr,
"GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(
met_denied.starts_with("HTTP/1.1 404 Not Found\r\n"),
"{met_denied}"
);
let met_ok = raw_http_exchange(
addr,
"GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer secret-metrics-tok\r\nConnection: close\r\n\r\n",
);
assert!(met_ok.starts_with("HTTP/1.1 200 OK\r\n"), "{met_ok}");
assert!(met_ok.contains("arks_git_upload_pack_total"));
assert!(met_ok.contains("arks_git_receive_pack_total"));
assert!(met_ok.contains("arks_lfs_bytes_total"));
assert!(met_ok.contains("arks_build_info{version="));
shutdown_flag.store(true, Ordering::SeqCst);
let ready_down = raw_http_exchange(
addr,
"GET /readyz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(
ready_down.starts_with("HTTP/1.1 503 Service Unavailable\r\n"),
"{ready_down}"
);
assert!(ready_down.contains("shutting_down"));
let live_still = raw_http_exchange(
addr,
"GET /livez HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
);
assert!(live_still.starts_with("HTTP/1.1 200 OK\r\n"));
stop.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
}
#[test]
fn gzip_compression_applies_to_html_and_excludes_git_wire() {
let html_body = "<div>".to_string() + &"hello arks ".repeat(300) + "</div>";
let mut html_resp = HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html_body.as_bytes().to_vec(),
www_authenticate: None,
extra_headers: vec![("Vary".into(), "HX-Request, Cookie".into())],
};
let req = HttpRequest::new("GET", "/issues", "", Vec::new())
.with_header("Accept-Encoding", "gzip, deflate");
maybe_gzip_response(&mut html_resp, &req);
assert!(
html_resp
.extra_headers
.contains(&("Content-Encoding".into(), "gzip".into()))
);
assert!(html_resp.body.len() < html_body.len());
let mut dec = flate2::read::GzDecoder::new(html_resp.body.as_slice());
let mut roundtrip = String::new();
dec.read_to_string(&mut roundtrip).unwrap();
assert_eq!(roundtrip, html_body);
let mut git_resp = HttpResponse {
status: 200,
content_type: "text/plain".into(),
body: vec![b'a'; 4096],
www_authenticate: None,
extra_headers: Vec::new(),
};
let git_req = HttpRequest::new("GET", "/repo.git/info/refs", "", Vec::new())
.with_header("Accept-Encoding", "gzip");
maybe_gzip_response(&mut git_resp, &git_req);
assert!(
!git_resp
.extra_headers
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
);
}
}