arks-server 0.4.0

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! receive-pack service (push path).
//!
//! Claimed caps: `report-status`, `report-status-v2` (classic ok/ng + FS2
//! proc-receive option rewrite when diverted), `delete-refs`,
//! `push-options` (O4; forward to hooks), `proc-receive` (FS2 when hook
//! present), `agent`.
//! Cite: <https://git-scm.com/docs/gitprotocol-capabilities>,
//! <https://git-scm.com/docs/git-receive-pack> (quarantine environment).

use crate::advertise::{encode_http_advertisement, encode_pack_advertisement};
use crate::error::ServerError;
use crate::hooks::{
    HookEnv, HookGate, ProcReceiveCmd, proc_receive_hook_present, proc_receive_ref_prefixes,
    ref_matches_proc_receive, run_post_receive, run_post_update, run_pre_receive, run_proc_receive,
    run_update,
};
use crate::push_policy::{PushPolicy, Pusher, RefUpdate, installed_push_policy, verdicts};
use arks_oid::Oid;
use arks_pack::DecodedPack;
use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet};
use arks_refs::RefTarget;
use arks_repo::Repository;
use arks_store::{FilesystemGitStore, ObjectStore};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

type RefsAndCaps = (Vec<(String, Oid)>, Vec<String>);

fn receive_refs_and_caps(repo: &Repository) -> Result<RefsAndCaps, ServerError> {
    let mut refs = repo
        .refs()
        .list_refs("refs/")
        .map_err(|e| ServerError::Msg(e.to_string()))?;
    refs.sort_by(|a, b| a.0.cmp(&b.0));
    if let Ok(oid) = repo.refs().resolve("HEAD") {
        if !refs.iter().any(|(n, _)| n == "HEAD") {
            refs.insert(0, ("HEAD".into(), oid));
        }
    } else if let Ok(RefTarget::Direct(oid)) = repo.head_target() {
        refs.insert(0, ("HEAD".into(), oid));
    }
    // Advertise only real caps. FS2: advertise `proc-receive` when hook present.
    // Cite: https://git-scm.com/docs/gitprotocol-capabilities
    let mut caps = vec![
        "report-status".into(),
        "report-status-v2".into(),
        "delete-refs".into(),
        "push-options".into(),
        "agent=arks/0.0.0".into(),
    ];
    if proc_receive_hook_present(repo.git_dir()) {
        caps.insert(caps.len() - 1, "proc-receive".into());
    }
    Ok((refs, caps))
}

/// Smart-HTTP receive-pack advertisement.
pub fn receive_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
    let (refs, caps) = receive_refs_and_caps(repo)?;
    encode_http_advertisement("git-receive-pack", &caps, &refs)
}

/// Pack-protocol duplex receive-pack advertisement (SSH / stdio).
pub fn receive_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
    let (refs, caps) = receive_refs_and_caps(repo)?;
    encode_pack_advertisement(&caps, &refs)
}

/// receive-pack with the installed push policy and a local pusher.
pub fn receive_pack(repo: &mut Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
    receive_pack_as(repo, body, &Pusher::local())
}

/// receive-pack with the installed push policy ([`crate::install_push_policy`]).
pub fn receive_pack_as(
    repo: &mut Repository,
    body: &[u8],
    pusher: &Pusher,
) -> Result<Vec<u8>, ServerError> {
    let policy = installed_push_policy();
    receive_pack_with(repo, body, pusher, policy.as_deref())
}

