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.sort_by(|a, b| a.0.cmp(&b.0));
36    if let Ok(oid) = repo.refs().resolve("HEAD") {
37        if !refs.iter().any(|(n, _)| n == "HEAD") {
38            refs.insert(0, ("HEAD".into(), oid));
39        }
40    } else if let Ok(RefTarget::Direct(oid)) = repo.head_target() {
41        refs.insert(0, ("HEAD".into(), oid));
42    }
43    // Advertise only real caps. FS2: advertise `proc-receive` when hook present.
44    // Cite: https://git-scm.com/docs/gitprotocol-capabilities
45    let mut caps = vec![
46        "report-status".into(),
47        "report-status-v2".into(),
48        "delete-refs".into(),
49        "push-options".into(),
50        "agent=arks/0.0.0".into(),
51    ];
52    if proc_receive_hook_present(repo.git_dir()) {
53        caps.insert(caps.len() - 1, "proc-receive".into());
54    }
55    Ok((refs, caps))
56}
57
58/// Smart-HTTP receive-pack advertisement.
59pub fn receive_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
60    let (refs, caps) = receive_refs_and_caps(repo)?;
61    encode_http_advertisement("git-receive-pack", &caps, &refs)
62}
63
64/// Pack-protocol duplex receive-pack advertisement (SSH / stdio).
65pub fn receive_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
66    let (refs, caps) = receive_refs_and_caps(repo)?;
67    encode_pack_advertisement(&caps, &refs)
68}
69
70/// receive-pack with the installed push policy and a local pusher.
71pub fn receive_pack(repo: &mut Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
72    receive_pack_as(repo, body, &Pusher::local())
73}
74
75/// receive-pack with the installed push policy ([`crate::install_push_policy`]).
76pub fn receive_pack_as(
77    repo: &mut Repository,
78    body: &[u8],
79    pusher: &Pusher,
80) -> Result<Vec<u8>, ServerError> {
81    let policy = installed_push_policy();
82    receive_pack_with(repo, body, pusher, policy.as_deref())
83}
84
85/// receive-pack gated by an explicit push policy: each refused ref is reported
86/// `ng <ref> <reason>` and left unchanged; other refs proceed.
87pub fn receive_pack_with(
88    repo: &mut Repository,
89    body: &[u8],
90    pusher: &Pusher,
91    policy: Option<&dyn PushPolicy>,
92) -> Result<Vec<u8>, ServerError> {
93    let (commands, push_options, pack) = split_commands(body)?;
94    let quarantine = Quarantine::create(repo.git_dir())?;
95    let hook_env = HookEnv {
96        quarantine_path: Some(quarantine.path.clone()),
97        push_options,
98    };
99
100    if !pack.is_empty() {
101        if !pack.starts_with(b"PACK") {
102            quarantine.discard();
103            return encode_report_status("unpack unpacker error", &[]);
104        }
105        let decoded = match DecodedPack::decode(&pack, repo.object_format()) {
106            Ok(d) => d,
107            Err(e) => {
108                quarantine.discard();
109                return encode_report_status(&format!("unpack {e}"), &[]);
110            }
111        };
112        let mut qstore = FilesystemGitStore::new(&quarantine.path)
113            .map_err(|e| ServerError::Msg(e.to_string()))?;
114        for object in decoded.objects {
115            qstore
116                .put(repo.object_format(), &object.object)
117                .map_err(|e| ServerError::Msg(e.to_string()))?;
118        }
119    }
120
121    // Honor list: pre-receive once after unpack, before any ref update.
122    // Cite: https://git-scm.com/docs/githooks , https://git-scm.com/docs/git-receive-pack
123    let pre_stdin = hook_stdin_lines(&commands);
124    if run_pre_receive(repo.git_dir(), &pre_stdin, &hook_env)? == HookGate::Decline {
125        quarantine.discard();
126        let declined: Vec<(String, Result<(), String>)> = commands
127            .iter()
128            .map(|cmd| (cmd.name.clone(), Err("pre-receive hook declined".into())))
129            .collect();
130        return encode_report_status_owned("ok", &declined);
131    }
132
133    // Migrate quarantined objects into the main store only after pre-receive.
134    quarantine.migrate_into(repo).map_err(ServerError::Msg)?;
135
136    let prefixes = proc_receive_ref_prefixes(repo.git_dir());
137    let use_proc = proc_receive_hook_present(repo.git_dir()) && !prefixes.is_empty();
138
139    // Push policy (forge rulesets): decided per ref after unpack, before any ref moves.
140    let updates: Vec<RefUpdate> = commands
141        .iter()
142        .map(|c| RefUpdate {
143            name: c.name.clone(),
144            old: c.old,
145            new: c.new,
146        })
147        .collect();
148    let refused = verdicts(policy, repo, pusher, &updates);
149
150    let mut results: Vec<(String, Result<(), String>)> = Vec::new();
151    let mut success_cmds: Vec<ReceiveCommand> = Vec::new();
152    let mut diverted: Vec<ReceiveCommand> = Vec::new();
153    let mut ordinary: Vec<&ReceiveCommand> = Vec::new();
154    for (cmd, refusal) in commands.iter().zip(refused) {
155        if let Some(reason) = refusal {
156            results.push((cmd.name.clone(), Err(reason)));
157            continue;
158        }
159        if use_proc && ref_matches_proc_receive(&cmd.name, &prefixes) {
160            diverted.push(cmd.clone());
161        } else {
162            ordinary.push(cmd);
163        }
164    }
165
166    for cmd in ordinary {
167        let old = repo.refs().resolve(&cmd.name).ok();
168        // Expect old matches when peer sent non-zero old (fast-forward check deferred:
169        // accept if old is None or matches cmd.old, else refuse).
170        if !cmd.old.as_bytes().iter().all(|b| *b == 0) {
171            match old {
172                Some(oid) if oid != cmd.old => {
173                    results.push((cmd.name.clone(), Err("non-fast-forward".into())));
174                    continue;
175                }
176                None => {
177                    results.push((cmd.name.clone(), Err("old oid mismatch".into())));
178                    continue;
179                }
180                _ => {}
181            }
182        }
183        let old_hex = cmd.old.to_hex();
184        let new_hex = cmd.new.to_hex();
185        if run_update(repo.git_dir(), &cmd.name, &old_hex, &new_hex, &hook_env)?
186            == HookGate::Decline
187        {
188            results.push((cmd.name.clone(), Err("hook declined".into())));
189            continue;
190        }
191        if let Some(branch) = cmd.name.strip_prefix("refs/heads/") {
192            if is_delete(cmd) && crate::web_ui::is_branch_delete_protected(repo, branch) {
193                results.push((
194                    cmd.name.clone(),
195                    Err("branch deletion blocked by branch protection rule".into()),
196                ));
197                continue;
198            }
199            if !is_delete(cmd) {
200                if let Some(old_oid) = old {
201                    if old_oid != cmd.new
202                        && crate::web_ui::is_force_push_blocked(repo.common_dir(), branch)
203                        && !is_commit_ancestor(repo, old_oid, cmd.new)
204                    {
205                        results.push((
206                            cmd.name.clone(),
207                            Err("force push blocked by branch protection rule".into()),
208                        ));
209                        continue;
210                    }
211                }
212            }
213        }
214        if is_delete(cmd) {
215            match repo.refs_mut().delete(&cmd.name, old.as_ref()) {
216                Ok(()) => {
217                    results.push((cmd.name.clone(), Ok(())));
218                    success_cmds.push(cmd.clone());
219                }
220                Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
221            }
222            continue;
223        }
224        match repo.refs_mut().update(&cmd.name, &cmd.new, old.as_ref()) {
225            Ok(()) => {
226                results.push((cmd.name.clone(), Ok(())));
227                success_cmds.push(cmd.clone());
228                crate::web_ui::dispatch_webhook_event(
229                    repo.common_dir(),
230                    "push",
231                    &format!(
232                        "{{\"event\":\"push\",\"ref\":\"{}\",\"before\":\"{old_hex}\",\"after\":\"{new_hex}\"}}",
233                        cmd.name.replace('"', "")
234                    ),
235                );
236                crate::web_ui::trigger_event_workflows(repo.common_dir(), "push");
237            }
238            Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
239        }
240    }
241
242    if !diverted.is_empty() {
243        // FS8 / HOOK-008 closest: refuse concurrent proc-receive under lock.
244        let pr_lock = repo.git_dir().join("hooks").join("proc-receive.lock");
245        if pr_lock.is_file() {
246            return Err(ServerError::Msg(format!(
247                "{} (HOOK-008 — concurrent proc-receive refuse; serialize push-options/proc-receive; lease ≠ skip)",
248                pr_lock.display()
249            )));
250        }
251        let _ = fs::write(&pr_lock, b"arks-proc-receive\n");
252        let pr_cmds: Vec<ProcReceiveCmd> = diverted
253            .iter()
254            .map(|c| ProcReceiveCmd {
255                old_hex: c.old.to_hex(),
256                new_hex: c.new.to_hex(),
257                name: c.name.clone(),
258            })
259            .collect();
260        let pr_results = match run_proc_receive(repo.git_dir(), &pr_cmds, &hook_env) {
261            Ok(r) => {
262                let _ = fs::remove_file(&pr_lock);
263                r
264            }
265            Err(e) => {
266                let _ = fs::remove_file(&pr_lock);
267                return Err(e);
268            }
269        };
270        for pr in pr_results {
271            if !pr.ok {
272                results.push((
273                    pr.name,
274                    Err(pr.error.unwrap_or_else(|| "proc-receive declined".into())),
275                ));
276                continue;
277            }
278            // Apply rewrite if hook provided option refname / new-oid; else
279            // treat ok as "hook handled ref" without receive-pack updating the
280            // original name (stock git behavior for successful proc-receive).
281            let target_name = pr.rewrite_ref.clone().unwrap_or_else(|| pr.name.clone());
282            let new_oid = if let Some(hex) = &pr.rewrite_new {
283                Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?
284            } else {
285                diverted
286                    .iter()
287                    .find(|c| c.name == pr.name)
288                    .map(|c| c.new)
289                    .ok_or_else(|| ServerError::Msg("proc-receive missing cmd".into()))?
290            };
291            let old_hint = if let Some(hex) = &pr.rewrite_old {
292                Some(Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?)
293            } else {
294                repo.refs().resolve(&target_name).ok()
295            };
296            if new_oid.as_bytes().iter().all(|b| *b == 0) {
297                match repo.refs_mut().delete(&target_name, old_hint.as_ref()) {
298                    Ok(()) => {
299                        results.push((pr.name, Ok(())));
300                        success_cmds.push(ReceiveCommand {
301                            old: old_hint.unwrap_or_else(zero_oid),
302                            new: new_oid,
303                            name: target_name,
304                        });
305                    }
306                    Err(e) => results.push((pr.name, Err(e.to_string()))),
307                }
308            } else {
309                match repo
310                    .refs_mut()
311                    .update(&target_name, &new_oid, old_hint.as_ref())
312                {
313                    Ok(()) => {
314                        results.push((pr.name, Ok(())));
315                        success_cmds.push(ReceiveCommand {
316                            old: old_hint.unwrap_or_else(zero_oid),
317                            new: new_oid,
318                            name: target_name,
319                        });
320                    }
321                    Err(e) => results.push((pr.name, Err(e.to_string()))),
322                }
323            }
324        }
325    }
326
327    if !success_cmds.is_empty() {
328        let post_stdin = hook_stdin_lines_refs(success_cmds.iter());
329        run_post_receive(repo.git_dir(), &post_stdin, &hook_env);
330        let names: Vec<&str> = success_cmds.iter().map(|c| c.name.as_str()).collect();
331        run_post_update(repo.git_dir(), &names, &hook_env);
332    }
333
334    encode_report_status_owned("ok", &results)
335}
336
337/// Quarantine object dir under `$GIT_DIR/objects` (git-receive-pack).
338struct Quarantine {
339    path: PathBuf,
340}
341
342impl Quarantine {
343    fn create(git_dir: &Path) -> Result<Self, ServerError> {
344        let objects = git_dir.join("objects");
345        fs::create_dir_all(&objects)?;
346        let nanos = SystemTime::now()
347            .duration_since(UNIX_EPOCH)
348            .map(|d| d.as_nanos())
349            .unwrap_or(0);
350        let path = objects.join(format!("incoming-{nanos}-{}", std::process::id()));
351        fs::create_dir_all(&path)?;
352        Ok(Self { path })
353    }
354
355    fn discard(self) {
356        let _ = fs::remove_dir_all(&self.path);
357    }
358
359    fn migrate_into(self, repo: &mut Repository) -> Result<(), String> {
360        // Walk quarantine loose objects and put into the main store.
361        let Ok(entries) = fs::read_dir(&self.path) else {
362            let _ = fs::remove_dir_all(&self.path);
363            return Ok(());
364        };
365        for entry in entries.flatten() {
366            let name = entry.file_name();
367            let name = name.to_string_lossy();
368            if name.len() != 2 {
369                continue;
370            }
371            let fanout = entry.path();
372            let Ok(objs) = fs::read_dir(&fanout) else {
373                continue;
374            };
375            for obj in objs.flatten() {
376                let fname = obj.file_name();
377                let rest = fname.to_string_lossy();
378                let hex = format!("{name}{rest}");
379                let Ok(oid) = Oid::from_hex(&hex) else {
380                    continue;
381                };
382                // Read via a store rooted at quarantine so packed/overlay stays honest.
383                let qstore = FilesystemGitStore::open(&self.path);
384                match qstore.get(&oid) {
385                    Ok(raw) => {
386                        let format = repo.object_format();
387                        repo.store_mut()
388                            .put(format, &raw)
389                            .map_err(|e| e.to_string())?;
390                    }
391                    Err(_) => continue,
392                }
393            }
394        }
395        let _ = fs::remove_dir_all(&self.path);
396        Ok(())
397    }
398}
399
400fn is_delete(cmd: &ReceiveCommand) -> bool {
401    cmd.new.as_bytes().iter().all(|b| *b == 0)
402}
403
404fn zero_oid() -> Oid {
405    Oid::from_hex("0000000000000000000000000000000000000000").expect("zero oid")
406}
407
408fn hook_stdin_lines(commands: &[ReceiveCommand]) -> Vec<u8> {
409    hook_stdin_lines_refs(commands.iter())
410}
411
412fn hook_stdin_lines_refs<'a, I>(commands: I) -> Vec<u8>
413where
414    I: IntoIterator<Item = &'a ReceiveCommand>,
415{
416    let mut out = Vec::new();
417    for cmd in commands {
418        out.extend(format!("{} {} {}\n", cmd.old.to_hex(), cmd.new.to_hex(), cmd.name).as_bytes());
419    }
420    out
421}
422
423#[derive(Debug, Clone)]
424struct ReceiveCommand {
425    old: Oid,
426    new: Oid,
427    name: String,
428}
429
430type SplitCommands = (Vec<ReceiveCommand>, Vec<String>, Vec<u8>);
431
432fn split_commands(body: &[u8]) -> Result<SplitCommands, ServerError> {
433    let mut offset = 0;
434    let mut commands = Vec::new();
435    let mut saw_push_options_cap = false;
436    while offset < body.len() {
437        let (packet, n) =
438            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
439        offset += n;
440        match packet {
441            Packet::Flush => break,
442            Packet::Data(payload) => {
443                let owned = if let Some(nul) = payload.iter().position(|b| *b == 0) {
444                    let text = std::str::from_utf8(&payload[..nul])
445                        .map_err(|_| ServerError::Protocol("command not utf-8".into()))?
446                        .to_string();
447                    let caps = std::str::from_utf8(&payload[nul + 1..]).unwrap_or("");
448                    if caps.split_whitespace().any(|c| c == "push-options") {
449                        saw_push_options_cap = true;
450                    }
451                    text
452                } else {
453                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?
454                };
455                let text = owned.trim_end_matches('\n');
456                let mut parts = text.splitn(3, ' ');
457                let old_hex = parts
458                    .next()
459                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
460                let new_hex = parts
461                    .next()
462                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
463                let name = parts
464                    .next()
465                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
466                // Capability list may trail the first command after a NUL already handled;
467                // also accept space-separated caps after the refname on some peers.
468                if name.contains("push-options") || text.contains(" push-options") {
469                    saw_push_options_cap = true;
470                }
471                let refname = name.split('\0').next().unwrap_or(name).to_string();
472                commands.push(ReceiveCommand {
473                    old: Oid::from_hex(old_hex)
474                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
475                    new: Oid::from_hex(new_hex)
476                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
477                    name: refname,
478                });
479            }
480            _ => {}
481        }
482    }
483    let mut push_options = Vec::new();
484    if saw_push_options_cap {
485        while offset < body.len() {
486            if body[offset..].starts_with(b"PACK") {
487                break;
488            }
489            let (packet, n) =
490                decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
491            offset += n;
492            match packet {
493                Packet::Flush => break,
494                Packet::Data(payload) => {
495                    let line = decode_text_line(&payload)
496                        .map_err(|e| ServerError::Protocol(e.to_string()))?;
497                    let line = line.trim_end_matches('\n');
498                    if let Some(rest) = line.strip_prefix("push-option ") {
499                        push_options.push(rest.to_string());
500                    } else if line == "push-option" {
501                        push_options.push(String::new());
502                    } else {
503                        return Err(ServerError::Protocol(format!(
504                            "expected push-option line, got {line}"
505                        )));
506                    }
507                }
508                _ => {}
509            }
510        }
511    }
512    Ok((commands, push_options, body[offset..].to_vec()))
513}
514
515fn encode_report_status_owned(
516    unpack: &str,
517    refs: &[(String, Result<(), String>)],
518) -> Result<Vec<u8>, ServerError> {
519    let borrowed: Vec<(&str, Result<(), &str>)> = refs
520        .iter()
521        .map(|(n, r)| {
522            (
523                n.as_str(),
524                match r {
525                    Ok(()) => Ok(()),
526                    Err(e) => Err(e.as_str()),
527                },
528            )
529        })
530        .collect();
531    encode_report_status(unpack, &borrowed)
532}
533
534fn encode_report_status(
535    unpack: &str,
536    refs: &[(&str, Result<(), &str>)],
537) -> Result<Vec<u8>, ServerError> {
538    // Classic unpack/ok/ng lines are valid report-status and report-status-v2
539    // when no proc-receive rewrite options are needed.
540    let mut out = Vec::new();
541    out.extend(text_pkt(&format!("unpack {unpack}"))?);
542    for (name, result) in refs {
543        match result {
544            Ok(()) => out.extend(text_pkt(&format!("ok {name}"))?),
545            Err(err) => out.extend(text_pkt(&format!("ng {name} {err}"))?),
546        }
547    }
548    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
549    Ok(out)
550}
551
552fn text_pkt(text: &str) -> Result<Vec<u8>, ServerError> {
553    let mut payload = text.as_bytes().to_vec();
554    if !payload.ends_with(b"\n") {
555        payload.push(b'\n');
556    }
557    encode_packet(&Packet::Data(payload)).map_err(|e| ServerError::Protocol(e.to_string()))
558}
559
560fn is_commit_ancestor(repo: &Repository, ancestor: Oid, descendant: Oid) -> bool {
561    if ancestor == descendant {
562        return true;
563    }
564    let mut queue = std::collections::VecDeque::new();
565    let mut visited = std::collections::HashSet::new();
566    queue.push_back(descendant);
567    visited.insert(descendant);
568    let mut steps = 0usize;
569    while let Some(cur) = queue.pop_front() {
570        steps += 1;
571        if steps > 4096 {
572            break;
573        }
574        let Ok(obj) = repo.get_object(&cur) else {
575            continue;
576        };
577        if obj.kind != arks_object::ObjectKind::Commit {
578            continue;
579        }
580        let Ok(commit) = arks_object::Commit::decode(&obj.payload) else {
581            continue;
582        };
583        for parent in commit.parents {
584            if parent == ancestor {
585                return true;
586            }
587            if visited.insert(parent) {
588                queue.push_back(parent);
589            }
590        }
591    }
592    false
593}