Skip to main content

arks_server/
receive.rs

1//! receive-pack service (push path).
2//!
3//! Claimed caps: `report-status`, `report-status-v2` (classic ok/ng + FS2
4//! proc-receive option rewrite when diverted), `delete-refs`,
5//! `push-options` (O4; forward to hooks), `proc-receive` (FS2 when hook
6//! present), `agent`.
7//! Cite: <https://git-scm.com/docs/gitprotocol-capabilities>,
8//! <https://git-scm.com/docs/git-receive-pack> (quarantine environment).
9
10use crate::advertise::{encode_http_advertisement, encode_pack_advertisement};
11use crate::error::ServerError;
12use crate::hooks::{
13    HookEnv, HookGate, ProcReceiveCmd, proc_receive_hook_present, proc_receive_ref_prefixes,
14    ref_matches_proc_receive, run_post_receive, run_post_update, run_pre_receive, run_proc_receive,
15    run_update,
16};
17use crate::push_policy::{PushPolicy, Pusher, RefUpdate, installed_push_policy, verdicts};
18use arks_oid::Oid;
19use arks_pack::DecodedPack;
20use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet};
21use arks_refs::RefTarget;
22use arks_repo::Repository;
23use arks_store::{FilesystemGitStore, ObjectStore};
24use std::fs;
25use std::path::{Path, PathBuf};
26use std::time::{SystemTime, UNIX_EPOCH};
27
28type RefsAndCaps = (Vec<(String, Oid)>, Vec<String>);
29
30fn receive_refs_and_caps(repo: &Repository) -> Result<RefsAndCaps, ServerError> {
31    let mut refs = repo
32        .refs()
33        .list_refs("refs/")
34        .map_err(|e| ServerError::Msg(e.to_string()))?;
35    refs.retain(|(name, _)| !crate::advertise::is_internal_arks_ref(name));
36    refs.sort_by(|a, b| a.0.cmp(&b.0));
37    if let Ok(oid) = repo.refs().resolve("HEAD") {
38        let head_points_internal = matches!(
39            repo.head_target(),
40            Ok(RefTarget::Symbolic(ref sym)) if crate::advertise::is_internal_arks_ref(sym)
41        );
42        if !head_points_internal && !refs.iter().any(|(n, _)| n == "HEAD") {
43            refs.insert(0, ("HEAD".into(), oid));
44        }
45    } else if let Ok(RefTarget::Direct(oid)) = repo.head_target() {
46        refs.insert(0, ("HEAD".into(), oid));
47    }
48    // Advertise only real caps. FS2: advertise `proc-receive` when hook present.
49    // Cite: https://git-scm.com/docs/gitprotocol-capabilities
50    let mut caps = vec![
51        "report-status".into(),
52        "report-status-v2".into(),
53        "delete-refs".into(),
54        "push-options".into(),
55        "agent=arks/0.0.0".into(),
56    ];
57    if proc_receive_hook_present(repo.git_dir()) {
58        caps.insert(caps.len() - 1, "proc-receive".into());
59    }
60    Ok((refs, caps))
61}
62
63/// Smart-HTTP receive-pack advertisement.
64pub fn receive_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
65    let (refs, caps) = receive_refs_and_caps(repo)?;
66    encode_http_advertisement("git-receive-pack", &caps, &refs)
67}
68
69/// Pack-protocol duplex receive-pack advertisement (SSH / stdio).
70pub fn receive_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
71    let (refs, caps) = receive_refs_and_caps(repo)?;
72    encode_pack_advertisement(&caps, &refs)
73}
74
75/// receive-pack with the installed push policy and a local pusher.
76pub fn receive_pack(repo: &mut Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
77    receive_pack_as(repo, body, &Pusher::local())
78}
79
80/// receive-pack with the installed push policy ([`crate::install_push_policy`]).
81pub fn receive_pack_as(
82    repo: &mut Repository,
83    body: &[u8],
84    pusher: &Pusher,
85) -> Result<Vec<u8>, ServerError> {
86    let policy = installed_push_policy();
87    receive_pack_with(repo, body, pusher, policy.as_deref())
88}
89
90/// receive-pack gated by an explicit push policy: each refused ref is reported
91/// `ng <ref> <reason>` and left unchanged; other refs proceed.
92pub fn receive_pack_with(
93    repo: &mut Repository,
94    body: &[u8],
95    pusher: &Pusher,
96    policy: Option<&dyn PushPolicy>,
97) -> Result<Vec<u8>, ServerError> {
98    let (commands, push_options, pack) = split_commands(body)?;
99
100    // Fail closed on corrupted or archived ForgeStore before touching objects/refs.
101    let store_check = crate::web_ui::store::ForgeStore::load_shared(repo.common_dir());
102    if store_check.corrupt {
103        let declined: Vec<(String, Result<(), String>)> = commands
104            .iter()
105            .map(|cmd| {
106                (
107                    cmd.name.clone(),
108                    Err("forge store is corrupted; refusing push (fail-closed)".into()),
109                )
110            })
111            .collect();
112        return encode_report_status_owned("ok", &declined);
113    }
114    if store_check.archived {
115        let declined: Vec<(String, Result<(), String>)> = commands
116            .iter()
117            .map(|cmd| {
118                (
119                    cmd.name.clone(),
120                    Err("repository is archived (read-only)".into()),
121                )
122            })
123            .collect();
124        return encode_report_status_owned("ok", &declined);
125    }
126
127    let quarantine = Quarantine::create(repo.git_dir())?;
128    let hook_env = HookEnv {
129        quarantine_path: Some(quarantine.path.clone()),
130        push_options,
131    };
132
133    if !pack.is_empty() {
134        if !pack.starts_with(b"PACK") {
135            quarantine.discard();
136            return encode_report_status("unpack unpacker error", &[]);
137        }
138        let decoded =
139            match DecodedPack::decode_with_external_base(&pack, repo.object_format(), |base_oid| {
140                repo.get_object(base_oid).ok()
141            }) {
142                Ok(d) => d,
143                Err(e) => {
144                    quarantine.discard();
145                    return encode_report_status(&format!("unpack {e}"), &[]);
146                }
147            };
148        let mut qstore = FilesystemGitStore::new(&quarantine.path)
149            .map_err(|e| ServerError::Msg(e.to_string()))?;
150        for object in decoded.objects {
151            qstore
152                .put(repo.object_format(), &object.object)
153                .map_err(|e| ServerError::Msg(e.to_string()))?;
154        }
155    }
156
157    // Serialize ref verification and mutation across stock `git push`, `arks push --onto`,
158    // Headless API, and Web UI via the shared `RefUpdateGate` repository lock.
159    let gate_lock =
160        crate::ref_gate::acquire_repo_ref_lock(repo.common_dir()).map_err(ServerError::Msg)?;
161
162    // Reload ForgeStore under the ref gate lock so concurrent archive/corrupt transitions
163    // or branch protection updates cannot race past the pre-lock check.
164    let store_check = crate::web_ui::store::ForgeStore::load_shared(repo.common_dir());
165    if store_check.corrupt {
166        quarantine.discard();
167        let declined: Vec<(String, Result<(), String>)> = commands
168            .iter()
169            .map(|cmd| {
170                (
171                    cmd.name.clone(),
172                    Err("forge store is corrupted; refusing push (fail-closed)".into()),
173                )
174            })
175            .collect();
176        return encode_report_status_owned("ok", &declined);
177    }
178    if store_check.archived {
179        quarantine.discard();
180        let declined: Vec<(String, Result<(), String>)> = commands
181            .iter()
182            .map(|cmd| {
183                (
184                    cmd.name.clone(),
185                    Err("repository is archived (read-only)".into()),
186                )
187            })
188            .collect();
189        return encode_report_status_owned("ok", &declined);
190    }
191
192    // Honor list: pre-receive once after unpack, before any ref update.
193    // Cite: https://git-scm.com/docs/githooks , https://git-scm.com/docs/git-receive-pack
194    let pre_stdin = hook_stdin_lines(&commands);
195    if run_pre_receive(repo.git_dir(), &pre_stdin, &hook_env)? == HookGate::Decline {
196        quarantine.discard();
197        let declined: Vec<(String, Result<(), String>)> = commands
198            .iter()
199            .map(|cmd| (cmd.name.clone(), Err("pre-receive hook declined".into())))
200            .collect();
201        return encode_report_status_owned("ok", &declined);
202    }
203
204    // Migrate quarantined objects into the main store only after pre-receive.
205    quarantine.migrate_into(repo).map_err(ServerError::Msg)?;
206
207    let prefixes = proc_receive_ref_prefixes(repo.git_dir());
208    let use_proc = proc_receive_hook_present(repo.git_dir()) && !prefixes.is_empty();
209
210    // Push policy (forge rulesets): decided per ref after unpack, before any ref moves.
211    let updates: Vec<RefUpdate> = commands
212        .iter()
213        .map(|c| RefUpdate {
214            name: c.name.clone(),
215            old: c.old,
216            new: c.new,
217        })
218        .collect();
219    let refused = verdicts(policy, repo, pusher, &updates);
220
221    let mut results: Vec<(String, Result<(), String>)> = Vec::new();
222    let mut success_cmds: Vec<ReceiveCommand> = Vec::new();
223    let mut applied_side_effects: Vec<(String, Option<Oid>, Option<Oid>)> = Vec::new();
224    let mut diverted: Vec<ReceiveCommand> = Vec::new();
225    let mut ordinary: Vec<&ReceiveCommand> = Vec::new();
226    for (cmd, refusal) in commands.iter().zip(refused) {
227        if crate::advertise::is_internal_arks_ref(&cmd.name) {
228            results.push((
229                cmd.name.clone(),
230                Err(format!(
231                    "ref '{}' is reserved for internal arks metadata",
232                    cmd.name
233                )),
234            ));
235            continue;
236        }
237        if let Some(reason) = refusal {
238            results.push((cmd.name.clone(), Err(reason)));
239            continue;
240        }
241        if use_proc && ref_matches_proc_receive(&cmd.name, &prefixes) {
242            diverted.push(cmd.clone());
243        } else {
244            ordinary.push(cmd);
245        }
246    }
247
248    for cmd in ordinary {
249        let old = repo.refs().resolve(&cmd.name).ok();
250        // Expect old matches when peer sent non-zero old (fast-forward check deferred:
251        // accept if old is None or matches cmd.old, else refuse).
252        if !cmd.old.as_bytes().iter().all(|b| *b == 0) {
253            match old {
254                Some(oid) if oid != cmd.old => {
255                    results.push((cmd.name.clone(), Err("non-fast-forward".into())));
256                    continue;
257                }
258                None => {
259                    results.push((cmd.name.clone(), Err("old oid mismatch".into())));
260                    continue;
261                }
262                _ => {}
263            }
264        }
265        let target_new = if is_delete(cmd) { None } else { Some(cmd.new) };
266        let should_update_worktree = match crate::ref_gate::check_non_bare_deny_current_branch(
267            repo,
268            &cmd.name,
269            target_new.as_ref(),
270        ) {
271            Ok(v) => v,
272            Err(rej) => {
273                results.push((cmd.name.clone(), Err(rej.message().to_string())));
274                continue;
275            }
276        };
277        let old_hex = cmd.old.to_hex();
278        let new_hex = cmd.new.to_hex();
279        if run_update(repo.git_dir(), &cmd.name, &old_hex, &new_hex, &hook_env)?
280            == HookGate::Decline
281        {
282            results.push((cmd.name.clone(), Err("hook declined".into())));
283            continue;
284        }
285        if let Err(reason) =
286            check_branch_protection_rules(repo, &store_check, &cmd.name, old, target_new)
287        {
288            results.push((cmd.name.clone(), Err(reason)));
289            continue;
290        }
291        if is_delete(cmd) {
292            match repo.refs_mut().delete(&cmd.name, old.as_ref()) {
293                Ok(()) => {
294                    results.push((cmd.name.clone(), Ok(())));
295                    success_cmds.push(cmd.clone());
296                    applied_side_effects.push((cmd.name.clone(), old, None));
297                }
298                Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
299            }
300            continue;
301        }
302        match repo.refs_mut().update(&cmd.name, &cmd.new, old.as_ref()) {
303            Ok(()) => {
304                if should_update_worktree {
305                    if let Err(rej) = crate::ref_gate::sync_worktree_for_update_instead(
306                        repo,
307                        old.as_ref(),
308                        &cmd.new,
309                    ) {
310                        if let Some(prev) = old.as_ref() {
311                            let _ = repo.refs_mut().update(&cmd.name, prev, Some(&cmd.new));
312                        } else {
313                            let _ = repo.refs_mut().delete(&cmd.name, Some(&cmd.new));
314                        }
315                        results.push((cmd.name.clone(), Err(rej.message().to_string())));
316                        continue;
317                    }
318                }
319                results.push((cmd.name.clone(), Ok(())));
320                success_cmds.push(cmd.clone());
321                applied_side_effects.push((cmd.name.clone(), old, Some(cmd.new)));
322            }
323            Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
324        }
325    }
326
327    if !diverted.is_empty() {
328        // FS8 / HOOK-008 closest: refuse concurrent proc-receive under lock.
329        let pr_lock = repo.git_dir().join("hooks").join("proc-receive.lock");
330        if pr_lock.is_file() {
331            return Err(ServerError::Msg(format!(
332                "{} (HOOK-008 — concurrent proc-receive refuse; serialize push-options/proc-receive; lease ≠ skip)",
333                pr_lock.display()
334            )));
335        }
336        let _ = fs::write(&pr_lock, b"arks-proc-receive\n");
337        let pr_cmds: Vec<ProcReceiveCmd> = diverted
338            .iter()
339            .map(|c| ProcReceiveCmd {
340                old_hex: c.old.to_hex(),
341                new_hex: c.new.to_hex(),
342                name: c.name.clone(),
343            })
344            .collect();
345        let pr_results = match run_proc_receive(repo.git_dir(), &pr_cmds, &hook_env) {
346            Ok(r) => {
347                let _ = fs::remove_file(&pr_lock);
348                r
349            }
350            Err(e) => {
351                let _ = fs::remove_file(&pr_lock);
352                return Err(e);
353            }
354        };
355        for pr in pr_results {
356            if !pr.ok {
357                results.push((
358                    pr.name,
359                    Err(pr.error.unwrap_or_else(|| "proc-receive declined".into())),
360                ));
361                continue;
362            }
363            // Apply rewrite if hook provided option refname / new-oid; else
364            // treat ok as "hook handled ref" without receive-pack updating the
365            // original name (stock git behavior for successful proc-receive).
366            let target_name = pr.rewrite_ref.clone().unwrap_or_else(|| pr.name.clone());
367            if !arks_refs::is_valid_refname(&target_name) {
368                results.push((pr.name, Err(format!("invalid ref name '{target_name}'"))));
369                continue;
370            }
371            if crate::advertise::is_internal_arks_ref(&target_name) {
372                results.push((
373                    pr.name,
374                    Err(format!(
375                        "ref '{target_name}' is reserved for internal arks metadata"
376                    )),
377                ));
378                continue;
379            }
380            let new_oid = if let Some(hex) = &pr.rewrite_new {
381                Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?
382            } else {
383                diverted
384                    .iter()
385                    .find(|c| c.name == pr.name)
386                    .map(|c| c.new)
387                    .ok_or_else(|| ServerError::Msg("proc-receive missing cmd".into()))?
388            };
389            let live_old = repo.refs().resolve(&target_name).ok();
390            let old_hint = if let Some(hex) = &pr.rewrite_old {
391                Some(Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?)
392            } else {
393                live_old
394            };
395            let is_del = new_oid.as_bytes().iter().all(|b| *b == 0);
396            let target_new = if is_del { None } else { Some(new_oid) };
397            if pr.rewrite_ref.is_some() && policy.is_some() {
398                let target_upd = RefUpdate {
399                    name: target_name.clone(),
400                    old: live_old.unwrap_or_else(zero_oid),
401                    new: new_oid,
402                };
403                if let Some(Some(reason)) = verdicts(policy, repo, pusher, &[target_upd])
404                    .into_iter()
405                    .next()
406                {
407                    results.push((pr.name, Err(reason)));
408                    continue;
409                }
410            }
411            if let Err(reason) = check_branch_protection_rules(
412                repo,
413                &store_check,
414                &target_name,
415                live_old,
416                target_new,
417            ) {
418                results.push((pr.name, Err(reason)));
419                continue;
420            }
421            let should_update_worktree = match crate::ref_gate::check_non_bare_deny_current_branch(
422                repo,
423                &target_name,
424                target_new.as_ref(),
425            ) {
426                Ok(v) => v,
427                Err(rej) => {
428                    results.push((pr.name, Err(rej.message().to_string())));
429                    continue;
430                }
431            };
432            if is_del {
433                match repo.refs_mut().delete(&target_name, old_hint.as_ref()) {
434                    Ok(()) => {
435                        results.push((pr.name, Ok(())));
436                        applied_side_effects.push((target_name.clone(), old_hint, None));
437                        success_cmds.push(ReceiveCommand {
438                            old: old_hint.unwrap_or_else(zero_oid),
439                            new: new_oid,
440                            name: target_name,
441                        });
442                    }
443                    Err(e) => results.push((pr.name, Err(e.to_string()))),
444                }
445            } else {
446                match repo
447                    .refs_mut()
448                    .update(&target_name, &new_oid, old_hint.as_ref())
449                {
450                    Ok(()) => {
451                        if should_update_worktree {
452                            if let Err(rej) = crate::ref_gate::sync_worktree_for_update_instead(
453                                repo,
454                                live_old.as_ref(),
455                                &new_oid,
456                            ) {
457                                if let Some(prev) = live_old.as_ref() {
458                                    let _ =
459                                        repo.refs_mut().update(&target_name, prev, Some(&new_oid));
460                                } else {
461                                    let _ = repo.refs_mut().delete(&target_name, Some(&new_oid));
462                                }
463                                results.push((pr.name, Err(rej.message().to_string())));
464                                continue;
465                            }
466                        }
467                        results.push((pr.name, Ok(())));
468                        applied_side_effects.push((target_name.clone(), old_hint, Some(new_oid)));
469                        success_cmds.push(ReceiveCommand {
470                            old: old_hint.unwrap_or_else(zero_oid),
471                            new: new_oid,
472                            name: target_name,
473                        });
474                    }
475                    Err(e) => results.push((pr.name, Err(e.to_string()))),
476                }
477            }
478        }
479    }
480
481    if !success_cmds.is_empty() {
482        let post_stdin = hook_stdin_lines_refs(success_cmds.iter());
483        run_post_receive(repo.git_dir(), &post_stdin, &hook_env);
484        let names: Vec<&str> = success_cmds.iter().map(|c| c.name.as_str()).collect();
485        run_post_update(repo.git_dir(), &names, &hook_env);
486        crate::ref_gate::post_receive_locked_effects(repo, &applied_side_effects, true);
487    }
488
489    drop(gate_lock);
490
491    if !success_cmds.is_empty() {
492        crate::ref_gate::post_receive_external_effects(repo, &applied_side_effects, true);
493    }
494
495    encode_report_status_owned("ok", &results)
496}
497
498fn check_branch_protection_rules(
499    repo: &Repository,
500    _store: &crate::web_ui::store::ForgeStore,
501    refname: &str,
502    old: Option<Oid>,
503    new_oid: Option<Oid>,
504) -> Result<(), String> {
505    let Some(branch) = refname.strip_prefix("refs/heads/") else {
506        return Ok(());
507    };
508    match new_oid {
509        None => {
510            if crate::web_ui::is_branch_delete_protected(repo, branch) {
511                return Err("branch deletion blocked by branch protection rule".into());
512            }
513        }
514        Some(new_target) => {
515            if let Some(old_oid) = old {
516                if old_oid != new_target
517                    && crate::web_ui::is_force_push_blocked(repo.common_dir(), branch)
518                    && !is_commit_ancestor(repo, old_oid, new_target)
519                {
520                    return Err("force push blocked by branch protection rule".into());
521                }
522            }
523        }
524    }
525    Ok(())
526}
527
528/// Quarantine object dir under `$GIT_DIR/objects` (git-receive-pack).
529struct Quarantine {
530    path: PathBuf,
531}
532
533impl Quarantine {
534    fn create(git_dir: &Path) -> Result<Self, ServerError> {
535        let objects = git_dir.join("objects");
536        fs::create_dir_all(&objects)?;
537        let nanos = SystemTime::now()
538            .duration_since(UNIX_EPOCH)
539            .map(|d| d.as_nanos())
540            .unwrap_or(0);
541        let path = objects.join(format!("incoming-{nanos}-{}", std::process::id()));
542        fs::create_dir_all(&path)?;
543        Ok(Self { path })
544    }
545
546    fn discard(self) {
547        let _ = fs::remove_dir_all(&self.path);
548    }
549
550    fn migrate_into(self, repo: &mut Repository) -> Result<(), String> {
551        // Walk quarantine loose objects and put into the main store.
552        let Ok(entries) = fs::read_dir(&self.path) else {
553            let _ = fs::remove_dir_all(&self.path);
554            return Ok(());
555        };
556        for entry in entries.flatten() {
557            let name = entry.file_name();
558            let name = name.to_string_lossy();
559            if name.len() != 2 {
560                continue;
561            }
562            let fanout = entry.path();
563            let Ok(objs) = fs::read_dir(&fanout) else {
564                continue;
565            };
566            for obj in objs.flatten() {
567                let fname = obj.file_name();
568                let rest = fname.to_string_lossy();
569                let hex = format!("{name}{rest}");
570                let Ok(oid) = Oid::from_hex(&hex) else {
571                    continue;
572                };
573                // Read via a store rooted at quarantine so packed/overlay stays honest.
574                let qstore = FilesystemGitStore::open(&self.path);
575                match qstore.get(&oid) {
576                    Ok(raw) => {
577                        let format = repo.object_format();
578                        repo.store_mut()
579                            .put(format, &raw)
580                            .map_err(|e| e.to_string())?;
581                    }
582                    Err(_) => continue,
583                }
584            }
585        }
586        let _ = fs::remove_dir_all(&self.path);
587        Ok(())
588    }
589}
590
591fn is_delete(cmd: &ReceiveCommand) -> bool {
592    cmd.new.as_bytes().iter().all(|b| *b == 0)
593}
594
595fn zero_oid() -> Oid {
596    Oid::from_hex("0000000000000000000000000000000000000000").expect("zero oid")
597}
598
599fn hook_stdin_lines(commands: &[ReceiveCommand]) -> Vec<u8> {
600    hook_stdin_lines_refs(commands.iter())
601}
602
603fn hook_stdin_lines_refs<'a, I>(commands: I) -> Vec<u8>
604where
605    I: IntoIterator<Item = &'a ReceiveCommand>,
606{
607    let mut out = Vec::new();
608    for cmd in commands {
609        out.extend(format!("{} {} {}\n", cmd.old.to_hex(), cmd.new.to_hex(), cmd.name).as_bytes());
610    }
611    out
612}
613
614#[derive(Debug, Clone)]
615struct ReceiveCommand {
616    old: Oid,
617    new: Oid,
618    name: String,
619}
620
621type SplitCommands = (Vec<ReceiveCommand>, Vec<String>, Vec<u8>);
622
623fn split_commands(body: &[u8]) -> Result<SplitCommands, ServerError> {
624    let mut offset = 0;
625    let mut commands = Vec::new();
626    let mut saw_push_options_cap = false;
627    while offset < body.len() {
628        let (packet, n) =
629            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
630        offset += n;
631        match packet {
632            Packet::Flush => break,
633            Packet::Data(payload) => {
634                let owned = if let Some(nul) = payload.iter().position(|b| *b == 0) {
635                    let text = std::str::from_utf8(&payload[..nul])
636                        .map_err(|_| ServerError::Protocol("command not utf-8".into()))?
637                        .to_string();
638                    let caps = std::str::from_utf8(&payload[nul + 1..]).unwrap_or("");
639                    if caps.split_whitespace().any(|c| c == "push-options") {
640                        saw_push_options_cap = true;
641                    }
642                    text
643                } else {
644                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?
645                };
646                let text = owned.trim_end_matches('\n');
647                let mut parts = text.splitn(3, ' ');
648                let old_hex = parts
649                    .next()
650                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
651                let new_hex = parts
652                    .next()
653                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
654                let name = parts
655                    .next()
656                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
657                // Capability list may trail the first command after a NUL already handled;
658                // also accept space-separated caps after the refname on some peers.
659                if name.contains("push-options") || text.contains(" push-options") {
660                    saw_push_options_cap = true;
661                }
662                let refname = name.split('\0').next().unwrap_or(name).to_string();
663                commands.push(ReceiveCommand {
664                    old: Oid::from_hex(old_hex)
665                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
666                    new: Oid::from_hex(new_hex)
667                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
668                    name: refname,
669                });
670            }
671            _ => {}
672        }
673    }
674    let mut push_options = Vec::new();
675    if saw_push_options_cap {
676        while offset < body.len() {
677            if body[offset..].starts_with(b"PACK") {
678                break;
679            }
680            let (packet, n) =
681                decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
682            offset += n;
683            match packet {
684                Packet::Flush => break,
685                Packet::Data(payload) => {
686                    let line = decode_text_line(&payload)
687                        .map_err(|e| ServerError::Protocol(e.to_string()))?;
688                    let line = line.trim_end_matches('\n');
689                    if let Some(rest) = line.strip_prefix("push-option ") {
690                        push_options.push(rest.to_string());
691                    } else if line == "push-option" {
692                        push_options.push(String::new());
693                    } else {
694                        return Err(ServerError::Protocol(format!(
695                            "expected push-option line, got {line}"
696                        )));
697                    }
698                }
699                _ => {}
700            }
701        }
702    }
703    Ok((commands, push_options, body[offset..].to_vec()))
704}
705
706fn encode_report_status_owned(
707    unpack: &str,
708    refs: &[(String, Result<(), String>)],
709) -> Result<Vec<u8>, ServerError> {
710    let borrowed: Vec<(&str, Result<(), &str>)> = refs
711        .iter()
712        .map(|(n, r)| {
713            (
714                n.as_str(),
715                match r {
716                    Ok(()) => Ok(()),
717                    Err(e) => Err(e.as_str()),
718                },
719            )
720        })
721        .collect();
722    encode_report_status(unpack, &borrowed)
723}
724
725fn encode_report_status(
726    unpack: &str,
727    refs: &[(&str, Result<(), &str>)],
728) -> Result<Vec<u8>, ServerError> {
729    // Classic unpack/ok/ng lines are valid report-status and report-status-v2
730    // when no proc-receive rewrite options are needed.
731    let mut out = Vec::new();
732    out.extend(text_pkt(&format!("unpack {unpack}"))?);
733    for (name, result) in refs {
734        match result {
735            Ok(()) => out.extend(text_pkt(&format!("ok {name}"))?),
736            Err(err) => out.extend(text_pkt(&format!("ng {name} {err}"))?),
737        }
738    }
739    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
740    Ok(out)
741}
742
743fn text_pkt(text: &str) -> Result<Vec<u8>, ServerError> {
744    let mut payload = text.as_bytes().to_vec();
745    if !payload.ends_with(b"\n") {
746        payload.push(b'\n');
747    }
748    encode_packet(&Packet::Data(payload)).map_err(|e| ServerError::Protocol(e.to_string()))
749}
750
751fn is_commit_ancestor(repo: &Repository, ancestor: Oid, descendant: Oid) -> bool {
752    if ancestor == descendant {
753        return true;
754    }
755    let mut queue = std::collections::VecDeque::new();
756    let mut visited = std::collections::HashSet::new();
757    queue.push_back(descendant);
758    visited.insert(descendant);
759    let mut steps = 0usize;
760    while let Some(cur) = queue.pop_front() {
761        steps += 1;
762        if steps > 4096 {
763            break;
764        }
765        let Ok(obj) = repo.get_object(&cur) else {
766            continue;
767        };
768        if obj.kind != arks_object::ObjectKind::Commit {
769            continue;
770        }
771        let Ok(commit) = arks_object::Commit::decode(&obj.payload) else {
772            continue;
773        };
774        for parent in commit.parents {
775            if parent == ancestor {
776                return true;
777            }
778            if visited.insert(parent) {
779                queue.push_back(parent);
780            }
781        }
782    }
783    false
784}
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789    use crate::web_ui::allow_loopback_webhooks_for_repo;
790    use crate::web_ui::store::{ForgeStore, WebhookRecord};
791    use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
792    use tempfile::TempDir;
793
794    fn make_commit(
795        repo: &mut Repository,
796        parents: Vec<Oid>,
797        files: &[(&str, &[u8])],
798        msg: &str,
799    ) -> Oid {
800        let fmt = repo.object_format();
801        let mut entries = Vec::new();
802        for (name, content) in files {
803            let blob_oid = repo
804                .store_mut()
805                .put(fmt, &RawObject::new(ObjectKind::Blob, content.to_vec()))
806                .unwrap();
807            entries.push(TreeEntry {
808                mode: TreeMode::File,
809                name: (*name).to_string(),
810                oid: blob_oid,
811            });
812        }
813        entries.sort_by(|a, b| a.name.cmp(&b.name));
814        let tree_oid = repo
815            .store_mut()
816            .put(
817                fmt,
818                &RawObject::new(ObjectKind::Tree, Tree { entries }.encode().unwrap()),
819            )
820            .unwrap();
821        let sig = Signature {
822            name: "test".into(),
823            email: "test@example.invalid".into(),
824            timestamp: 1_700_000_000,
825            timezone: "+0000".into(),
826        };
827        let commit = Commit {
828            tree: tree_oid,
829            parents,
830            author: sig.clone(),
831            committer: sig,
832            gpgsig: None,
833            message: msg.into(),
834        };
835        repo.store_mut()
836            .put(
837                fmt,
838                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
839            )
840            .unwrap()
841    }
842
843    fn init_bare(root: &Path) -> (Repository, Oid) {
844        fs::create_dir_all(root.join("objects")).unwrap();
845        fs::create_dir_all(root.join("refs/heads")).unwrap();
846        fs::write(root.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
847        fs::write(root.join("config"), b"[core]\n\tbare = true\n").unwrap();
848        let mut repo = Repository::open(root).unwrap();
849        let c1 = make_commit(&mut repo, Vec::new(), &[("a.txt", b"v1\n")], "init\n");
850        repo.refs_mut()
851            .update("refs/heads/main", &c1, None)
852            .unwrap();
853        (repo, c1)
854    }
855
856    fn init_non_bare(root: &Path, config: &str) -> (Repository, Oid) {
857        let git_dir = root.join(".git");
858        fs::create_dir_all(git_dir.join("objects")).unwrap();
859        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
860        fs::write(git_dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
861        fs::write(git_dir.join("config"), config).unwrap();
862        fs::write(root.join("a.txt"), b"v1\n").unwrap();
863        let mut repo = Repository::open(&git_dir).unwrap();
864        let c1 = make_commit(&mut repo, Vec::new(), &[("a.txt", b"v1\n")], "init\n");
865        repo.refs_mut()
866            .update("refs/heads/main", &c1, None)
867            .unwrap();
868        (repo, c1)
869    }
870
871    fn make_receive_body(old: Oid, new: Oid, refname: &str) -> Vec<u8> {
872        let mut body = Vec::new();
873        let line = format!(
874            "{} {} {}\0report-status\n",
875            old.to_hex(),
876            new.to_hex(),
877            refname
878        );
879        body.extend(encode_packet(&Packet::Data(line.into_bytes())).unwrap());
880        body.extend(encode_packet(&Packet::Flush).unwrap());
881        body
882    }
883
884    #[test]
885    fn receive_pack_propagates_update_instead_worktree_sync_error_and_rolls_back() {
886        let tmp = TempDir::new().unwrap();
887        let (mut repo, c1) = init_non_bare(
888            tmp.path(),
889            "[core]\n\tbare = false\n[receive]\n\tdenyCurrentBranch = updateInstead\n",
890        );
891        let c2 = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");
892
893        // Pre-create `.git/index.lock` so `sync_worktree_for_update_instead` fails on index write.
894        fs::write(repo.git_dir().join("index.lock"), b"locked\n").unwrap();
895
896        let body = make_receive_body(c1, c2, "refs/heads/main");
897        let report_bytes = receive_pack(&mut repo, &body).unwrap();
898        let report = String::from_utf8_lossy(&report_bytes);
899        assert!(
900            report.contains("ng refs/heads/main "),
901            "worktree sync failure must report ng instead of swallowing error: {report}"
902        );
903        assert!(
904            !report.contains("ok refs/heads/main"),
905            "failed worktree sync must not report ok: {report}"
906        );
907        assert_eq!(
908            repo.refs().resolve("refs/heads/main").unwrap(),
909            c1,
910            "ref update must roll back when updateInstead worktree/index sync fails"
911        );
912    }
913
914    #[test]
915    fn receive_pack_drops_ref_gate_lock_before_webhook_dispatch() {
916        use std::io::{Read as _, Write as _};
917        use std::net::TcpListener;
918
919        let tmp = TempDir::new().unwrap();
920        let (mut repo, c1) = init_bare(tmp.path());
921        let c2 = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");
922
923        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
924        let addr = listener.local_addr().unwrap();
925        let common_dir_bg = repo.common_dir().to_path_buf();
926        let lock_path_bg = common_dir_bg.join("arks-ref-gate.lock");
927
928        let srv = std::thread::spawn(move || {
929            let (mut stream, _) = listener.accept().unwrap();
930            let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
931            let mut req = Vec::new();
932            let mut buf = [0u8; 2048];
933            let mut header_end = None;
934            let mut content_len = 0usize;
935            loop {
936                match stream.read(&mut buf) {
937                    Ok(0) | Err(_) => break,
938                    Ok(n) => {
939                        req.extend_from_slice(&buf[..n]);
940                        if header_end.is_none() {
941                            if let Some(pos) = req.windows(4).position(|w| w == b"\r\n\r\n") {
942                                header_end = Some(pos + 4);
943                                let hdrs = String::from_utf8_lossy(&req[..pos]);
944                                for line in hdrs.lines() {
945                                    if let Some((k, v)) = line.split_once(':') {
946                                        if k.trim().eq_ignore_ascii_case("content-length") {
947                                            content_len = v.trim().parse().unwrap_or(0);
948                                        }
949                                    }
950                                }
951                            }
952                        }
953                        if let Some(end) = header_end {
954                            if req.len() >= end + content_len {
955                                break;
956                            }
957                        }
958                    }
959                }
960            }
961            let lock_file_absent = !lock_path_bg.exists();
962            let acquired_in_webhook =
963                crate::ref_gate::acquire_repo_ref_lock(&common_dir_bg).is_ok();
964            let _ = stream
965                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
966            let _ = stream.flush();
967            let _ = stream.shutdown(std::net::Shutdown::Write);
968            (lock_file_absent, acquired_in_webhook)
969        });
970
971        let _loopback_guard = allow_loopback_webhooks_for_repo(repo.common_dir());
972        ForgeStore::update(repo.common_dir(), |s| {
973            s.next_webhook_id = 2;
974            s.webhooks.push(WebhookRecord {
975                id: 1,
976                url: format!("http://{addr}/hook"),
977                secret: "sec".into(),
978                events: vec!["push".into()],
979                active: true,
980                created_at: 1,
981            });
982        })
983        .unwrap();
984
985        let body = make_receive_body(c1, c2, "refs/heads/main");
986        let report_bytes = receive_pack(&mut repo, &body).unwrap();
987        let report = String::from_utf8_lossy(&report_bytes);
988        assert!(report.contains("ok refs/heads/main"), "report={report}");
989
990        let (lock_file_absent, acquired_in_webhook) = srv.join().unwrap();
991        assert!(
992            lock_file_absent,
993            "ref gate lockfile must be removed before webhook dispatch"
994        );
995        assert!(
996            acquired_in_webhook,
997            "RefGateGuard must be dropped before webhook dispatch"
998        );
999        let st = ForgeStore::load_shared(repo.common_dir());
1000        assert_eq!(st.webhook_deliveries.len(), 1);
1001        assert_eq!(st.webhook_deliveries[0].status, 200);
1002    }
1003
1004    #[cfg(unix)]
1005    fn write_proc_receive_hook(git_dir: &Path, response_lines: &[&str]) {
1006        use std::os::unix::fs::PermissionsExt;
1007        let hooks_dir = git_dir.join("hooks");
1008        fs::create_dir_all(&hooks_dir).unwrap();
1009        let mut pkt_out = Vec::new();
1010        pkt_out.extend(encode_packet(&Packet::Data(b"version=0\n".to_vec())).unwrap());
1011        pkt_out.extend(encode_packet(&Packet::Flush).unwrap());
1012        for line in response_lines {
1013            let mut payload = line.as_bytes().to_vec();
1014            payload.push(b'\n');
1015            pkt_out.extend(encode_packet(&Packet::Data(payload)).unwrap());
1016        }
1017        pkt_out.extend(encode_packet(&Packet::Flush).unwrap());
1018        let resp_file = hooks_dir.join("proc-receive.out");
1019        fs::write(&resp_file, &pkt_out).unwrap();
1020        let hook = hooks_dir.join("proc-receive");
1021        let script = format!("#!/bin/sh\ncat >/dev/null\ncat '{}'\n", resp_file.display());
1022        fs::write(&hook, script).unwrap();
1023        fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
1024    }
1025
1026    #[cfg(unix)]
1027    #[test]
1028    fn proc_receive_enforces_refname_branch_rules_and_non_bare_checks() {
1029        use crate::web_ui::store::BranchRule;
1030
1031        // 1. Bare repo: invalid target refname + branch protection rules (delete, force-push, attestation).
1032        let tmp_bare = TempDir::new().unwrap();
1033        let (mut bare_repo, c1) = init_bare(tmp_bare.path());
1034        fs::write(
1035            bare_repo.git_dir().join("config"),
1036            b"[core]\n\tbare = true\n[receive]\n\tprocReceiveRefs = refs/for/\n",
1037        )
1038        .unwrap();
1039        let c2 = make_commit(&mut bare_repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");
1040        let c_div = make_commit(&mut bare_repo, Vec::new(), &[("a.txt", b"div\n")], "div\n");
1041
1042        // Invalid rewritten refname (`..`) rejected.
1043        write_proc_receive_hook(
1044            bare_repo.git_dir(),
1045            &[
1046                "ok refs/for/main",
1047                "option refname refs/heads/../escape",
1048                &format!("option new-oid {}", c2.to_hex()),
1049            ],
1050        );
1051        let rep_invalid = String::from_utf8_lossy(
1052            &receive_pack(
1053                &mut bare_repo,
1054                &make_receive_body(zero_oid(), c2, "refs/for/main"),
1055            )
1056            .unwrap(),
1057        )
1058        .into_owned();
1059        assert!(
1060            rep_invalid.contains("ng refs/for/main invalid ref name"),
1061            "invalid proc-receive refname must be rejected: {rep_invalid}"
1062        );
1063
1064        // Configure branch protection on `main`.
1065        ForgeStore::update(bare_repo.common_dir(), |s| {
1066            s.branch_rules.push(BranchRule {
1067                pattern: "main".into(),
1068                require_pr: false,
1069                block_force_push: true,
1070                block_delete: true,
1071                required_reviews: 0,
1072            });
1073        })
1074        .unwrap();
1075
1076        // Protected delete rejected.
1077        write_proc_receive_hook(
1078            bare_repo.git_dir(),
1079            &[
1080                "ok refs/for/main",
1081                "option refname refs/heads/main",
1082                &format!("option new-oid {}", zero_oid().to_hex()),
1083            ],
1084        );
1085        let rep_del = String::from_utf8_lossy(
1086            &receive_pack(
1087                &mut bare_repo,
1088                &make_receive_body(zero_oid(), c2, "refs/for/main"),
1089            )
1090            .unwrap(),
1091        )
1092        .into_owned();
1093        assert!(
1094            rep_del.contains("ng refs/for/main branch deletion blocked"),
1095            "proc-receive delete of protected branch must be blocked: {rep_del}"
1096        );
1097        assert_eq!(bare_repo.refs().resolve("refs/heads/main").unwrap(), c1);
1098
1099        // Protected force-push rejected.
1100        write_proc_receive_hook(
1101            bare_repo.git_dir(),
1102            &[
1103                "ok refs/for/main",
1104                "option refname refs/heads/main",
1105                &format!("option new-oid {}", c_div.to_hex()),
1106            ],
1107        );
1108        let rep_force = String::from_utf8_lossy(
1109            &receive_pack(
1110                &mut bare_repo,
1111                &make_receive_body(zero_oid(), c_div, "refs/for/main"),
1112            )
1113            .unwrap(),
1114        )
1115        .into_owned();
1116        assert!(
1117            rep_force.contains("ng refs/for/main force push blocked"),
1118            "proc-receive force-push to protected branch must be blocked: {rep_force}"
1119        );
1120        assert_eq!(bare_repo.refs().resolve("refs/heads/main").unwrap(), c1);
1121
1122        // 2. Non-bare repo: denyCurrentBranch=refuse + updateInstead sync failure rollback.
1123        let tmp_nb = TempDir::new().unwrap();
1124        let (mut nb_repo, nb_c1) = init_non_bare(
1125            tmp_nb.path(),
1126            "[core]\n\tbare = false\n[receive]\n\tprocReceiveRefs = refs/for/\n\tdenyCurrentBranch = refuse\n",
1127        );
1128        let nb_c2 = make_commit(&mut nb_repo, vec![nb_c1], &[("a.txt", b"v2\n")], "v2\n");
1129        write_proc_receive_hook(
1130            nb_repo.git_dir(),
1131            &[
1132                "ok refs/for/main",
1133                "option refname refs/heads/main",
1134                &format!("option new-oid {}", nb_c2.to_hex()),
1135            ],
1136        );
1137        let rep_nb_refuse = String::from_utf8_lossy(
1138            &receive_pack(
1139                &mut nb_repo,
1140                &make_receive_body(zero_oid(), nb_c2, "refs/for/main"),
1141            )
1142            .unwrap(),
1143        )
1144        .into_owned();
1145        assert!(
1146            rep_nb_refuse.contains("ng refs/for/main refusing to update checked-out branch"),
1147            "proc-receive to checked-out branch must be refused: {rep_nb_refuse}"
1148        );
1149        assert_eq!(nb_repo.refs().resolve("refs/heads/main").unwrap(), nb_c1);
1150
1151        // With updateInstead and a locked index, worktree sync failure must report ng and roll back.
1152        fs::write(
1153            nb_repo.git_dir().join("config"),
1154            b"[core]\n\tbare = false\n[receive]\n\tprocReceiveRefs = refs/for/\n\tdenyCurrentBranch = updateInstead\n",
1155        )
1156        .unwrap();
1157        fs::write(nb_repo.git_dir().join("index.lock"), b"locked\n").unwrap();
1158        let rep_nb_sync = String::from_utf8_lossy(
1159            &receive_pack(
1160                &mut nb_repo,
1161                &make_receive_body(zero_oid(), nb_c2, "refs/for/main"),
1162            )
1163            .unwrap(),
1164        )
1165        .into_owned();
1166        assert!(
1167            rep_nb_sync.contains("ng refs/for/main "),
1168            "proc-receive worktree sync error must be propagated: {rep_nb_sync}"
1169        );
1170        assert_eq!(nb_repo.refs().resolve("refs/heads/main").unwrap(), nb_c1);
1171    }
1172
1173    #[test]
1174    fn receive_pack_unpacks_thin_pack_against_existing_repo_objects() {
1175        use flate2::{Compression, write::ZlibEncoder};
1176        use std::io::Write;
1177
1178        let tmp = TempDir::new().unwrap();
1179        let bare_path = crate::init_bare_repo(tmp.path(), "thin", "").unwrap();
1180        let mut repo = Repository::open(&bare_path).unwrap();
1181        let fmt = repo.object_format();
1182
1183        let base_bytes = b"hello thin pack base content line 1\nline 2\n".to_vec();
1184        let base_blob_oid = repo
1185            .store_mut()
1186            .put(fmt, &RawObject::new(ObjectKind::Blob, base_bytes.clone()))
1187            .unwrap();
1188        let c1_tree = repo
1189            .store_mut()
1190            .put(
1191                fmt,
1192                &RawObject::new(
1193                    ObjectKind::Tree,
1194                    Tree {
1195                        entries: vec![TreeEntry {
1196                            mode: TreeMode::File,
1197                            name: "a.txt".into(),
1198                            oid: base_blob_oid,
1199                        }],
1200                    }
1201                    .encode()
1202                    .unwrap(),
1203                ),
1204            )
1205            .unwrap();
1206        let sig = Signature {
1207            name: "Thin Tester".into(),
1208            email: "test@example.invalid".into(),
1209            timestamp: 1_700_000_000,
1210            timezone: "+0000".into(),
1211        };
1212        let c1 = repo
1213            .store_mut()
1214            .put(
1215                fmt,
1216                &RawObject::new(
1217                    ObjectKind::Commit,
1218                    Commit {
1219                        tree: c1_tree,
1220                        parents: vec![],
1221                        author: sig.clone(),
1222                        committer: sig.clone(),
1223                        gpgsig: None,
1224                        message: "base\n".into(),
1225                    }
1226                    .encode()
1227                    .unwrap(),
1228                ),
1229            )
1230            .unwrap();
1231        repo.refs_mut()
1232            .update("refs/heads/main", &c1, None)
1233            .unwrap();
1234
1235        // Build c2 whose blob is sent ONLY as a thin OBJ_REF_DELTA against `base_blob_oid`!
1236        let new_bytes = b"hello thin pack base content line 1\nline 2 updated!\n".to_vec();
1237        let new_blob_raw = RawObject::new(ObjectKind::Blob, new_bytes.clone());
1238        let new_blob_oid = new_blob_raw.oid(fmt).unwrap();
1239        let c2_tree_raw = RawObject::new(
1240            ObjectKind::Tree,
1241            Tree {
1242                entries: vec![TreeEntry {
1243                    mode: TreeMode::File,
1244                    name: "a.txt".into(),
1245                    oid: new_blob_oid,
1246                }],
1247            }
1248            .encode()
1249            .unwrap(),
1250        );
1251        let c2_tree_oid = c2_tree_raw.oid(fmt).unwrap();
1252        let c2_raw = RawObject::new(
1253            ObjectKind::Commit,
1254            Commit {
1255                tree: c2_tree_oid,
1256                parents: vec![c1],
1257                author: sig.clone(),
1258                committer: sig,
1259                gpgsig: None,
1260                message: "thin delta update\n".into(),
1261            }
1262            .encode()
1263            .unwrap(),
1264        );
1265        let c2 = c2_raw.oid(fmt).unwrap();
1266
1267        let delta = arks_pack::create_delta(&base_bytes, &new_bytes, 4096).unwrap();
1268
1269        let push_hdr = |buf: &mut Vec<u8>, ty: u8, mut sz: usize| {
1270            let mut b = ((ty & 0x07) << 4) | ((sz & 0x0f) as u8);
1271            sz >>= 4;
1272            while sz > 0 {
1273                buf.push(b | 0x80);
1274                b = (sz & 0x7f) as u8;
1275                sz >>= 7;
1276            }
1277            buf.push(b);
1278        };
1279        let zlib_of = |data: &[u8]| -> Vec<u8> {
1280            let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1281            enc.write_all(data).unwrap();
1282            enc.finish().unwrap()
1283        };
1284
1285        let mut pack = Vec::new();
1286        pack.extend_from_slice(b"PACK");
1287        pack.extend_from_slice(&2u32.to_be_bytes());
1288        pack.extend_from_slice(&3u32.to_be_bytes());
1289        // 1) OBJ_REF_DELTA (type 7) referencing `base_blob_oid` already in repo ODB
1290        push_hdr(&mut pack, 7, delta.len());
1291        pack.extend_from_slice(base_blob_oid.as_bytes());
1292        pack.extend_from_slice(&zlib_of(&delta));
1293        // 2) OBJ_TREE (type 2)
1294        push_hdr(&mut pack, 2, c2_tree_raw.payload.len());
1295        pack.extend_from_slice(&zlib_of(&c2_tree_raw.payload));
1296        // 3) OBJ_COMMIT (type 1)
1297        push_hdr(&mut pack, 1, c2_raw.payload.len());
1298        pack.extend_from_slice(&zlib_of(&c2_raw.payload));
1299        arks_pack::trailer(&mut pack, fmt);
1300
1301        let mut body = make_receive_body(c1, c2, "refs/heads/main");
1302        body.extend_from_slice(&pack);
1303
1304        let reply = String::from_utf8_lossy(&receive_pack(&mut repo, &body).unwrap()).into_owned();
1305        assert!(
1306            reply.contains("unpack ok"),
1307            "thin pack unpack must succeed against existing repo objects: {reply}"
1308        );
1309        assert!(
1310            reply.contains("ok refs/heads/main"),
1311            "ref update after thin pack unpack must succeed: {reply}"
1312        );
1313        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
1314        assert_eq!(repo.get_object(&new_blob_oid).unwrap().payload, new_bytes);
1315    }
1316}