/// receive-pack gated by an explicit push policy: each refused ref is reported
/// `ng <ref> <reason>` and left unchanged; other refs proceed.
pub fn receive_pack_with(
    repo: &mut Repository,
    body: &[u8],
    pusher: &Pusher,
    policy: Option<&dyn PushPolicy>,
) -> Result<Vec<u8>, ServerError> {
    let (commands, push_options, pack) = split_commands(body)?;
    let quarantine = Quarantine::create(repo.git_dir())?;
    let hook_env = HookEnv {
        quarantine_path: Some(quarantine.path.clone()),
        push_options,
    };

    if !pack.is_empty() {
        if !pack.starts_with(b"PACK") {
            quarantine.discard();
            return encode_report_status("unpack unpacker error", &[]);
        }
        let decoded = match DecodedPack::decode(&pack, repo.object_format()) {
            Ok(d) => d,
            Err(e) => {
                quarantine.discard();
                return encode_report_status(&format!("unpack {e}"), &[]);
            }
        };
        let mut qstore = FilesystemGitStore::new(&quarantine.path)
            .map_err(|e| ServerError::Msg(e.to_string()))?;
        for object in decoded.objects {
            qstore
                .put(repo.object_format(), &object.object)
                .map_err(|e| ServerError::Msg(e.to_string()))?;
        }
    }

    // Honor list: pre-receive once after unpack, before any ref update.
    // Cite: https://git-scm.com/docs/githooks , https://git-scm.com/docs/git-receive-pack
    let pre_stdin = hook_stdin_lines(&commands);
    if run_pre_receive(repo.git_dir(), &pre_stdin, &hook_env)? == HookGate::Decline {
        quarantine.discard();
        let declined: Vec<(String, Result<(), String>)> = commands
            .iter()
            .map(|cmd| (cmd.name.clone(), Err("pre-receive hook declined".into())))
            .collect();
        return encode_report_status_owned("ok", &declined);
    }

    // Migrate quarantined objects into the main store only after pre-receive.
    quarantine.migrate_into(repo).map_err(ServerError::Msg)?;

    let prefixes = proc_receive_ref_prefixes(repo.git_dir());
    let use_proc = proc_receive_hook_present(repo.git_dir()) && !prefixes.is_empty();

    // Push policy (forge rulesets): decided per ref after unpack, before any ref moves.
    let updates: Vec<RefUpdate> = commands
        .iter()
        .map(|c| RefUpdate {
            name: c.name.clone(),
            old: c.old,
            new: c.new,
        })
        .collect();
    let refused = verdicts(policy, repo, pusher, &updates);

    let mut results: Vec<(String, Result<(), String>)> = Vec::new();
    let mut success_cmds: Vec<ReceiveCommand> = Vec::new();
    let mut diverted: Vec<ReceiveCommand> = Vec::new();
    let mut ordinary: Vec<&ReceiveCommand> = Vec::new();
    for (cmd, refusal) in commands.iter().zip(refused) {
        if let Some(reason) = refusal {
            results.push((cmd.name.clone(), Err(reason)));
            continue;
        }
        if use_proc && ref_matches_proc_receive(&cmd.name, &prefixes) {
            diverted.push(cmd.clone());
        } else {
            ordinary.push(cmd);
        }
    }

    for cmd in ordinary {
        let old = repo.refs().resolve(&cmd.name).ok();
        // Expect old matches when peer sent non-zero old (fast-forward check deferred:
        // accept if old is None or matches cmd.old, else refuse).
        if !cmd.old.as_bytes().iter().all(|b| *b == 0) {
            match old {
                Some(oid) if oid != cmd.old => {
                    results.push((cmd.name.clone(), Err("non-fast-forward".into())));
                    continue;
                }
                None => {
                    results.push((cmd.name.clone(), Err("old oid mismatch".into())));
                    continue;
                }
                _ => {}
            }
        }
        let old_hex = cmd.old.to_hex();
        let new_hex = cmd.new.to_hex();
        if run_update(repo.git_dir(), &cmd.name, &old_hex, &new_hex, &hook_env)?
            == HookGate::Decline
        {
            results.push((cmd.name.clone(), Err("hook declined".into())));
            continue;
        }
        if let Some(branch) = cmd.name.strip_prefix("refs/heads/") {
            if is_delete(cmd) && crate::web_ui::is_branch_delete_protected(repo, branch) {
                results.push((
                    cmd.name.clone(),
                    Err("branch deletion blocked by branch protection rule".into()),
                ));
                continue;
            }
            if !is_delete(cmd) {
                if let Some(old_oid) = old {
                    if old_oid != cmd.new
                        && crate::web_ui::is_force_push_blocked(repo.common_dir(), branch)
                        && !is_commit_ancestor(repo, old_oid, cmd.new)
                    {
                        results.push((
                            cmd.name.clone(),
                            Err("force push blocked by branch protection rule".into()),
                        ));
                        continue;
                    }
                }
            }
        }
        if is_delete(cmd) {
            match repo.refs_mut().delete(&cmd.name, old.as_ref()) {
                Ok(()) => {
                    results.push((cmd.name.clone(), Ok(())));
                    success_cmds.push(cmd.clone());
                }
                Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
            }
            continue;
        }
        match repo.refs_mut().update(&cmd.name, &cmd.new, old.as_ref()) {
            Ok(()) => {
                results.push((cmd.name.clone(), Ok(())));
                success_cmds.push(cmd.clone());
                crate::web_ui::dispatch_webhook_event(
                    repo.common_dir(),
                    "push",
                    &format!(
                        "{{\"event\":\"push\",\"ref\":\"{}\",\"before\":\"{old_hex}\",\"after\":\"{new_hex}\"}}",
                        cmd.name.replace('"', "")
                    ),
                );
                crate::web_ui::trigger_event_workflows(repo.common_dir(), "push");
            }
            Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
        }
    }

    if !diverted.is_empty() {
        // FS8 / HOOK-008 closest: refuse concurrent proc-receive under lock.
        let pr_lock = repo.git_dir().join("hooks").join("proc-receive.lock");
        if pr_lock.is_file() {
            return Err(ServerError::Msg(format!(
                "{} (HOOK-008 — concurrent proc-receive refuse; serialize push-options/proc-receive; lease ≠ skip)",
                pr_lock.display()
            )));
        }
        let _ = fs::write(&pr_lock, b"arks-proc-receive\n");
        let pr_cmds: Vec<ProcReceiveCmd> = diverted
            .iter()
            .map(|c| ProcReceiveCmd {
                old_hex: c.old.to_hex(),
                new_hex: c.new.to_hex(),
                name: c.name.clone(),
            })
            .collect();
        let pr_results = match run_proc_receive(repo.git_dir(), &pr_cmds, &hook_env) {
            Ok(r) => {
                let _ = fs::remove_file(&pr_lock);
                r
            }
            Err(e) => {
                let _ = fs::remove_file(&pr_lock);
                return Err(e);
            }
        };
        for pr in pr_results {
            if !pr.ok {
                results.push((
                    pr.name,
                    Err(pr.error.unwrap_or_else(|| "proc-receive declined".into())),
                ));
                continue;
            }
            // Apply rewrite if hook provided option refname / new-oid; else
            // treat ok as "hook handled ref" without receive-pack updating the
            // original name (stock git behavior for successful proc-receive).
            let target_name = pr.rewrite_ref.clone().unwrap_or_else(|| pr.name.clone());
            let new_oid = if let Some(hex) = &pr.rewrite_new {
                Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?
            } else {
                diverted
                    .iter()
                    .find(|c| c.name == pr.name)
                    .map(|c| c.new)
                    .ok_or_else(|| ServerError::Msg("proc-receive missing cmd".into()))?
            };
            let old_hint = if let Some(hex) = &pr.rewrite_old {
                Some(Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?)
            } else {
                repo.refs().resolve(&target_name).ok()
            };
            if new_oid.as_bytes().iter().all(|b| *b == 0) {
                match repo.refs_mut().delete(&target_name, old_hint.as_ref()) {
                    Ok(()) => {
                        results.push((pr.name, Ok(())));
                        success_cmds.push(ReceiveCommand {
                            old: old_hint.unwrap_or_else(zero_oid),
                            new: new_oid,
                            name: target_name,
                        });
                    }
                    Err(e) => results.push((pr.name, Err(e.to_string()))),
                }
            } else {
                match repo
                    .refs_mut()
                    .update(&target_name, &new_oid, old_hint.as_ref())
                {
                    Ok(()) => {
                        results.push((pr.name, Ok(())));
                        success_cmds.push(ReceiveCommand {
                            old: old_hint.unwrap_or_else(zero_oid),
                            new: new_oid,
                            name: target_name,
                        });
                    }
                    Err(e) => results.push((pr.name, Err(e.to_string()))),
                }
            }
        }
    }

    if !success_cmds.is_empty() {
        let post_stdin = hook_stdin_lines_refs(success_cmds.iter());
        run_post_receive(repo.git_dir(), &post_stdin, &hook_env);
        let names: Vec<&str> = success_cmds.iter().map(|c| c.name.as_str()).collect();
        run_post_update(repo.git_dir(), &names, &hook_env);
    }

    encode_report_status_owned("ok", &results)
}

