use crate::auth::BasicAuthConfig;
use crate::dav::{handle_dav_as, is_dav_method};
use crate::dumb::serve_dumb_path;
use crate::error::ServerError;
use crate::push_policy::Pusher;
use crate::receive::{receive_advertisement, receive_pack_as};
use crate::upload::{upload_advertisement, upload_pack_result};
use crate::v2::{handle_v2_request, v2_capability_advertisement_for};
use arks_repo::Repository;
const UPLOAD_AD: &str = "application/x-git-upload-pack-advertisement";
const UPLOAD_RES: &str = "application/x-git-upload-pack-result";
const RECEIVE_AD: &str = "application/x-git-receive-pack-advertisement";
const RECEIVE_RES: &str = "application/x-git-receive-pack-result";
#[derive(Debug, Clone)]
pub struct HttpRequest {
pub method: String,
pub path: String,
pub query: String,
pub body: Vec<u8>,
pub git_protocol: Option<String>,
pub authorization: Option<String>,
pub destination: Option<String>,
pub lock_token: Option<String>,
pub host: Option<String>,
pub cookie: Option<String>,
pub origin: Option<String>,
pub forwarded_proto: Option<String>,
pub sec_fetch_site: Option<String>,
}
impl HttpRequest {
pub fn new(
method: impl Into<String>,
path: impl Into<String>,
query: impl Into<String>,
body: Vec<u8>,
) -> Self {
Self {
method: method.into(),
path: path.into(),
query: query.into(),
body,
git_protocol: None,
authorization: None,
destination: None,
lock_token: None,
host: None,
cookie: None,
origin: None,
forwarded_proto: None,
sec_fetch_site: None,
}
}
pub fn is_https(&self) -> bool {
self.forwarded_proto.as_deref().is_some_and(|v| {
v.split(',')
.next()
.unwrap_or("")
.trim()
.eq_ignore_ascii_case("https")
})
}
}
#[derive(Debug, Clone)]
pub struct HttpResponse {
pub status: u16,
pub content_type: String,
pub body: Vec<u8>,
pub www_authenticate: Option<String>,
pub extra_headers: Vec<(String, String)>,
}
pub fn handle_smart_http(
repo: &mut Repository,
req: &HttpRequest,
) -> Result<HttpResponse, ServerError> {
handle_smart_http_auth(repo, req, None)
}
pub fn handle_smart_http_auth(
repo: &mut Repository,
req: &HttpRequest,
basic: Option<&BasicAuthConfig>,
) -> Result<HttpResponse, ServerError> {
handle_smart_http_auth_opts(repo, req, basic, true, "http")
}
pub fn handle_smart_http_auth_opts(
repo: &mut Repository,
req: &HttpRequest,
basic: Option<&BasicAuthConfig>,
enable_lfs: bool,
scheme: &str,
) -> Result<HttpResponse, ServerError> {
let verified_basic_user = if let Some(cfg) = basic {
match cfg.authorized_user(req.authorization.as_deref()) {
Some(user) => Some(user),
None => {
return Ok(HttpResponse {
status: 401,
content_type: "text/plain".into(),
body: b"unauthorized\n".to_vec(),
www_authenticate: Some(cfg.challenge_header()),
extra_headers: Vec::new(),
});
}
}
} else {
None
};
if crate::lfs::is_lfs_path(&req.path) {
if enable_lfs {
return crate::lfs::handle_lfs(repo, req, scheme);
}
return Ok(text(404, b"LFS disabled\n"));
}
if is_dav_method(&req.method) {
if dav_mutation_targets_internal_arks_ref(req) {
return Ok(text(
403,
b"Forbidden: mutations under refs/arks/ are not permitted\n",
));
}
let pusher = Pusher {
transport: "http",
verified_user: verified_basic_user,
authorization: req.authorization.clone(),
};
return handle_dav_as(repo, req, &pusher);
}
let path = req.path.as_str();
let wants_v2 = req
.git_protocol
.as_deref()
.map(|v| {
v.split(':')
.any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
})
.unwrap_or(false)
|| req
.git_protocol
.as_deref()
.map(|v| v.contains("version=2"))
.unwrap_or(false);
if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
let service = query_param(&req.query, "service").unwrap_or("");
if service.is_empty() {
return match serve_dumb_path(repo, "info/refs")? {
Some((ct, body)) => Ok(typed(200, &ct, body)),
None => Ok(text(404, b"not found")),
};
}
if wants_v2 && service == "git-upload-pack" {
let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
.map_err(|e| ServerError::Protocol(e.to_string()))?;
body.extend(
arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
.map_err(|e| ServerError::Protocol(e.to_string()))?,
);
body.extend(v2_capability_advertisement_for(repo)?);
return Ok(typed(200, UPLOAD_AD, body));
}
return match service {
"git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
"git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
_ => Ok(text(403, b"unknown service")),
};
}
if req.method.eq_ignore_ascii_case("POST")
&& (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
{
if looks_like_v2_command(&req.body) {
return Ok(typed(
200,
UPLOAD_RES,
handle_v2_request(repo, &req.body, true)?,
));
}
return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
}
if req.method.eq_ignore_ascii_case("POST")
&& (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
{
let pusher = Pusher {
transport: "http",
verified_user: verified_basic_user,
authorization: req.authorization.clone(),
};
return Ok(typed(
200,
RECEIVE_RES,
receive_pack_as(repo, &req.body, &pusher)?,
));
}
if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
let rel = path.trim_start_matches('/');
if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
return Ok(typed(200, &ct, body));
}
if let Some(idx) = rel.find("objects/") {
if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
return Ok(typed(200, &ct, body));
}
}
if let Some(idx) = rel.find("info/refs") {
if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
return Ok(typed(200, &ct, body));
}
}
}
Ok(text(404, b"not found"))
}
fn dav_mutation_targets_internal_arks_ref(req: &HttpRequest) -> bool {
let method = req.method.to_ascii_uppercase();
if !matches!(
method.as_str(),
"PUT" | "MOVE" | "DELETE" | "LOCK" | "UNLOCK" | "MKCOL"
) {
return false;
}
if raw_path_targets_internal_arks_ref(&req.path) {
return true;
}
if let Some(dest) = req.destination.as_deref() {
if raw_path_targets_internal_arks_ref(dest) {
return true;
}
}
false
}
fn hex_nibble(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn percent_decode_path(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
{
out.push((hi << 4) | lo);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn raw_path_targets_internal_arks_ref(raw: &str) -> bool {
let path_only = if let Some(idx) = raw.find("://") {
let after = &raw[idx + 3..];
match after.find('/') {
Some(slash) => &after[slash..],
None => return false,
}
} else {
raw
};
let without_query = path_only.split(['?', '#']).next().unwrap_or("");
let decoded = percent_decode_path(without_query);
let normalized = decoded.replace('\\', "/");
let mut segments: Vec<&str> = Vec::new();
for seg in normalized.split('/') {
if seg.is_empty() || seg == "." {
continue;
}
if seg == ".." {
segments.pop();
continue;
}
segments.push(seg);
}
segments
.windows(2)
.any(|w| w[0].eq_ignore_ascii_case("refs") && w[1].eq_ignore_ascii_case("arks"))
}
fn looks_like_v2_command(body: &[u8]) -> bool {
body.len() >= 4 && {
let s = String::from_utf8_lossy(body);
s.contains("command=")
}
}
fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
for part in query.split('&') {
if let Some((k, v)) = part.split_once('=') {
if k == key {
return Some(v);
}
}
}
None
}
fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
HttpResponse {
status,
content_type: ct.into(),
body,
www_authenticate: None,
extra_headers: Vec::new(),
}
}
fn text(status: u16, body: &[u8]) -> HttpResponse {
HttpResponse {
status,
content_type: "text/plain".into(),
body: body.to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
use arks_store::{ObjectFormat, ObjectStore};
use tempfile::TempDir;
fn seed_repo(format: ObjectFormat) -> (TempDir, Repository) {
let dir = TempDir::new().unwrap();
let git = dir.path();
std::fs::create_dir_all(git.join("objects")).unwrap();
std::fs::create_dir_all(git.join("refs/heads")).unwrap();
std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
if format == ObjectFormat::Sha256 {
std::fs::write(
git.join("config"),
"[core]\n\trepositoryformatversion = 1\n\tbare = true\n[extensions]\n\tobjectformat = sha256\n",
)
.unwrap();
} else {
std::fs::write(
git.join("config"),
"[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
)
.unwrap();
}
let mut repo = Repository::open(git).unwrap();
let blob = repo
.store_mut()
.put(format, &RawObject::new(ObjectKind::Blob, b"hi\n".to_vec()))
.unwrap();
let tree = Tree::new(vec![TreeEntry {
mode: TreeMode::File,
name: "a.txt".into(),
oid: blob,
}])
.unwrap();
let tree_oid = repo
.store_mut()
.put(
format,
&RawObject::new(ObjectKind::Tree, tree.encode().unwrap()),
)
.unwrap();
let sig = Signature {
name: "arks".into(),
email: "arks@example.invalid".into(),
timestamp: 1_700_000_000,
timezone: "+0000".into(),
};
let commit = Commit {
tree: tree_oid,
parents: Vec::new(),
author: sig.clone(),
committer: sig,
gpgsig: None,
message: "init\n".into(),
};
let oid = repo
.store_mut()
.put(
format,
&RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
)
.unwrap();
repo.refs_mut()
.update("refs/heads/main", &oid, None)
.unwrap();
(dir, repo)
}
#[test]
fn webdav_mutations_targeting_refs_arks_return_403() {
let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
for method in ["PUT", "DELETE", "LOCK", "MOVE"] {
let mut req = HttpRequest::new(
method,
"/repo.git/refs/arks/v2/keep/pin1",
"",
b"1111111111111111111111111111111111111111\n".to_vec(),
);
if method == "MOVE" {
req.destination = Some("http://127.0.0.1:8080/repo.git/refs/heads/other".into());
}
let resp = handle_smart_http(&mut repo, &req).unwrap();
assert_eq!(
resp.status, 403,
"WebDAV {method} targeting refs/arks/ must return 403"
);
}
let mut move_into_arks = HttpRequest::new("MOVE", "/refs/heads/main", "", Vec::new());
move_into_arks.destination =
Some("http://127.0.0.1:8080/repo.git/refs/arks/internal/alice/c1".into());
let resp = handle_smart_http(&mut repo, &move_into_arks).unwrap();
assert_eq!(resp.status, 403);
}
#[test]
fn raw_path_targets_internal_arks_ref_blocks_normalized_and_case_bypasses() {
let (_dir, mut repo) = seed_repo(ObjectFormat::Sha1);
for bypass_path in [
"/refs/./arks/v2/keep/x",
"/refs//arks/v2/keep/x",
"/refs/ARKS/v2/keep/x",
"/REFS/ARKS",
"/repo.git/refs/./arks/v2/keep/x",
"/repo.git/refs//ARKS/v2/keep/x",
"/refs%2farks/v2/keep/x",
"/refs%2F%2e%2FARKS/v2/keep/x",
"/refs/%2E/arks/v2/keep/x",
"/refs/heads/../arks/v2/keep/x",
"/refs/heads/%2e%2e/ARKS/v2/keep/x",
] {
assert!(
raw_path_targets_internal_arks_ref(bypass_path),
"must detect internal refs/arks bypass '{bypass_path}'"
);
let req = HttpRequest::new(
"PUT",
bypass_path,
"",
b"1111111111111111111111111111111111111111\n".to_vec(),
);
let resp = handle_smart_http(&mut repo, &req).unwrap();
assert_eq!(
resp.status, 403,
"PUT {bypass_path} must be rejected with 403"
);
}
assert!(!raw_path_targets_internal_arks_ref("/refs/heads/main"));
assert!(!raw_path_targets_internal_arks_ref("/refs/heads/arks"));
assert!(!raw_path_targets_internal_arks_ref("/refs/arks-other/foo"));
assert!(!raw_path_targets_internal_arks_ref(
"/repo.git/objects/ab/cdef"
));
}
#[test]
fn smart_http_v2_info_refs_advertises_sha256_for_sha256_repo() {
let (_dir, mut repo) = seed_repo(ObjectFormat::Sha256);
let mut req = HttpRequest::new("GET", "/info/refs", "service=git-upload-pack", Vec::new());
req.git_protocol = Some("version=2".into());
let resp = handle_smart_http(&mut repo, &req).unwrap();
assert_eq!(resp.status, 200);
let text = String::from_utf8_lossy(&resp.body);
assert!(text.contains("object-format=sha256"), "{text}");
assert!(!text.contains("object-format=sha1"), "{text}");
}
}