Skip to main content

arks_server/
ref_gate.rs

1//! Unified `RefUpdateGate` for all server-side Git ref mutations.
2//!
3//! Enforces per-repository in-process + cross-process serialization (`arks-ref-gate.lock`),
4//! internal `refs/arks/*` confidentiality, archived repository immutability, branch
5//! protection rules (`block_delete`, `block_force_push`),
6//! [`PushPolicy`](crate::push_policy::PushPolicy), non-bare checkout safety
7//! (`receive.denyCurrentBranch`), Git receive hooks (`pre-receive`, `update`,
8//! `post-receive`, `post-update`), atomic CAS ref mutation, dumb HTTP `info/refs`
9//! refresh, webhooks, and Actions CI.
10//!
11//! Spec: `.spec/sot/arks-self-host-server.sot.md` §38–§43.
12
13use crate::hooks::{
14    HookEnv, HookGate, run_post_receive, run_post_update, run_pre_receive, run_update,
15};
16use crate::push_policy::{Pusher, RefUpdate, installed_push_policy, verdicts};
17use crate::web_ui::store::ForgeStore;
18use arks_config::ConfigSet;
19use arks_object::{Commit, ObjectKind, RawObject, TreeMode};
20use arks_oid::{Oid, OidKind};
21use arks_refs::RefTarget;
22use arks_repo::{Repository, commit_tree_map};
23use std::collections::{HashMap, HashSet, VecDeque};
24use std::fmt;
25use std::fs;
26use std::io::Write as _;
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak};
29use std::time::{Duration, Instant};
30
31const REF_GATE_LOCK_FILE: &str = "arks-ref-gate.lock";
32const REF_GATE_STALE_SECS: u64 = 30;
33const REF_GATE_TIMEOUT_SECS: u64 = 30;
34
35#[derive(Default)]
36struct RepoSlot {
37    locked: Mutex<bool>,
38    cvar: Condvar,
39}
40
41struct OwnedRepoSlotGuard {
42    slot: Arc<RepoSlot>,
43}
44
45impl OwnedRepoSlotGuard {
46    fn lock(slot: Arc<RepoSlot>) -> Self {
47        let mut locked = slot.locked.lock().unwrap_or_else(|e| e.into_inner());
48        while *locked {
49            locked = slot.cvar.wait(locked).unwrap_or_else(|e| e.into_inner());
50        }
51        *locked = true;
52        drop(locked);
53        Self { slot }
54    }
55}
56
57impl Drop for OwnedRepoSlotGuard {
58    fn drop(&mut self) {
59        let mut locked = self.slot.locked.lock().unwrap_or_else(|e| e.into_inner());
60        *locked = false;
61        self.slot.cvar.notify_one();
62    }
63}
64
65struct FileLockGuard {
66    lock_path: PathBuf,
67}
68
69impl Drop for FileLockGuard {
70    fn drop(&mut self) {
71        let _ = fs::remove_file(&self.lock_path);
72    }
73}
74
75/// RAII lock guard serializing ref updates per repository across both threads
76/// (via an `Arc`-backed slot map with zero `Box::leak`) and OS processes
77/// (via sibling lockfile `<common_dir>/arks-ref-gate.lock`).
78pub struct RefGateGuard {
79    common_dir_key: PathBuf,
80    // Drop order is declaration order: remove the lockfile BEFORE releasing the in-process guard.
81    _file_lock: FileLockGuard,
82    _in_proc: OwnedRepoSlotGuard,
83}
84
85/// Canonical description of one server-side ref create, update, or delete.
86#[derive(Debug, Clone)]
87pub struct GatedRefUpdate {
88    pub refname: String,
89    pub old_oid: Option<Oid>,
90    pub new_oid: Option<Oid>,
91    pub allow_non_ff: bool,
92    pub pusher: Pusher,
93    pub allow_internal_arks_ref: bool,
94    pub trigger_ci: bool,
95}
96
97/// Structured rejection reason returned by [`RefUpdateGate`](apply_gated_ref_update).
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum GateReject {
100    Forbidden(String),
101    Conflict(String),
102    PreconditionFailed(String),
103    Internal(String),
104}
105
106impl GateReject {
107    pub fn message(&self) -> &str {
108        match self {
109            Self::Forbidden(m)
110            | Self::Conflict(m)
111            | Self::PreconditionFailed(m)
112            | Self::Internal(m) => m.as_str(),
113        }
114    }
115
116    pub fn http_status(&self) -> u16 {
117        match self {
118            Self::Forbidden(_) => 403,
119            Self::Conflict(_) => 409,
120            Self::PreconditionFailed(_) => 412,
121            Self::Internal(_) => 500,
122        }
123    }
124}
125
126impl fmt::Display for GateReject {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.write_str(self.message())
129    }
130}
131
132impl std::error::Error for GateReject {}
133
134fn canonical_repo_key(common_dir: &Path) -> PathBuf {
135    common_dir
136        .canonicalize()
137        .unwrap_or_else(|_| common_dir.to_path_buf())
138}
139
140fn acquire_in_process_repo_lock(key: &Path) -> OwnedRepoSlotGuard {
141    static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Weak<RepoSlot>>>> = OnceLock::new();
142    let map_lock = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
143    let slot = {
144        let mut map = map_lock.lock().unwrap_or_else(|e| e.into_inner());
145        match map.get(key).and_then(Weak::upgrade) {
146            Some(existing) => existing,
147            None => {
148                if map.len() > 64 {
149                    map.retain(|_, w| w.strong_count() > 0);
150                }
151                let fresh = Arc::new(RepoSlot::default());
152                map.insert(key.to_path_buf(), Arc::downgrade(&fresh));
153                fresh
154            }
155        }
156    };
157    OwnedRepoSlotGuard::lock(slot)
158}
159
160fn is_lock_stale(lock_path: &Path, stale_after: Duration) -> bool {
161    if let Some(pid) = crate::web_ui::store::parse_lockfile_pid(lock_path) {
162        if crate::web_ui::store::is_other_pid_alive_strict(pid) == Some(false) {
163            return true;
164        }
165    }
166    match fs::metadata(lock_path).and_then(|m| m.modified()) {
167        Ok(mtime) => mtime
168            .elapsed()
169            .map(|age| age >= stale_after)
170            .unwrap_or(false),
171        Err(_) => false,
172    }
173}
174
175fn acquire_file_lock_with(
176    lock_path: &Path,
177    stale_after: Duration,
178    timeout: Duration,
179) -> Result<FileLockGuard, String> {
180    if let Some(parent) = lock_path.parent() {
181        fs::create_dir_all(parent)
182            .map_err(|e| format!("failed to prepare lock directory {}: {e}", parent.display()))?;
183    }
184    let deadline = Instant::now() + timeout;
185    let mut backoff_ms = 2u64;
186    loop {
187        match fs::OpenOptions::new()
188            .write(true)
189            .create_new(true)
190            .open(lock_path)
191        {
192            Ok(mut f) => {
193                let payload = format!("pid={}\n", std::process::id());
194                let _ = f.write_all(payload.as_bytes());
195                drop(f);
196                return Ok(FileLockGuard {
197                    lock_path: lock_path.to_path_buf(),
198                });
199            }
200            Err(e)
201                if e.kind() == std::io::ErrorKind::AlreadyExists
202                    || (cfg!(windows) && e.kind() == std::io::ErrorKind::PermissionDenied) =>
203            {
204                if e.kind() == std::io::ErrorKind::AlreadyExists
205                    && is_lock_stale(lock_path, stale_after)
206                {
207                    let _ = fs::remove_file(lock_path);
208                    continue;
209                }
210                if Instant::now() >= deadline {
211                    return Err(format!(
212                        "timed out acquiring repository ref gate lock {}",
213                        lock_path.display()
214                    ));
215                }
216                std::thread::sleep(Duration::from_millis(backoff_ms));
217                backoff_ms = (backoff_ms * 2).min(20);
218            }
219            Err(e) => {
220                return Err(format!(
221                    "failed to create repository ref gate lock {}: {e}",
222                    lock_path.display()
223                ));
224            }
225        }
226    }
227}
228
229/// Acquire the per-repository serialization lock (both in-process and cross-process
230/// `<common_dir>/arks-ref-gate.lock`).
231pub fn acquire_repo_ref_lock(common_dir: &Path) -> Result<RefGateGuard, String> {
232    let key = canonical_repo_key(common_dir);
233    let in_proc = acquire_in_process_repo_lock(&key);
234    let lock_path = common_dir.join(REF_GATE_LOCK_FILE);
235    let file_lock = acquire_file_lock_with(
236        &lock_path,
237        Duration::from_secs(REF_GATE_STALE_SECS),
238        Duration::from_secs(REF_GATE_TIMEOUT_SECS),
239    )?;
240    Ok(RefGateGuard {
241        common_dir_key: key,
242        _file_lock: file_lock,
243        _in_proc: in_proc,
244    })
245}
246
247fn zero_oid(kind: OidKind) -> Result<Oid, GateReject> {
248    let zeros = [0u8; 32];
249    Oid::from_bytes(kind, &zeros[..kind.digest_len()])
250        .map_err(|e| GateReject::Internal(format!("zero oid error: {e}")))
251}
252
253fn zero_hex(kind: OidKind) -> String {
254    "0".repeat(kind.hex_len())
255}
256
257pub(crate) fn branch_rule_matches(pattern: &str, branch: &str) -> bool {
258    pattern == "*" || pattern == branch || glob_match(pattern, branch)
259}
260
261fn glob_match(pattern: &str, text: &str) -> bool {
262    let p: Vec<char> = pattern.chars().collect();
263    let t: Vec<char> = text.chars().collect();
264    let (mut pi, mut ti) = (0usize, 0usize);
265    let (mut star_pi, mut star_ti) = (None, 0usize);
266    while ti < t.len() {
267        if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
268            pi += 1;
269            ti += 1;
270        } else if pi < p.len() && p[pi] == '*' {
271            star_pi = Some(pi);
272            star_ti = ti;
273            pi += 1;
274        } else if let Some(sp) = star_pi {
275            pi = sp + 1;
276            star_ti += 1;
277            ti = star_ti;
278        } else {
279            return false;
280        }
281    }
282    while pi < p.len() && p[pi] == '*' {
283        pi += 1;
284    }
285    pi == p.len()
286}
287
288fn is_valid_refname(refname: &str) -> bool {
289    !refname.is_empty()
290        && !refname.starts_with('/')
291        && !refname.ends_with('/')
292        && !refname.contains("..")
293        && !refname.contains('\\')
294        && !refname.contains("@{")
295        && !refname.bytes().any(|b| b <= 0x20 || b == 0x7f)
296}
297
298fn is_internal_arks_ref(refname: &str) -> bool {
299    refname == "refs/arks" || refname.starts_with("refs/arks/")
300}
301
302fn is_commit_ancestor(repo: &Repository, ancestor: Oid, descendant: Oid) -> bool {
303    if ancestor == descendant {
304        return true;
305    }
306    let mut queue = VecDeque::new();
307    let mut visited = HashSet::new();
308    queue.push_back(descendant);
309    visited.insert(descendant);
310    let mut steps = 0usize;
311    while let Some(cur) = queue.pop_front() {
312        steps += 1;
313        if steps > 100_000 {
314            break;
315        }
316        let Ok(obj) = repo.get_object(&cur) else {
317            continue;
318        };
319        if obj.kind != ObjectKind::Commit {
320            continue;
321        }
322        let Ok(commit) = Commit::decode(&obj.payload) else {
323            continue;
324        };
325        for parent in commit.parents {
326            if parent == ancestor {
327                return true;
328            }
329            if visited.insert(parent) {
330                queue.push_back(parent);
331            }
332        }
333    }
334    false
335}
336
337/// Check non-bare checkout safety per `receive.denyCurrentBranch` / `receive.denyDeleteCurrent`.
338///
339/// Returns:
340/// - `Ok(true)` when `receive.denyCurrentBranch=updateInstead` is configured, `refname` is
341///   currently checked out, and the working tree is clean (caller must sync worktree after CAS).
342/// - `Ok(false)` when bare, `refname` is not checked out, or config allows update without sync.
343/// - `Err(GateReject::Conflict(..))` when updating/deleting the checked-out branch is refused
344///   (default `refuse`) or the working tree has uncommitted changes under `updateInstead`.
345pub fn check_non_bare_deny_current_branch(
346    repo: &Repository,
347    refname: &str,
348    new_oid: Option<&Oid>,
349) -> Result<bool, GateReject> {
350    check_non_bare_deny_current_branch_with_default(repo, refname, new_oid, false)
351}
352
353/// Like [`check_non_bare_deny_current_branch`], except when `receive.denyCurrentBranch` is
354/// unset in repository config and `default_update_instead` is `true` (used for interactive
355/// Web UI merges/edits on a local non-bare checkout), defaults to guarded `updateInstead`
356/// (still failing closed on dirty working trees and syncing both worktree and `.git/index`).
357pub(crate) fn check_non_bare_deny_current_branch_with_default(
358    repo: &Repository,
359    refname: &str,
360    new_oid: Option<&Oid>,
361    default_update_instead: bool,
362) -> Result<bool, GateReject> {
363    let cfg = ConfigSet::load(Some(repo.git_dir()));
364    if cfg.get_bool("core.bare") == Some(true) {
365        return Ok(false);
366    }
367    let Some(work_tree) = repo.work_tree() else {
368        return Ok(false);
369    };
370    let head_matches =
371        matches!(repo.head_target(), Ok(RefTarget::Symbolic(ref sym)) if sym == refname);
372    if !head_matches {
373        return Ok(false);
374    }
375
376    if new_oid.is_none() {
377        let mode = cfg
378            .get("receive.denydeletecurrent")
379            .unwrap_or_else(|| "refuse".to_string());
380        return match mode.trim().to_ascii_lowercase().as_str() {
381            "ignore" | "false" | "warn" => Ok(false),
382            _ => Err(GateReject::Conflict(format!(
383                "refusing to delete checked-out branch '{refname}' in non-bare repository (receive.denyDeleteCurrent)"
384            ))),
385        };
386    }
387
388    let mode = cfg.get("receive.denycurrentbranch").unwrap_or_else(|| {
389        if default_update_instead {
390            "updateInstead".to_string()
391        } else {
392            "refuse".to_string()
393        }
394    });
395    match mode.trim().to_ascii_lowercase().as_str() {
396        "ignore" | "false" | "warn" => Ok(false),
397        "updateinstead" => {
398            verify_worktree_clean_for_update_instead(
399                repo,
400                work_tree,
401                refname,
402                new_oid,
403                cfg.autocrlf_to_lf(),
404            )?;
405            Ok(true)
406        }
407        _ => Err(GateReject::Conflict(format!(
408            "refusing to update checked-out branch '{refname}' in non-bare repository (receive.denyCurrentBranch=refuse)"
409        ))),
410    }
411}
412
413fn read_worktree_entry_bytes(path: &Path) -> Option<(Vec<u8>, bool)> {
414    let meta = fs::symlink_metadata(path).ok()?;
415    if meta.file_type().is_symlink() {
416        let target = fs::read_link(path).ok()?;
417        Some((target.to_string_lossy().as_bytes().to_vec(), true))
418    } else if meta.is_file() {
419        Some((fs::read(path).ok()?, false))
420    } else {
421        None
422    }
423}
424
425fn crlf_to_lf(bytes: &[u8]) -> Vec<u8> {
426    let mut out = Vec::with_capacity(bytes.len());
427    let mut i = 0;
428    while i < bytes.len() {
429        if bytes[i] == b'\r' && i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
430            out.push(b'\n');
431            i += 2;
432        } else {
433            out.push(bytes[i]);
434            i += 1;
435        }
436    }
437    out
438}
439
440fn worktree_bytes_match_blob(
441    repo: &Repository,
442    disk_bytes: &[u8],
443    is_symlink: bool,
444    expected_oid: &Oid,
445    autocrlf: bool,
446) -> Result<bool, GateReject> {
447    let format = repo.object_format();
448    let actual_oid = RawObject::new(ObjectKind::Blob, disk_bytes.to_vec())
449        .oid(format)
450        .map_err(|e| GateReject::Internal(format!("blob hash error: {e}")))?;
451    if actual_oid == *expected_oid {
452        return Ok(true);
453    }
454    if !is_symlink
455        && autocrlf
456        && !disk_bytes[..disk_bytes.len().min(8000)].contains(&0)
457        && disk_bytes.windows(2).any(|w| w == b"\r\n")
458    {
459        let normalized = crlf_to_lf(disk_bytes);
460        let norm_oid = RawObject::new(ObjectKind::Blob, normalized)
461            .oid(format)
462            .map_err(|e| GateReject::Internal(format!("blob hash error: {e}")))?;
463        return Ok(norm_oid == *expected_oid);
464    }
465    Ok(false)
466}
467
468fn verify_worktree_clean_for_update_instead(
469    repo: &Repository,
470    work_tree: &Path,
471    refname: &str,
472    new_oid: Option<&Oid>,
473    autocrlf: bool,
474) -> Result<(), GateReject> {
475    let head_files = match repo.refs().resolve(refname).ok() {
476        Some(cur_head) => commit_tree_map(repo, &cur_head)
477            .map_err(|e| GateReject::Internal(format!("failed to read HEAD tree: {e}")))?,
478        None => HashMap::new(),
479    };
480
481    for (rel_path, expected_oid) in &head_files {
482        if !is_safe_worktree_rel_path(rel_path) {
483            return Err(GateReject::Conflict(format!(
484                "refusing updateInstead on '{refname}': unsafe path '{rel_path}'"
485            )));
486        }
487        let full = work_tree.join(rel_path);
488        let Some((disk_bytes, is_symlink)) = read_worktree_entry_bytes(&full) else {
489            return Err(GateReject::Conflict(format!(
490                "refusing updateInstead on '{refname}': working tree has missing or modified tracked path '{rel_path}'"
491            )));
492        };
493        if !worktree_bytes_match_blob(repo, &disk_bytes, is_symlink, expected_oid, autocrlf)? {
494            return Err(GateReject::Conflict(format!(
495                "refusing updateInstead on '{refname}': working tree has uncommitted modifications at '{rel_path}'"
496            )));
497        }
498    }
499
500    if let Some(target_oid) = new_oid {
501        if let Ok(new_files) = commit_tree_map(repo, target_oid) {
502            for (rel_path, new_blob_oid) in new_files {
503                if head_files.contains_key(&rel_path) {
504                    continue;
505                }
506                if !is_safe_worktree_rel_path(&rel_path) {
507                    return Err(GateReject::Conflict(format!(
508                        "refusing updateInstead on '{refname}': unsafe target path '{rel_path}'"
509                    )));
510                }
511                let full = work_tree.join(&rel_path);
512                if fs::symlink_metadata(&full).is_ok() {
513                    let matches_new = read_worktree_entry_bytes(&full)
514                        .and_then(|(b, is_sym)| {
515                            worktree_bytes_match_blob(repo, &b, is_sym, &new_blob_oid, autocrlf)
516                                .ok()
517                        })
518                        .unwrap_or(false);
519                    if !matches_new {
520                        return Err(GateReject::Conflict(format!(
521                            "refusing updateInstead on '{refname}': untracked working tree file '{rel_path}' would be overwritten"
522                        )));
523                    }
524                }
525            }
526        }
527    }
528    Ok(())
529}
530
531fn is_safe_worktree_rel_path(rel: &str) -> bool {
532    !rel.is_empty()
533        && !rel.starts_with('/')
534        && !rel.ends_with('/')
535        && !rel.contains('\\')
536        && !rel
537            .split('/')
538            .any(|seg| seg.is_empty() || seg == "." || seg == ".." || seg == ".git")
539}
540
541fn flatten_tree_with_modes(
542    repo: &Repository,
543    tree_oid: &Oid,
544    prefix: &str,
545    out: &mut HashMap<String, (TreeMode, Oid)>,
546) -> Result<(), GateReject> {
547    let raw = repo
548        .get_object(tree_oid)
549        .map_err(|e| GateReject::Internal(format!("worktree sync load tree: {e}")))?;
550    if raw.kind != ObjectKind::Tree {
551        return Err(GateReject::Internal(
552            "worktree sync: object is not a tree".into(),
553        ));
554    }
555    let tree = arks_object::Tree::decode(&raw.payload, repo.oid_kind())
556        .map_err(|e| GateReject::Internal(format!("worktree sync decode tree: {e}")))?;
557    for entry in tree.entries {
558        let path = if prefix.is_empty() {
559            entry.name
560        } else {
561            format!("{prefix}/{}", entry.name)
562        };
563        if entry.mode == TreeMode::Tree {
564            flatten_tree_with_modes(repo, &entry.oid, &path, out)?;
565        } else {
566            out.insert(path, (entry.mode, entry.oid));
567        }
568    }
569    Ok(())
570}
571
572pub(crate) fn sync_worktree_for_update_instead(
573    repo: &Repository,
574    old_head: Option<&Oid>,
575    new_oid: &Oid,
576) -> Result<(), GateReject> {
577    let Some(work_tree) = repo.work_tree() else {
578        return Ok(());
579    };
580    let old_files = old_head
581        .and_then(|o| commit_tree_map(repo, o).ok())
582        .unwrap_or_default();
583    let new_commit_raw = repo
584        .get_object(new_oid)
585        .map_err(|e| GateReject::Internal(format!("worktree sync load commit: {e}")))?;
586    let new_commit = Commit::decode(&new_commit_raw.payload)
587        .map_err(|e| GateReject::Internal(format!("worktree sync decode commit: {e}")))?;
588    let mut new_map: HashMap<String, (TreeMode, Oid)> = HashMap::new();
589    flatten_tree_with_modes(repo, &new_commit.tree, "", &mut new_map)?;
590
591    // Remove tracked files deleted in the new commit.
592    for old_path in old_files.keys() {
593        if !new_map.contains_key(old_path) && is_safe_worktree_rel_path(old_path) {
594            let full = work_tree.join(old_path);
595            let _ = fs::remove_file(&full);
596            let mut cur = full.parent();
597            while let Some(dir) = cur {
598                if dir == work_tree {
599                    break;
600                }
601                if fs::remove_dir(dir).is_err() {
602                    break;
603                }
604                cur = dir.parent();
605            }
606        }
607    }
608
609    // Materialize added or modified files in the new commit.
610    for (rel_path, (mode, blob_oid)) in &new_map {
611        if !is_safe_worktree_rel_path(rel_path) {
612            continue;
613        }
614        if mode == &TreeMode::Gitlink {
615            continue;
616        }
617        if old_files.get(rel_path) == Some(blob_oid) && work_tree.join(rel_path).exists() {
618            continue;
619        }
620        let Ok(blob) = repo.get_object(blob_oid) else {
621            continue;
622        };
623        let full = work_tree.join(rel_path);
624        if let Some(parent) = full.parent() {
625            let _ = fs::create_dir_all(parent);
626        }
627        let _ = fs::remove_file(&full);
628        #[cfg(unix)]
629        if mode == &TreeMode::Symlink {
630            let target = String::from_utf8_lossy(&blob.payload);
631            let _ = std::os::unix::fs::symlink(target.as_ref(), &full);
632            continue;
633        }
634        if fs::write(&full, &blob.payload).is_ok() {
635            #[cfg(unix)]
636            {
637                use std::os::unix::fs::PermissionsExt;
638                let perm = if mode == &TreeMode::Executable {
639                    0o755
640                } else {
641                    0o644
642                };
643                let _ = fs::set_permissions(&full, fs::Permissions::from_mode(perm));
644            }
645        }
646    }
647
648    // Atomically synchronize `.git/index` to `new_commit.tree` so `git status` and
649    // `git diff --cached` never see reverse-deletions after non-bare checkout updates.
650    sync_index_for_tree_map(repo, work_tree, &new_map)?;
651    Ok(())
652}
653
654fn sync_index_for_tree_map(
655    repo: &Repository,
656    work_tree: &Path,
657    new_map: &HashMap<String, (TreeMode, Oid)>,
658) -> Result<(), GateReject> {
659    let mut entries = Vec::with_capacity(new_map.len());
660    for (rel_path, (mode, oid)) in new_map {
661        let mode_u32 = match mode {
662            TreeMode::Gitlink => 0o160000,
663            TreeMode::Symlink => 0o120000,
664            TreeMode::Executable => 0o100755,
665            TreeMode::File | TreeMode::Tree => 0o100644,
666        };
667        let (ctime_sec, ctime_nsec, mtime_sec, mtime_nsec, dev, ino, uid, gid, size) =
668            if *mode == TreeMode::Gitlink {
669                (0, 0, 0, 0, 0, 0, 0, 0, 0)
670            } else if let Ok(meta) = fs::symlink_metadata(work_tree.join(rel_path)) {
671                let (ms, mn) = meta
672                    .modified()
673                    .ok()
674                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
675                    .map(|d| (d.as_secs() as u32, d.subsec_nanos()))
676                    .unwrap_or((0, 0));
677                let sz = meta.len().min(u32::MAX as u64) as u32;
678                #[cfg(unix)]
679                let (cs, cn, d, i, u, g) = {
680                    use std::os::unix::fs::MetadataExt;
681                    (
682                        meta.ctime() as u32,
683                        meta.ctime_nsec() as u32,
684                        meta.dev() as u32,
685                        meta.ino() as u32,
686                        meta.uid(),
687                        meta.gid(),
688                    )
689                };
690                #[cfg(not(unix))]
691                let (cs, cn, d, i, u, g) = (ms, mn, 0u32, 0u32, 0u32, 0u32);
692                (cs, cn, ms, mn, d, i, u, g, sz)
693            } else {
694                (0, 0, 0, 0, 0, 0, 0, 0, 0)
695            };
696        let flags = rel_path.len().min(0x0fff) as u16;
697        entries.push(arks_index::IndexEntry {
698            ctime_sec,
699            ctime_nsec,
700            mtime_sec,
701            mtime_nsec,
702            dev,
703            ino,
704            mode: mode_u32,
705            uid,
706            gid,
707            size,
708            oid: *oid,
709            flags,
710            flags_extended: None,
711            path: rel_path.clone(),
712        });
713    }
714    arks_index::sort_entries(&mut entries);
715    let idx = arks_index::Index {
716        version: 2,
717        entries,
718        extensions: Vec::new(),
719    };
720    let encoded = idx
721        .write(repo.oid_kind())
722        .map_err(|e| GateReject::Internal(format!("index encode failed: {e}")))?;
723    arks_index::write_index_locked(&repo.index_path(), &encoded)
724        .map_err(|e| GateReject::Internal(format!("index write failed: {e}")))?;
725    Ok(())
726}
727
728/// Enforce internal ref isolation, archived-repo immutability, `ForgeStore.branch_rules`
729/// (`block_delete`, `block_force_push`), non-ff rules, and the
730/// installed process-wide [`PushPolicy`](crate::push_policy::PushPolicy).
731pub fn enforce_branch_rules_and_policy(
732    repo: &Repository,
733    upd: &GatedRefUpdate,
734) -> Result<(), GateReject> {
735    if !is_valid_refname(&upd.refname) {
736        return Err(GateReject::Forbidden(format!(
737            "invalid ref name '{}'",
738            upd.refname
739        )));
740    }
741    // (a) Internal `refs/arks/*` confidentiality unless explicitly allowed.
742    if !upd.allow_internal_arks_ref && is_internal_arks_ref(&upd.refname) {
743        return Err(GateReject::Forbidden(format!(
744            "ref '{}' is reserved for internal arks metadata",
745            upd.refname
746        )));
747    }
748
749    // (b) ForgeStore corrupt (fail-closed) and archived checks.
750    let store = ForgeStore::load_shared(repo.common_dir());
751    if store.corrupt {
752        return Err(GateReject::Internal(
753            "forge store is corrupted; refusing ref update (fail-closed)".into(),
754        ));
755    }
756    if store.archived {
757        return Err(GateReject::Forbidden(
758            "repository is archived (read-only)".into(),
759        ));
760    }
761
762    let live_old = repo.refs().resolve(&upd.refname).ok();
763
764    // Enforce fast-forward unless caller explicitly opted in to non-ff.
765    if let (Some(old_oid), Some(new_oid)) = (live_old, upd.new_oid) {
766        if old_oid != new_oid && !upd.allow_non_ff && !is_commit_ancestor(repo, old_oid, new_oid) {
767            return Err(GateReject::Conflict(format!(
768                "non-fast-forward update rejected for '{}'",
769                upd.refname
770            )));
771        }
772    }
773
774    // (c) `ForgeStore.branch_rules` enforcement for `refs/heads/<branch>`.
775    if let Some(branch) = upd.refname.strip_prefix("refs/heads/") {
776        let matching: Vec<_> = store
777            .branch_rules
778            .iter()
779            .filter(|r| branch_rule_matches(&r.pattern, branch))
780            .collect();
781
782        if upd.new_oid.is_none() {
783            if matching.iter().any(|r| r.block_delete) {
784                return Err(GateReject::Forbidden(format!(
785                    "branch deletion of '{branch}' blocked by branch protection rule"
786                )));
787            }
788        } else if let Some(new_oid) = upd.new_oid {
789            if let Some(old_oid) = live_old {
790                if old_oid != new_oid
791                    && matching.iter().any(|r| r.block_force_push)
792                    && !is_commit_ancestor(repo, old_oid, new_oid)
793                {
794                    return Err(GateReject::Forbidden(format!(
795                        "force push to '{branch}' blocked by branch protection rule"
796                    )));
797                }
798            }
799        }
800    }
801
802    // (d) Process-wide `installed_push_policy()` rulesets.
803    if let Some(policy) = installed_push_policy() {
804        let zero = zero_oid(repo.oid_kind())?;
805        let old = upd.old_oid.or(live_old).unwrap_or(zero);
806        let new = upd.new_oid.unwrap_or(zero);
807        let ref_upd = RefUpdate {
808            name: upd.refname.clone(),
809            old,
810            new,
811        };
812        let results = verdicts(Some(policy.as_ref()), repo, &upd.pusher, &[ref_upd]);
813        if let Some(Some(reason)) = results.into_iter().next() {
814            return Err(GateReject::Forbidden(reason));
815        }
816    }
817
818    Ok(())
819}
820
821/// Apply a single gated ref update acquiring the per-repository [`RefGateGuard`].
822/// Drops [`RefGateGuard`] BEFORE dispatching synchronous webhooks and CI workflows.
823pub fn apply_gated_ref_update(
824    repo: &mut Repository,
825    upd: &GatedRefUpdate,
826) -> Result<(), GateReject> {
827    let guard = acquire_repo_ref_lock(repo.common_dir()).map_err(GateReject::Internal)?;
828    let live_old = apply_gated_ref_update_locked_full(repo, upd, &guard, true, false)?;
829    drop(guard);
830    post_receive_external_effects(
831        repo,
832        &[(upd.refname.clone(), live_old, upd.new_oid)],
833        upd.trigger_ci,
834    );
835    Ok(())
836}
837
838/// Apply a single gated ref update when the caller already holds [`RefGateGuard`]
839/// for `repo.common_dir()`. Executes only lock-scoped effects (`update_server_info`);
840/// callers needing external webhooks/CI should invoke [`post_receive_external_effects`]
841/// after dropping `guard`.
842pub fn apply_gated_ref_update_locked(
843    repo: &mut Repository,
844    upd: &GatedRefUpdate,
845    guard: &RefGateGuard,
846) -> Result<(), GateReject> {
847    apply_gated_ref_update_locked_full(repo, upd, guard, true, false).map(|_| ())
848}
849
850/// Interactive Web UI entry point: respects explicit `receive.denyCurrentBranch`
851/// config, and when unset defaults to guarded `updateInstead` (failing closed on dirty worktrees
852/// while syncing both working tree and `.git/index` when clean).
853/// Drops [`RefGateGuard`] BEFORE dispatching synchronous webhooks and CI workflows.
854pub(crate) fn apply_gated_ref_update_interactive(
855    repo: &mut Repository,
856    upd: &GatedRefUpdate,
857) -> Result<(), GateReject> {
858    let guard = acquire_repo_ref_lock(repo.common_dir()).map_err(GateReject::Internal)?;
859    let live_old = apply_gated_ref_update_locked_full(repo, upd, &guard, true, true)?;
860    drop(guard);
861    post_receive_external_effects(
862        repo,
863        &[(upd.refname.clone(), live_old, upd.new_oid)],
864        upd.trigger_ci,
865    );
866    Ok(())
867}
868
869fn apply_gated_ref_update_locked_full(
870    repo: &mut Repository,
871    upd: &GatedRefUpdate,
872    guard: &RefGateGuard,
873    reconcile_internal: bool,
874    default_update_instead: bool,
875) -> Result<Option<Oid>, GateReject> {
876    let repo_key = canonical_repo_key(repo.common_dir());
877    if guard.common_dir_key != repo_key {
878        return Err(GateReject::Internal(
879            "RefGateGuard held for a different repository".into(),
880        ));
881    }
882
883    let live_old = repo.refs().resolve(&upd.refname).ok();
884    if let Some(expected_old) = upd.old_oid {
885        match live_old {
886            Some(actual) if actual == expected_old => {}
887            Some(actual) => {
888                return Err(GateReject::Conflict(format!(
889                    "CAS mismatch on '{}': expected {}, found {}",
890                    upd.refname,
891                    expected_old.to_hex(),
892                    actual.to_hex()
893                )));
894            }
895            None => {
896                return Err(GateReject::Conflict(format!(
897                    "CAS mismatch on '{}': expected {}, ref does not exist",
898                    upd.refname,
899                    expected_old.to_hex()
900                )));
901            }
902        }
903    }
904
905    if let Some(new_oid) = upd.new_oid {
906        if repo.get_object(&new_oid).is_err() {
907            return Err(GateReject::PreconditionFailed(format!(
908                "target object {} missing from repository object store",
909                new_oid.to_hex()
910            )));
911        }
912    }
913
914    enforce_branch_rules_and_policy(repo, upd)?;
915    let should_update_worktree = check_non_bare_deny_current_branch_with_default(
916        repo,
917        &upd.refname,
918        upd.new_oid.as_ref(),
919        default_update_instead,
920    )?;
921
922    let old_hex = live_old
923        .map(|o| o.to_hex())
924        .unwrap_or_else(|| zero_hex(repo.oid_kind()));
925    let new_hex = upd
926        .new_oid
927        .map(|o| o.to_hex())
928        .unwrap_or_else(|| zero_hex(repo.oid_kind()));
929    let stdin_line = format!("{old_hex} {new_hex} {}\n", upd.refname);
930    let hook_env = HookEnv::default();
931
932    if run_pre_receive(repo.git_dir(), stdin_line.as_bytes(), &hook_env)
933        .map_err(|e| GateReject::Internal(e.to_string()))?
934        == HookGate::Decline
935    {
936        return Err(GateReject::Forbidden("pre-receive hook declined".into()));
937    }
938    if run_update(repo.git_dir(), &upd.refname, &old_hex, &new_hex, &hook_env)
939        .map_err(|e| GateReject::Internal(e.to_string()))?
940        == HookGate::Decline
941    {
942        return Err(GateReject::Forbidden("update hook declined".into()));
943    }
944
945    if let Some(new_oid) = upd.new_oid {
946        repo.refs_mut()
947            .update(&upd.refname, &new_oid, live_old.as_ref())
948            .map_err(|e| GateReject::Conflict(format!("atomic ref update failed: {e}")))?;
949        if should_update_worktree {
950            if let Err(rej) = sync_worktree_for_update_instead(repo, live_old.as_ref(), &new_oid) {
951                if let Some(prev) = live_old.as_ref() {
952                    let _ = repo.refs_mut().update(&upd.refname, prev, Some(&new_oid));
953                } else {
954                    let _ = repo.refs_mut().delete(&upd.refname, Some(&new_oid));
955                }
956                return Err(rej);
957            }
958        }
959    } else {
960        repo.refs_mut()
961            .delete(&upd.refname, live_old.as_ref())
962            .map_err(|e| GateReject::Conflict(format!("atomic ref delete failed: {e}")))?;
963    }
964
965    run_post_receive(repo.git_dir(), stdin_line.as_bytes(), &hook_env);
966    run_post_update(repo.git_dir(), &[upd.refname.as_str()], &hook_env);
967
968    post_receive_locked_effects(
969        repo,
970        &[(upd.refname.clone(), live_old, upd.new_oid)],
971        reconcile_internal,
972    );
973    Ok(live_old)
974}
975
976/// Shared post-receive side effects combining lock-scoped repository refreshes and
977/// external notifications:
978/// 1. Refresh dumb HTTP `info/refs` & `objects/info/packs` (best-effort).
979/// 2. Dispatch signed `"push"` webhook events for non-internal refs.
980/// 3. Trigger opt-in local Actions CI workflows when `trigger_ci` is true.
981pub fn post_receive_side_effects(
982    repo: &Repository,
983    updates: &[(String, Option<Oid>, Option<Oid>)],
984    trigger_ci: bool,
985) {
986    post_receive_locked_effects(repo, updates, true);
987    post_receive_external_effects(repo, updates, trigger_ci);
988}
989
990/// Lock-scoped post-receive effects (run while holding [`RefGateGuard`]):
991/// 1. Best-effort dumb HTTP `info/refs` & `objects/info/packs` refresh.
992pub(crate) fn post_receive_locked_effects(
993    repo: &Repository,
994    updates: &[(String, Option<Oid>, Option<Oid>)],
995    _reconcile_internal: bool,
996) {
997    if updates.is_empty() {
998        return;
999    }
1000
1001    // Best-effort dumb HTTP metadata refresh (`info/refs`, `objects/info/packs`).
1002    let _ = crate::dumb::update_server_info(repo);
1003}
1004
1005/// External post-receive effects (MUST run AFTER dropping [`RefGateGuard`]):
1006/// 3. Dispatch signed `"push"` webhook events for public/normal refs.
1007/// 3. Trigger opt-in local Actions CI workflows when `trigger_ci` is true.
1008pub(crate) fn post_receive_external_effects(
1009    repo: &Repository,
1010    updates: &[(String, Option<Oid>, Option<Oid>)],
1011    trigger_ci: bool,
1012) {
1013    if updates.is_empty() {
1014        return;
1015    }
1016
1017    // 3. Dispatch `"push"` webhooks for public/normal refs (skip internal `refs/arks/*`).
1018    let zero = zero_hex(repo.oid_kind());
1019    let mut has_non_internal_update = false;
1020    for (refname, old_oid, new_oid) in updates {
1021        if is_internal_arks_ref(refname) {
1022            continue;
1023        }
1024        if new_oid.is_some() {
1025            has_non_internal_update = true;
1026        }
1027        let before = old_oid.map(|o| o.to_hex()).unwrap_or_else(|| zero.clone());
1028        let after = new_oid.map(|o| o.to_hex()).unwrap_or_else(|| zero.clone());
1029        let payload = serde_json::json!({
1030            "event": "push",
1031            "ref": refname,
1032            "before": before,
1033            "after": after,
1034        })
1035        .to_string();
1036        crate::web_ui::dispatch_webhook_event(repo.common_dir(), "push", &payload);
1037    }
1038
1039    // 4. Trigger opt-in local Actions CI workflows.
1040    if trigger_ci && has_non_internal_update {
1041        crate::web_ui::trigger_event_workflows(repo.common_dir(), "push");
1042    }
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047    use super::*;
1048    use crate::web_ui::store::BranchRule;
1049    use arks_object::{Signature, Tree, TreeEntry};
1050    use arks_store::ObjectStore;
1051    use tempfile::TempDir;
1052
1053    fn make_commit(
1054        repo: &mut Repository,
1055        parents: Vec<Oid>,
1056        files: &[(&str, &[u8])],
1057        msg: &str,
1058    ) -> (Oid, Oid) {
1059        let fmt = repo.object_format();
1060        let mut entries = Vec::new();
1061        for (name, content) in files {
1062            let blob_oid = repo
1063                .store_mut()
1064                .put(fmt, &RawObject::new(ObjectKind::Blob, content.to_vec()))
1065                .unwrap();
1066            entries.push(TreeEntry {
1067                mode: TreeMode::File,
1068                name: (*name).to_string(),
1069                oid: blob_oid,
1070            });
1071        }
1072        entries.sort_by(|a, b| a.name.cmp(&b.name));
1073        let tree_oid = repo
1074            .store_mut()
1075            .put(
1076                fmt,
1077                &RawObject::new(ObjectKind::Tree, Tree { entries }.encode().unwrap()),
1078            )
1079            .unwrap();
1080        let sig = Signature {
1081            name: "test".into(),
1082            email: "test@example.invalid".into(),
1083            timestamp: 1_700_000_000,
1084            timezone: "+0000".into(),
1085        };
1086        let commit = Commit {
1087            tree: tree_oid,
1088            parents,
1089            author: sig.clone(),
1090            committer: sig,
1091            gpgsig: None,
1092            message: msg.into(),
1093        };
1094        let oid = repo
1095            .store_mut()
1096            .put(
1097                fmt,
1098                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
1099            )
1100            .unwrap();
1101        (oid, tree_oid)
1102    }
1103
1104    fn init_bare_classic(root: &Path) -> (Repository, Oid) {
1105        fs::create_dir_all(root.join("objects")).unwrap();
1106        fs::create_dir_all(root.join("refs/heads")).unwrap();
1107        fs::write(root.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
1108        fs::write(root.join("config"), b"[core]\n\tbare = true\n").unwrap();
1109        let mut repo = Repository::open(root).unwrap();
1110        let (c1, _) = make_commit(&mut repo, Vec::new(), &[("a.txt", b"v1\n")], "init\n");
1111        repo.refs_mut()
1112            .update("refs/heads/main", &c1, None)
1113            .unwrap();
1114        (repo, c1)
1115    }
1116
1117    fn init_non_bare(root: &Path) -> (Repository, Oid) {
1118        let git_dir = root.join(".git");
1119        fs::create_dir_all(git_dir.join("objects")).unwrap();
1120        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
1121        fs::write(git_dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
1122        fs::write(git_dir.join("config"), b"[core]\n\tbare = false\n").unwrap();
1123        fs::write(root.join("a.txt"), b"v1\n").unwrap();
1124        let mut repo = Repository::open(&git_dir).unwrap();
1125        let (c1, _) = make_commit(&mut repo, Vec::new(), &[("a.txt", b"v1\n")], "init\n");
1126        repo.refs_mut()
1127            .update("refs/heads/main", &c1, None)
1128            .unwrap();
1129        (repo, c1)
1130    }
1131
1132    #[test]
1133    fn ref_gate_rejects_internal_refs_and_archived_and_respects_od1() {
1134        let tmp = TempDir::new().unwrap();
1135        let (mut repo, c1) = init_bare_classic(tmp.path());
1136        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "second\n");
1137
1138        // Internal refs/arks/* rejected unless allow_internal_arks_ref is true.
1139        let bad_internal = GatedRefUpdate {
1140            refname: "refs/arks/v2/keep/fake".into(),
1141            old_oid: None,
1142            new_oid: Some(c2),
1143            allow_non_ff: true,
1144            pusher: Pusher::local(),
1145            allow_internal_arks_ref: false,
1146            trigger_ci: false,
1147        };
1148        assert!(matches!(
1149            apply_gated_ref_update(&mut repo, &bad_internal),
1150            Err(GateReject::Forbidden(_))
1151        ));
1152
1153        // Normal update succeeds AND preserves OD-1 (does not create `.git/arks/v2/`).
1154        let good = GatedRefUpdate {
1155            refname: "refs/heads/main".into(),
1156            old_oid: Some(c1),
1157            new_oid: Some(c2),
1158            allow_non_ff: false,
1159            pusher: Pusher::local(),
1160            allow_internal_arks_ref: false,
1161            trigger_ci: false,
1162        };
1163        apply_gated_ref_update(&mut repo, &good).unwrap();
1164        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
1165        assert!(
1166            !repo.common_dir().join("arks").join("v2").exists(),
1167            "RefUpdateGate must not create arks/v2/ on a classic repository"
1168        );
1169        assert!(
1170            repo.common_dir().join("info/refs").is_file(),
1171            "RefUpdateGate must refresh dumb HTTP info/refs"
1172        );
1173
1174        // Archived repo rejects updates.
1175        ForgeStore::update(repo.common_dir(), |s| s.archived = true).unwrap();
1176        let (c3, _) = make_commit(&mut repo, vec![c2], &[("a.txt", b"v3\n")], "third\n");
1177        let archived_upd = GatedRefUpdate {
1178            refname: "refs/heads/main".into(),
1179            old_oid: Some(c2),
1180            new_oid: Some(c3),
1181            allow_non_ff: false,
1182            pusher: Pusher::local(),
1183            allow_internal_arks_ref: false,
1184            trigger_ci: false,
1185        };
1186        assert!(matches!(
1187            apply_gated_ref_update(&mut repo, &archived_upd),
1188            Err(GateReject::Forbidden(_))
1189        ));
1190    }
1191
1192    #[test]
1193    fn ref_gate_enforces_branch_rules_delete_and_force_push() {
1194        let tmp = TempDir::new().unwrap();
1195        let (mut repo, c1) = init_bare_classic(tmp.path());
1196        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "c2\n");
1197        let (c_div, _) = make_commit(&mut repo, Vec::new(), &[("a.txt", b"div\n")], "div\n");
1198
1199        ForgeStore::update(repo.common_dir(), |s| {
1200            s.branch_rules.push(BranchRule {
1201                pattern: "main".into(),
1202                require_pr: false,
1203                block_force_push: true,
1204                block_delete: true,
1205                required_reviews: 0,
1206            });
1207        })
1208        .unwrap();
1209
1210        // Deletion blocked.
1211        let del = GatedRefUpdate {
1212            refname: "refs/heads/main".into(),
1213            old_oid: Some(c1),
1214            new_oid: None,
1215            allow_non_ff: true,
1216            pusher: Pusher::local(),
1217            allow_internal_arks_ref: false,
1218            trigger_ci: false,
1219        };
1220        assert!(matches!(
1221            apply_gated_ref_update(&mut repo, &del),
1222            Err(GateReject::Forbidden(_))
1223        ));
1224
1225        // Force-push blocked even when allow_non_ff is true.
1226        let force = GatedRefUpdate {
1227            refname: "refs/heads/main".into(),
1228            old_oid: Some(c1),
1229            new_oid: Some(c_div),
1230            allow_non_ff: true,
1231            pusher: Pusher::local(),
1232            allow_internal_arks_ref: false,
1233            trigger_ci: false,
1234        };
1235        assert!(matches!(
1236            apply_gated_ref_update(&mut repo, &force),
1237            Err(GateReject::Forbidden(_))
1238        ));
1239
1240        // Fast-forward update succeeds!
1241        let ff = GatedRefUpdate {
1242            refname: "refs/heads/main".into(),
1243            old_oid: Some(c1),
1244            new_oid: Some(c2),
1245            allow_non_ff: false,
1246            pusher: Pusher::local(),
1247            allow_internal_arks_ref: false,
1248            trigger_ci: false,
1249        };
1250        apply_gated_ref_update(&mut repo, &ff).unwrap();
1251        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
1252    }
1253
1254    #[test]
1255    fn non_bare_deny_current_branch_refuses_by_default_and_handles_update_instead() {
1256        let tmp = TempDir::new().unwrap();
1257        let (mut repo, c1) = init_non_bare(tmp.path());
1258        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");
1259
1260        // Default receive.denyCurrentBranch=refuse rejects checked-out main.
1261        let upd = GatedRefUpdate {
1262            refname: "refs/heads/main".into(),
1263            old_oid: Some(c1),
1264            new_oid: Some(c2),
1265            allow_non_ff: false,
1266            pusher: Pusher::local(),
1267            allow_internal_arks_ref: false,
1268            trigger_ci: false,
1269        };
1270        assert!(matches!(
1271            apply_gated_ref_update(&mut repo, &upd),
1272            Err(GateReject::Conflict(_))
1273        ));
1274        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c1);
1275
1276        // Configure updateInstead: dirty worktree must still be refused!
1277        fs::write(
1278            repo.git_dir().join("config"),
1279            b"[core]\n\tbare = false\n[receive]\n\tdenyCurrentBranch = updateInstead\n",
1280        )
1281        .unwrap();
1282        fs::write(tmp.path().join("a.txt"), b"dirty local edit\n").unwrap();
1283        assert!(matches!(
1284            apply_gated_ref_update(&mut repo, &upd),
1285            Err(GateReject::Conflict(_))
1286        ));
1287
1288        // Clean worktree succeeds and updates worktree file to v2!
1289        fs::write(tmp.path().join("a.txt"), b"v1\n").unwrap();
1290        apply_gated_ref_update(&mut repo, &upd).unwrap();
1291        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
1292        assert_eq!(
1293            fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
1294            "v2\n"
1295        );
1296    }
1297
1298    #[test]
1299    fn ref_gate_reclaims_stale_lockfile() {
1300        let tmp = TempDir::new().unwrap();
1301        let lock_path = tmp.path().join(REF_GATE_LOCK_FILE);
1302        fs::write(&lock_path, b"pid=999999\n").unwrap();
1303        std::thread::sleep(Duration::from_millis(15));
1304        let guard =
1305            acquire_file_lock_with(&lock_path, Duration::from_millis(5), Duration::from_secs(2))
1306                .expect("stale ref gate lockfile must be reclaimed");
1307        assert!(lock_path.is_file());
1308        drop(guard);
1309        assert!(!lock_path.exists());
1310    }
1311
1312    #[test]
1313    fn ref_gate_drops_lock_before_webhook_dispatch() {
1314        use crate::web_ui::allow_loopback_webhooks_for_repo;
1315        use crate::web_ui::store::WebhookRecord;
1316        use std::io::{Read as _, Write as _};
1317        use std::net::TcpListener;
1318
1319        let tmp = TempDir::new().unwrap();
1320        let (mut repo, c1) = init_bare_classic(tmp.path());
1321        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");
1322
1323        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1324        let addr = listener.local_addr().unwrap();
1325        let common_dir_bg = repo.common_dir().to_path_buf();
1326        let lock_path_bg = common_dir_bg.join(REF_GATE_LOCK_FILE);
1327
1328        let srv = std::thread::spawn(move || {
1329            let (mut stream, _) = listener.accept().unwrap();
1330            let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
1331            let mut req = Vec::new();
1332            let mut buf = [0u8; 2048];
1333            let mut header_end = None;
1334            let mut content_len = 0usize;
1335            loop {
1336                match stream.read(&mut buf) {
1337                    Ok(0) | Err(_) => break,
1338                    Ok(n) => {
1339                        req.extend_from_slice(&buf[..n]);
1340                        if header_end.is_none() {
1341                            if let Some(pos) = req.windows(4).position(|w| w == b"\r\n\r\n") {
1342                                header_end = Some(pos + 4);
1343                                let hdrs = String::from_utf8_lossy(&req[..pos]);
1344                                for line in hdrs.lines() {
1345                                    if let Some((k, v)) = line.split_once(':') {
1346                                        if k.trim().eq_ignore_ascii_case("content-length") {
1347                                            content_len = v.trim().parse().unwrap_or(0);
1348                                        }
1349                                    }
1350                                }
1351                            }
1352                        }
1353                        if let Some(end) = header_end {
1354                            if req.len() >= end + content_len {
1355                                break;
1356                            }
1357                        }
1358                    }
1359                }
1360            }
1361            let lock_file_absent = !lock_path_bg.exists();
1362            // Acquiring the repository ref gate lock inside the synchronous webhook receiver
1363            // would deadlock if RefGateGuard were still held during webhook dispatch.
1364            let acquired_while_in_webhook = acquire_repo_ref_lock(&common_dir_bg).is_ok();
1365            let _ = stream
1366                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
1367            let _ = stream.flush();
1368            let _ = stream.shutdown(std::net::Shutdown::Write);
1369            (lock_file_absent, acquired_while_in_webhook)
1370        });
1371
1372        let _loopback_guard = allow_loopback_webhooks_for_repo(repo.common_dir());
1373        ForgeStore::update(repo.common_dir(), |s| {
1374            s.next_webhook_id = 2;
1375            s.webhooks.push(WebhookRecord {
1376                id: 1,
1377                url: format!("http://{addr}/hook"),
1378                secret: "sec".into(),
1379                events: vec!["push".into()],
1380                active: true,
1381                created_at: 1,
1382            });
1383        })
1384        .unwrap();
1385
1386        let upd = GatedRefUpdate {
1387            refname: "refs/heads/main".into(),
1388            old_oid: Some(c1),
1389            new_oid: Some(c2),
1390            allow_non_ff: false,
1391            pusher: Pusher::local(),
1392            allow_internal_arks_ref: false,
1393            trigger_ci: false,
1394        };
1395        apply_gated_ref_update(&mut repo, &upd).unwrap();
1396
1397        let (lock_file_absent, acquired_while_in_webhook) = srv.join().unwrap();
1398        assert!(
1399            lock_file_absent,
1400            "arks-ref-gate.lock must be removed before synchronous webhook dispatch"
1401        );
1402        assert!(
1403            acquired_while_in_webhook,
1404            "RefGateGuard must be dropped before synchronous webhook dispatch"
1405        );
1406        let st = ForgeStore::load_shared(repo.common_dir());
1407        assert_eq!(st.webhook_deliveries.len(), 1);
1408        assert_eq!(st.webhook_deliveries[0].status, 200);
1409    }
1410
1411    #[test]
1412    fn update_instead_accepts_crlf_checkout_when_core_autocrlf_enabled() {
1413        let tmp = TempDir::new().unwrap();
1414        let wt = tmp.path();
1415        let git_dir = wt.join(".git");
1416        fs::create_dir_all(git_dir.join("objects")).unwrap();
1417        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
1418        fs::write(git_dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
1419        fs::write(
1420            git_dir.join("config"),
1421            b"[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tautocrlf = true\n[receive]\n\tdenyCurrentBranch = updateInstead\n",
1422        )
1423        .unwrap();
1424        let mut repo = Repository::open(&git_dir).unwrap();
1425        let (c1, _) = make_commit(&mut repo, vec![], &[("f.txt", b"line1\nline2\n")], "c1\n");
1426        let (c2, _) = make_commit(&mut repo, vec![c1], &[("f.txt", b"line1\nline3\n")], "c2\n");
1427        repo.refs_mut()
1428            .update("refs/heads/main", &c1, None)
1429            .unwrap();
1430
1431        // Simulate Windows Git checkout with CRLF on disk matching LF blob in HEAD.
1432        fs::write(wt.join("f.txt"), b"line1\r\nline2\r\n").unwrap();
1433        assert!(
1434            check_non_bare_deny_current_branch(&repo, "refs/heads/main", Some(&c2)).unwrap(),
1435            "CRLF checkout of LF blob must be considered clean when core.autocrlf=true"
1436        );
1437
1438        // Actual content modification must still fail closed with 409 Conflict.
1439        fs::write(wt.join("f.txt"), b"line1\r\ndirty\r\n").unwrap();
1440        assert!(
1441            matches!(
1442                check_non_bare_deny_current_branch(&repo, "refs/heads/main", Some(&c2)),
1443                Err(GateReject::Conflict(_))
1444            ),
1445            "actual uncommitted edit must still be rejected"
1446        );
1447    }
1448}