/// Quarantine object dir under `$GIT_DIR/objects` (git-receive-pack).
struct Quarantine {
    path: PathBuf,
}

impl Quarantine {
    fn create(git_dir: &Path) -> Result<Self, ServerError> {
        let objects = git_dir.join("objects");
        fs::create_dir_all(&objects)?;
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let path = objects.join(format!("incoming-{nanos}-{}", std::process::id()));
        fs::create_dir_all(&path)?;
        Ok(Self { path })
    }

    fn discard(self) {
        let _ = fs::remove_dir_all(&self.path);
    }

    fn migrate_into(self, repo: &mut Repository) -> Result<(), String> {
        // Walk quarantine loose objects and put into the main store.
        let Ok(entries) = fs::read_dir(&self.path) else {
            let _ = fs::remove_dir_all(&self.path);
            return Ok(());
        };
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.len() != 2 {
                continue;
            }
            let fanout = entry.path();
            let Ok(objs) = fs::read_dir(&fanout) else {
                continue;
            };
            for obj in objs.flatten() {
                let fname = obj.file_name();
                let rest = fname.to_string_lossy();
                let hex = format!("{name}{rest}");
                let Ok(oid) = Oid::from_hex(&hex) else {
                    continue;
                };
                // Read via a store rooted at quarantine so packed/overlay stays honest.
                let qstore = FilesystemGitStore::open(&self.path);
                match qstore.get(&oid) {
                    Ok(raw) => {
                        let format = repo.object_format();
                        repo.store_mut()
                            .put(format, &raw)
                            .map_err(|e| e.to_string())?;
                    }
                    Err(_) => continue,
                }
            }
        }
        let _ = fs::remove_dir_all(&self.path);
        Ok(())
    }
}

