use crate::error::ServerError;
use crate::http::{HttpRequest, HttpResponse};
use crate::push_policy::Pusher;
use crate::ref_gate::{GateReject, GatedRefUpdate, apply_gated_ref_update};
use crate::web_ui::store::ForgeStore;
use arks_oid::Oid;
use arks_refs::RefTarget;
use arks_repo::Repository;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
const DAV_XML: &str = "application/xml; charset=\"utf-8\"";
pub fn is_dav_method(method: &str) -> bool {
matches!(
method.to_ascii_uppercase().as_str(),
"PROPFIND" | "LOCK" | "UNLOCK" | "MKCOL" | "PUT" | "MOVE" | "DELETE"
)
}
#[cfg(test)]
pub fn handle_dav(repo: &mut Repository, req: &HttpRequest) -> Result<HttpResponse, ServerError> {
let pusher = Pusher {
transport: "http",
verified_user: None,
authorization: req.authorization.clone(),
};
handle_dav_as(repo, req, &pusher)
}
pub(crate) fn handle_dav_as(
repo: &mut Repository,
req: &HttpRequest,
pusher: &Pusher,
) -> Result<HttpResponse, ServerError> {
let method = req.method.to_ascii_uppercase();
if method == "PROPFIND" {
return Ok(propfind_supported_lock());
}
let rel = repo_rel_path(&req.path)?;
let store = ForgeStore::load_shared(repo.common_dir());
if store.corrupt {
return Ok(text(
503,
b"Service Unavailable: forge store.json is corrupted (fail-closed)\n",
));
}
if store.archived {
return Ok(text(
403,
b"Forbidden: repository is archived (read-only)\n",
));
}
match method.as_str() {
"LOCK" => lock_path(repo.git_dir(), &rel),
"UNLOCK" => unlock_path(repo.git_dir(), &rel, req.lock_token.as_deref()),
"MKCOL" => mkcol(repo.git_dir(), &rel),
"PUT" => put_resource(repo, &rel, &req.body, req.lock_token.as_deref(), pusher),
"MOVE" => move_resource(repo.git_dir(), &rel, req.destination.as_deref()),
"DELETE" => delete_resource(repo, &rel, req.lock_token.as_deref(), pusher),
_ => Ok(text(405, b"method not allowed")),
}
}
fn propfind_supported_lock() -> HttpResponse {
let body = br#"<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response>
<D:href>/</D:href>
<D:propstat>
<D:prop>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
"#;
HttpResponse {
status: 207,
content_type: DAV_XML.into(),
body: body.to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
}
}
fn lock_path(git_dir: &Path, rel: &str) -> Result<HttpResponse, ServerError> {
ensure_writable_rel(rel)?;
if rel.is_empty() {
return Ok(text(403, b"lock path not claimed"));
}
let token = new_lock_token();
let lock_file = lock_file_path(git_dir, rel)?;
if let Some(parent) = lock_file.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&lock_file, format!("{token}\n"))?;
let body = format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<D:prop xmlns:D=\"DAV:\">\n\
<D:lockdiscovery>\n\
<D:activelock>\n\
<D:locktype><D:write/></D:locktype>\n\
<D:lockscope><D:exclusive/></D:lockscope>\n\
<D:depth>0</D:depth>\n\
<D:timeout>Second-600</D:timeout>\n\
<D:locktoken><D:href>{token}</D:href></D:locktoken>\n\
</D:activelock>\n\
</D:lockdiscovery>\n\
</D:prop>\n"
);
Ok(HttpResponse {
status: 200,
content_type: DAV_XML.into(),
body: body.into_bytes(),
www_authenticate: None,
extra_headers: vec![("Lock-Token".into(), format!("<{token}>"))],
})
}
fn unlock_path(
git_dir: &Path,
rel: &str,
token: Option<&str>,
) -> Result<HttpResponse, ServerError> {
ensure_writable_rel(rel)?;
if rel.is_empty() {
return Ok(text(403, b"unlock path not claimed"));
}
let lock_file = lock_file_path(git_dir, rel)?;
if !lock_file.is_file() {
return Ok(text(409, b"not locked"));
}
let stored = fs::read_to_string(&lock_file).unwrap_or_default();
let stored = stored.trim();
let given = token.map(strip_lock_brackets).unwrap_or("");
if given.is_empty() || given != stored {
return Ok(text(409, b"lock token mismatch"));
}
let _ = fs::remove_file(&lock_file);
Ok(text(204, b""))
}
fn mkcol(git_dir: &Path, rel: &str) -> Result<HttpResponse, ServerError> {
ensure_writable_rel(rel)?;
if !(rel.starts_with("objects/") && rel.matches('/').count() == 1) {
return Ok(text(403, b"mkcol path not claimed"));
}
let path = git_dir.join(rel);
if path.exists() {
return Ok(text(405, b"exists"));
}
fs::create_dir_all(&path)?;
Ok(text(201, b""))
}
fn put_resource(
repo: &mut Repository,
rel: &str,
body: &[u8],
token: Option<&str>,
pusher: &Pusher,
) -> Result<HttpResponse, ServerError> {
ensure_writable_rel(rel)?;
if let Some(resp) = lock_conflict(repo.git_dir(), rel, token)? {
return Ok(resp);
}
if let Some(rest) = rel.strip_prefix("objects/") {
return put_loose_object(repo.git_dir(), rest, body);
}
if rel.starts_with("refs/") {
return put_ref(repo, rel, body, pusher);
}
if rel == "info/refs" {
let path = repo.git_dir().join("info/refs");
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
atomic_write(&path, body)?;
return Ok(text(201, b""));
}
Ok(text(403, b"put path not claimed"))
}
fn put_loose_object(git_dir: &Path, rest: &str, body: &[u8]) -> Result<HttpResponse, ServerError> {
let parts: Vec<&str> = rest.split('/').collect();
if parts.len() != 2 || parts[0].len() != 2 {
return Ok(text(403, b"bad loose path"));
}
let fanout = parts[0];
let name = parts[1];
if !fanout.chars().all(|c| c.is_ascii_hexdigit()) {
return Ok(text(403, b"bad fanout"));
}
if name.is_empty() || name.starts_with('.') {
return Ok(text(403, b"bad loose path"));
}
let dir = git_dir.join("objects").join(fanout);
fs::create_dir_all(&dir)?;
let path = dir.join(name);
if path.is_file() {
return Ok(text(200, b""));
}
atomic_write(&path, body)?;
Ok(text(201, b""))
}
fn put_ref(
repo: &mut Repository,
rel: &str,
body: &[u8],
pusher: &Pusher,
) -> Result<HttpResponse, ServerError> {
if !arks_refs::is_valid_refname(rel) {
return Ok(text(403, b"invalid ref name"));
}
let text_body = std::str::from_utf8(body)
.map_err(|e| ServerError::Protocol(format!("ref body utf-8: {e}")))?;
let oid_hex = text_body.trim();
let oid = Oid::from_hex(oid_hex).map_err(|e| ServerError::Protocol(format!("ref oid: {e}")))?;
let upd = GatedRefUpdate {
refname: rel.to_string(),
old_oid: None,
new_oid: Some(oid),
allow_non_ff: true,
pusher: pusher.clone(),
allow_internal_arks_ref: false,
trigger_ci: true,
};
match apply_gated_ref_update(repo, &upd) {
Ok(()) => Ok(text(201, b"")),
Err(reject) => Ok(text(reject.http_status(), reject.message().as_bytes())),
}
}
fn delete_resource(
repo: &mut Repository,
rel: &str,
token: Option<&str>,
pusher: &Pusher,
) -> Result<HttpResponse, ServerError> {
ensure_writable_rel(rel)?;
if !rel.starts_with("refs/") || !arks_refs::is_valid_refname(rel) {
return Ok(text(403, b"delete path not claimed"));
}
if let Some(resp) = lock_conflict(repo.git_dir(), rel, token)? {
return Ok(resp);
}
if let Ok(RefTarget::Symbolic(head_ref)) = repo.head_target() {
if head_ref == rel {
return Ok(text(403, b"cannot delete current HEAD"));
}
}
let upd = GatedRefUpdate {
refname: rel.to_string(),
old_oid: None,
new_oid: None,
allow_non_ff: true,
pusher: pusher.clone(),
allow_internal_arks_ref: false,
trigger_ci: false,
};
match apply_gated_ref_update(repo, &upd) {
Ok(()) => Ok(text(204, b"")),
Err(GateReject::Conflict(msg))
if (msg.contains("not found")
|| msg.contains("missing")
|| msg.contains("does not exist"))
&& repo.refs().resolve(rel).is_err() =>
{
Ok(text(404, b"ref missing"))
}
Err(reject) => Ok(text(reject.http_status(), reject.message().as_bytes())),
}
}
fn is_loose_object_src_path(rel: &str) -> bool {
let Some(rest) = rel.strip_prefix("objects/") else {
return false;
};
let mut parts = rest.split('/');
let (Some(fanout), Some(name), None) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
fanout.len() == 2
&& fanout.bytes().all(|b| b.is_ascii_hexdigit())
&& !name.is_empty()
&& !name.starts_with('.')
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}
fn is_loose_object_final_path(rel: &str) -> bool {
let Some(rest) = rel.strip_prefix("objects/") else {
return false;
};
let mut parts = rest.split('/');
let (Some(fanout), Some(name), None) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
let total_hex = fanout.len() + name.len();
fanout.len() == 2
&& (total_hex == 40 || total_hex == 64)
&& fanout.bytes().all(|b| b.is_ascii_hexdigit())
&& name.bytes().all(|b| b.is_ascii_hexdigit())
}
fn move_resource(
git_dir: &Path,
rel: &str,
destination: Option<&str>,
) -> Result<HttpResponse, ServerError> {
ensure_writable_rel(rel)?;
let dest_url =
destination.ok_or_else(|| ServerError::Protocol("MOVE missing Destination".into()))?;
let dest_rel = destination_to_rel(dest_url)?;
ensure_writable_rel(&dest_rel)?;
if !is_loose_object_src_path(rel) || !is_loose_object_final_path(&dest_rel) {
return Ok(text(403, b"move path not allowed"));
}
let src = git_dir.join(rel);
let dst = git_dir.join(&dest_rel);
if !src.is_file() {
return Ok(text(404, b"move source missing"));
}
if let Some(parent) = dst.parent() {
fs::create_dir_all(parent)?;
}
if dst.exists() {
let _ = fs::remove_file(&src);
return Ok(text(204, b""));
}
fs::rename(&src, &dst)?;
Ok(text(201, b""))
}
fn lock_conflict(
git_dir: &Path,
rel: &str,
token: Option<&str>,
) -> Result<Option<HttpResponse>, ServerError> {
let lock_file = lock_file_path(git_dir, rel)?;
if !lock_file.is_file() {
return Ok(None);
}
let stored = fs::read_to_string(&lock_file).unwrap_or_default();
let stored = stored.trim();
let given = token.map(strip_lock_brackets).unwrap_or("");
if given.is_empty() || given != stored {
return Ok(Some(text(423, b"locked")));
}
Ok(None)
}
fn repo_rel_path(path: &str) -> Result<String, ServerError> {
let mut rel = path.trim_start_matches('/').to_string();
for marker in ["objects/", "refs/", "info/"] {
if let Some(idx) = rel.find(marker) {
rel = rel[idx..].to_string();
break;
}
}
if rel.is_empty() {
return Ok(String::new());
}
ensure_writable_rel(&rel)?;
Ok(rel)
}
fn destination_to_rel(destination: &str) -> Result<String, ServerError> {
if let Some(idx) = destination.find("://") {
let after = &destination[idx + 3..];
if let Some(slash) = after.find('/') {
return repo_rel_path(&after[slash..]);
}
return Err(ServerError::Protocol("bad Destination URL".into()));
}
repo_rel_path(destination)
}
fn ensure_writable_rel(rel: &str) -> Result<(), ServerError> {
if rel.is_empty() {
return Ok(());
}
if rel.contains('\\') || rel.contains('\0') || rel.contains("//") {
return Err(ServerError::Protocol("dav path escape".into()));
}
let segments: Vec<&str> = rel.split('/').collect();
if segments
.iter()
.any(|s| s.is_empty() || *s == "." || *s == "..")
{
return Err(ServerError::Protocol("dav path escape".into()));
}
let path = Path::new(rel);
if path.components().any(|c| {
matches!(
c,
Component::CurDir | Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(ServerError::Protocol("dav path escape".into()));
}
if segments.len() >= 2
&& segments[0].eq_ignore_ascii_case("refs")
&& segments[1].eq_ignore_ascii_case("arks")
{
return Err(ServerError::Protocol(
"forbidden: internal refs/arks path".into(),
));
}
if !(rel.starts_with("objects/") || rel.starts_with("refs/") || rel.starts_with("info/")) {
return Err(ServerError::Protocol(format!(
"dav path not claimed: {rel}"
)));
}
Ok(())
}
fn lock_file_path(git_dir: &Path, rel: &str) -> Result<PathBuf, ServerError> {
let safe: String = rel
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
Ok(git_dir.join("arks-dav-locks").join(safe))
}
fn new_lock_token() -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
format!("opaquelocktoken:arks-{nanos:x}")
}
fn strip_lock_brackets(token: &str) -> &str {
token.trim().trim_start_matches('<').trim_end_matches('>')
}
fn atomic_write(path: &Path, data: &[u8]) -> Result<(), ServerError> {
let tmp = PathBuf::from(format!("{}.tmp-arks-dav", path.display()));
fs::write(&tmp, data)?;
fs::rename(&tmp, path)?;
Ok(())
}
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 crate::web_ui::store::BranchRule;
use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
use arks_store::{ObjectFormat, ObjectStore};
use tempfile::TempDir;
fn make_commit(repo: &mut Repository, parents: Vec<Oid>, content: &[u8], msg: &str) -> Oid {
let blob = repo
.store_mut()
.put(
ObjectFormat::Sha1,
&RawObject::new(ObjectKind::Blob, content.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(
ObjectFormat::Sha1,
&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,
author: sig.clone(),
committer: sig,
gpgsig: None,
message: msg.into(),
};
repo.store_mut()
.put(
ObjectFormat::Sha1,
&RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
)
.unwrap()
}
fn seed_bare_repo() -> (TempDir, Repository, Oid) {
let dir = TempDir::new().unwrap();
let git = dir.path();
fs::create_dir_all(git.join("objects")).unwrap();
fs::create_dir_all(git.join("refs/heads")).unwrap();
fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
fs::write(
git.join("config"),
b"[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
)
.unwrap();
let mut repo = Repository::open(git).unwrap();
let c1 = make_commit(&mut repo, Vec::new(), b"v1\n", "init\n");
repo.refs_mut()
.update("refs/heads/main", &c1, None)
.unwrap();
(dir, repo, c1)
}
#[test]
fn dav_rejects_dot_empty_backslash_and_refs_arks_paths() {
let (_dir, mut repo, c1) = seed_bare_repo();
let body = format!("{}\n", c1.to_hex()).into_bytes();
for bad in [
"/refs/./arks/v2/keep/x",
"/refs//arks/v2/keep/x",
"/refs/ARKS/v2/keep/x",
"/refs\\arks\\v2\\keep\\x",
"/objects/./ab/cd",
"/objects//ab/cd",
] {
let req = HttpRequest::new("PUT", bad, "", body.clone());
assert!(
handle_dav(&mut repo, &req).is_err(),
"handle_dav must reject malformed/internal path '{bad}'"
);
}
}
#[test]
fn dav_writes_blocked_when_archived_or_corrupt() {
let (dir, mut repo, c1) = seed_bare_repo();
let c2 = make_commit(&mut repo, vec![c1], b"v2\n", "second\n");
let mut store = ForgeStore::load(dir.path());
store.archived = true;
store.save(dir.path()).unwrap();
let requests = vec![
HttpRequest::new("PUT", "/info/refs", "", b"info\n".to_vec()),
HttpRequest::new("PUT", "/objects/ab/1111_tmp", "", b"blob".to_vec()),
HttpRequest::new(
"PUT",
"/refs/heads/main",
"",
format!("{}\n", c2.to_hex()).into_bytes(),
),
HttpRequest::new("MKCOL", "/objects/cd", "", Vec::new()),
HttpRequest::new("LOCK", "/refs/heads/main", "", Vec::new()),
HttpRequest::new("UNLOCK", "/refs/heads/main", "", Vec::new()),
HttpRequest::new("DELETE", "/refs/heads/topic", "", Vec::new()),
{
let mut m = HttpRequest::new("MOVE", "/objects/ab/1111_tmp", "", Vec::new());
m.destination = Some(format!("/objects/ab/{}", "a".repeat(38)));
m
},
];
for req in &requests {
let resp = handle_dav(&mut repo, req).unwrap();
assert_eq!(
resp.status, 403,
"archived repo must reject {} {} with 403",
req.method, req.path
);
}
let store_file = dir.path().join("arks-forge").join("store.json");
fs::write(&store_file, b"{corrupt json!").unwrap();
for req in &requests {
let resp = handle_dav(&mut repo, req).unwrap();
assert_eq!(
resp.status, 503,
"corrupt store must reject {} {} with 503",
req.method, req.path
);
}
}
#[test]
fn dav_put_and_delete_ref_enforce_ref_update_gate_and_move_rejects_refs() {
let (dir, mut repo, c1) = seed_bare_repo();
let c2 = make_commit(&mut repo, vec![c1], b"v2\n", "ff\n");
let c_alt = make_commit(&mut repo, Vec::new(), b"alt\n", "diverged\n");
repo.refs_mut()
.update("refs/heads/topic", &c1, None)
.unwrap();
let mut store = ForgeStore::load(dir.path());
store.branch_rules.push(BranchRule {
pattern: "main".into(),
require_pr: false,
block_force_push: true,
block_delete: true,
required_reviews: 0,
});
store.branch_rules.push(BranchRule {
pattern: "topic".into(),
require_pr: false,
block_force_push: false,
block_delete: true,
required_reviews: 0,
});
store.save(dir.path()).unwrap();
let ff_req = HttpRequest::new(
"PUT",
"/refs/heads/main",
"",
format!("{}\n", c2.to_hex()).into_bytes(),
);
let ff_resp = handle_dav(&mut repo, &ff_req).unwrap();
assert_eq!(ff_resp.status, 201);
assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
let force_req = HttpRequest::new(
"PUT",
"/refs/heads/main",
"",
format!("{}\n", c_alt.to_hex()).into_bytes(),
);
let force_resp = handle_dav(&mut repo, &force_req).unwrap();
assert_eq!(force_resp.status, 403);
assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
let del_req = HttpRequest::new("DELETE", "/refs/heads/topic", "", Vec::new());
let del_resp = handle_dav(&mut repo, &del_req).unwrap();
assert_eq!(del_resp.status, 403);
assert_eq!(repo.refs().resolve("refs/heads/topic").unwrap(), c1);
let mut move_into_ref = HttpRequest::new("MOVE", "/objects/ab/tmp_obj", "", Vec::new());
move_into_ref.destination = Some("/refs/heads/main".into());
assert_eq!(handle_dav(&mut repo, &move_into_ref).unwrap().status, 403);
let mut move_from_ref = HttpRequest::new("MOVE", "/refs/heads/topic", "", Vec::new());
move_from_ref.destination = Some(format!("/objects/ab/{}", "b".repeat(38)));
assert_eq!(handle_dav(&mut repo, &move_from_ref).unwrap().status, 403);
let put_tmp = HttpRequest::new("PUT", "/objects/ab/final_tmp", "", b"loose-bytes".to_vec());
assert_eq!(handle_dav(&mut repo, &put_tmp).unwrap().status, 201);
let final_dest = format!("/objects/ab/{}", "c".repeat(38));
let mut move_obj = HttpRequest::new("MOVE", "/objects/ab/final_tmp", "", Vec::new());
move_obj.destination = Some(final_dest);
assert_eq!(handle_dav(&mut repo, &move_obj).unwrap().status, 201);
}
}