fn is_delete(cmd: &ReceiveCommand) -> bool {
    cmd.new.as_bytes().iter().all(|b| *b == 0)
}

fn zero_oid() -> Oid {
    Oid::from_hex("0000000000000000000000000000000000000000").expect("zero oid")
}

fn hook_stdin_lines(commands: &[ReceiveCommand]) -> Vec<u8> {
    hook_stdin_lines_refs(commands.iter())
}

fn hook_stdin_lines_refs<'a, I>(commands: I) -> Vec<u8>
where
    I: IntoIterator<Item = &'a ReceiveCommand>,
{
    let mut out = Vec::new();
    for cmd in commands {
        out.extend(format!("{} {} {}\n", cmd.old.to_hex(), cmd.new.to_hex(), cmd.name).as_bytes());
    }
    out
}

#[derive(Debug, Clone)]
struct ReceiveCommand {
    old: Oid,
    new: Oid,
    name: String,
}

type SplitCommands = (Vec<ReceiveCommand>, Vec<String>, Vec<u8>);

fn split_commands(body: &[u8]) -> Result<SplitCommands, ServerError> {
    let mut offset = 0;
    let mut commands = Vec::new();
    let mut saw_push_options_cap = false;
    while offset < body.len() {
        let (packet, n) =
            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
        offset += n;
        match packet {
            Packet::Flush => break,
            Packet::Data(payload) => {
                let owned = if let Some(nul) = payload.iter().position(|b| *b == 0) {
                    let text = std::str::from_utf8(&payload[..nul])
                        .map_err(|_| ServerError::Protocol("command not utf-8".into()))?
                        .to_string();
                    let caps = std::str::from_utf8(&payload[nul + 1..]).unwrap_or("");
                    if caps.split_whitespace().any(|c| c == "push-options") {
                        saw_push_options_cap = true;
                    }
                    text
                } else {
                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?
                };
                let text = owned.trim_end_matches('\n');
                let mut parts = text.splitn(3, ' ');
                let old_hex = parts
                    .next()
                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
                let new_hex = parts
                    .next()
                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
                let name = parts
                    .next()
                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
                // Capability list may trail the first command after a NUL already handled;
                // also accept space-separated caps after the refname on some peers.
                if name.contains("push-options") || text.contains(" push-options") {
                    saw_push_options_cap = true;
                }
                let refname = name.split('\0').next().unwrap_or(name).to_string();
                commands.push(ReceiveCommand {
                    old: Oid::from_hex(old_hex)
                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
                    new: Oid::from_hex(new_hex)
                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
                    name: refname,
                });
            }
            _ => {}
        }
    }
    let mut push_options = Vec::new();
    if saw_push_options_cap {
        while offset < body.len() {
            if body[offset..].starts_with(b"PACK") {
                break;
            }
            let (packet, n) =
                decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
            offset += n;
            match packet {
                Packet::Flush => break,
                Packet::Data(payload) => {
                    let line = decode_text_line(&payload)
                        .map_err(|e| ServerError::Protocol(e.to_string()))?;
                    let line = line.trim_end_matches('\n');
                    if let Some(rest) = line.strip_prefix("push-option ") {
                        push_options.push(rest.to_string());
                    } else if line == "push-option" {
                        push_options.push(String::new());
                    } else {
                        return Err(ServerError::Protocol(format!(
                            "expected push-option line, got {line}"
                        )));
                    }
                }
                _ => {}
            }
        }
    }
    Ok((commands, push_options, body[offset..].to_vec()))
}

fn encode_report_status_owned(
    unpack: &str,
    refs: &[(String, Result<(), String>)],
) -> Result<Vec<u8>, ServerError> {
    let borrowed: Vec<(&str, Result<(), &str>)> = refs
        .iter()
        .map(|(n, r)| {
            (
                n.as_str(),
                match r {
                    Ok(()) => Ok(()),
                    Err(e) => Err(e.as_str()),
                },
            )
        })
        .collect();
    encode_report_status(unpack, &borrowed)
}

fn encode_report_status(
    unpack: &str,
    refs: &[(&str, Result<(), &str>)],
) -> Result<Vec<u8>, ServerError> {
    // Classic unpack/ok/ng lines are valid report-status and report-status-v2
    // when no proc-receive rewrite options are needed.
    let mut out = Vec::new();
    out.extend(text_pkt(&format!("unpack {unpack}"))?);
    for (name, result) in refs {
        match result {
            Ok(()) => out.extend(text_pkt(&format!("ok {name}"))?),
            Err(err) => out.extend(text_pkt(&format!("ng {name} {err}"))?),
        }
    }
    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
    Ok(out)
}

fn text_pkt(text: &str) -> Result<Vec<u8>, ServerError> {
    let mut payload = text.as_bytes().to_vec();
    if !payload.ends_with(b"\n") {
        payload.push(b'\n');
    }
    encode_packet(&Packet::Data(payload)).map_err(|e| ServerError::Protocol(e.to_string()))
}

fn is_commit_ancestor(repo: &Repository, ancestor: Oid, descendant: Oid) -> bool {
    if ancestor == descendant {
        return true;
    }
    let mut queue = std::collections::VecDeque::new();
    let mut visited = std::collections::HashSet::new();
    queue.push_back(descendant);
    visited.insert(descendant);
    let mut steps = 0usize;
    while let Some(cur) = queue.pop_front() {
        steps += 1;
        if steps > 4096 {
            break;
        }
        let Ok(obj) = repo.get_object(&cur) else {
            continue;
        };
        if obj.kind != arks_object::ObjectKind::Commit {
            continue;
        }
        let Ok(commit) = arks_object::Commit::decode(&obj.payload) else {
            continue;
        };
        for parent in commit.parents {
            if parent == ancestor {
                return true;
            }
            if visited.insert(parent) {
                queue.push_back(parent);
            }
        }
    }
    false
}