gitiverse-git 0.3.0

Git object store abstraction, packfile construction, strict quarantine ingest, canonical serialisation, and merge/diff helpers for gitiverse
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use core::fmt;
use core::str::FromStr;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use async_trait::async_trait;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;

/// Errors returned by [`GitStore`] and Git subprocess operations.
#[derive(Debug, Error)]
pub enum GitError {
    #[error("invalid Git OID {0:?}")]
    InvalidOid(String),
    #[error("invalid Git ref name {0:?}")]
    InvalidRefName(String),
    #[error("invalid input: {0}")]
    InvalidInput(String),
    #[error("object not found: {0}")]
    ObjectNotFound(String),
    #[error("compare-and-swap ref update conflict on {ref_name}: {details}")]
    CasConflict { ref_name: String, details: String },
    #[error("packfile or fsck verification failed: {0}")]
    VerificationFailed(String),
    #[error("git command '{command}' failed (status {status:?}): {stderr}")]
    CommandFailed {
        command: String,
        status: Option<i32>,
        stderr: String,
    },
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
}

/// Validated lowercase hexadecimal Git object identifier (40-character SHA-1 or 64-character SHA-256).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Oid(String);

impl Oid {
    pub fn parse(raw: &str) -> Result<Self, GitError> {
        let trimmed = raw.trim();
        let valid_len = trimmed.len() == 40 || trimmed.len() == 64;
        let valid_hex = trimmed
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
        if !valid_len || !valid_hex {
            return Err(GitError::InvalidOid(raw.to_owned()));
        }
        Ok(Self(trimmed.to_owned()))
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for Oid {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Oid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for Oid {
    type Err = GitError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl Serialize for Oid {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Oid {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// Kind of a raw Git object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GitObjectKind {
    Blob,
    Tree,
    Commit,
    Tag,
}

impl GitObjectKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            GitObjectKind::Blob => "blob",
            GitObjectKind::Tree => "tree",
            GitObjectKind::Commit => "commit",
            GitObjectKind::Tag => "tag",
        }
    }

    pub fn parse(raw: &str) -> Result<Self, GitError> {
        match raw.trim() {
            "blob" => Ok(GitObjectKind::Blob),
            "tree" => Ok(GitObjectKind::Tree),
            "commit" => Ok(GitObjectKind::Commit),
            "tag" => Ok(GitObjectKind::Tag),
            other => Err(GitError::InvalidInput(format!(
                "unknown Git object type {other:?}"
            ))),
        }
    }
}

/// Raw Git object payload read from an object database.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitObject {
    pub kind: GitObjectKind,
    pub bytes: Vec<u8>,
}

/// Validates a Git reference name so flags, path traversals, or malformed refs cannot reach `git`.
pub fn validate_ref_name(name: &str) -> Result<(), GitError> {
    if name.is_empty()
        || name.starts_with('-')
        || name.starts_with('/')
        || name.ends_with('/')
        || name.ends_with('.')
        || name.ends_with(".lock")
        || name.contains("//")
        || name.contains("..")
        || name.contains("@{")
        || name.chars().any(|c| {
            c.is_control()
                || c.is_whitespace()
                || matches!(c, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
        })
    {
        return Err(GitError::InvalidRefName(name.to_owned()));
    }
    if name != "HEAD" && !name.starts_with("refs/") {
        return Err(GitError::InvalidRefName(name.to_owned()));
    }
    Ok(())
}

/// Validates an optional ref prefix for listing refs.
pub(crate) fn validate_ref_prefix(prefix: &str) -> Result<(), GitError> {
    if prefix.is_empty()
        || prefix.starts_with('-')
        || prefix.starts_with('/')
        || prefix.contains("..")
        || prefix.contains("//")
        || prefix.chars().any(|c| {
            c.is_control()
                || c.is_whitespace()
                || matches!(c, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
        })
    {
        return Err(GitError::InvalidRefName(prefix.to_owned()));
    }
    Ok(())
}

/// Storage abstraction over a bare Git repository.
#[async_trait]
pub trait GitStore: Send + Sync {
    async fn init_bare(&self) -> Result<(), GitError>;
    async fn list_refs(&self, prefix: Option<&str>) -> Result<BTreeMap<String, Oid>, GitError>;
    async fn resolve_ref(&self, ref_name: &str) -> Result<Option<Oid>, GitError>;
    async fn update_ref_cas(
        &self,
        ref_name: &str,
        new_oid: Option<&Oid>,
        expected_old_oid: Option<&Oid>,
    ) -> Result<(), GitError>;
    async fn read_object(&self, oid: &Oid) -> Result<GitObject, GitError>;
    async fn write_blob(&self, data: &[u8]) -> Result<Oid, GitError>;
    async fn object_exists(&self, oid: &Oid) -> Result<bool, GitError>;
    async fn merge_base(&self, a: &Oid, b: &Oid) -> Result<Option<Oid>, GitError>;
    async fn rev_list(&self, include: &[Oid], exclude: &[Oid]) -> Result<Vec<Oid>, GitError>;
}

/// Creates a `git` command with inherited repository environment variables cleared so outer hooks or worktrees never interfere.
pub(crate) fn clean_git_command() -> Command {
    let mut cmd = Command::new("git");
    for var in [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_INDEX_FILE",
        "GIT_OBJECT_DIRECTORY",
        "GIT_ALTERNATE_OBJECT_DIRECTORIES",
        "GIT_COMMON_DIR",
        "GIT_NAMESPACE",
    ] {
        cmd.env_remove(var);
    }
    cmd
}

pub(crate) async fn run_git_bytes(
    repo_dir: &Path,
    args: &[&str],
    stdin_bytes: Option<&[u8]>,
    extra_env: &[(&str, &Path)],
) -> Result<std::process::Output, GitError> {
    let mut cmd = clean_git_command();
    cmd.arg("-C").arg(repo_dir).args(args);
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    if stdin_bytes.is_some() {
        cmd.stdin(std::process::Stdio::piped());
    } else {
        cmd.stdin(std::process::Stdio::null());
    }
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let mut child = cmd.spawn()?;
    if let Some(input) = stdin_bytes
        && let Some(mut stdin) = child.stdin.take()
    {
        stdin.write_all(input).await?;
        stdin.shutdown().await?;
    }
    Ok(child.wait_with_output().await?)
}

/// Git CLI backed implementation of [`GitStore`] operating on a bare repository directory without shell interpolation.
#[derive(Debug, Clone)]
pub struct CliGitStore {
    repo_dir: PathBuf,
}

impl CliGitStore {
    #[must_use]
    pub fn new(repo_dir: impl Into<PathBuf>) -> Self {
        Self {
            repo_dir: repo_dir.into(),
        }
    }

    #[must_use]
    pub fn repo_dir(&self) -> &Path {
        &self.repo_dir
    }

    /// Initialises a bare repository at `repo_dir` and returns a store handle pointing to it.
    pub async fn init_bare_at(repo_dir: impl Into<PathBuf>) -> Result<Self, GitError> {
        let store = Self::new(repo_dir);
        store.init_bare().await?;
        Ok(store)
    }
}

#[async_trait]
impl GitStore for CliGitStore {
    async fn init_bare(&self) -> Result<(), GitError> {
        tokio::fs::create_dir_all(&self.repo_dir).await?;
        let mut cmd = clean_git_command();
        cmd.arg("init")
            .arg("--bare")
            .arg("--initial-branch=main")
            .arg(&self.repo_dir);
        let output = cmd.output().await?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: "git init --bare".to_owned(),
                status: output.status.code(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            });
        }
        Ok(())
    }

    async fn list_refs(&self, prefix: Option<&str>) -> Result<BTreeMap<String, Oid>, GitError> {
        let mut args = vec!["for-each-ref", "--format=%(objectname) %(refname)"];
        if let Some(p) = prefix {
            validate_ref_prefix(p)?;
            args.push(p);
        }
        let output = run_git_bytes(&self.repo_dir, &args, None, &[]).await?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: "git for-each-ref".to_owned(),
                status: output.status.code(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            });
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut refs = BTreeMap::new();
        for line in stdout.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            let Some((oid_str, ref_name)) = line.split_once(' ') else {
                return Err(GitError::InvalidInput(format!(
                    "unexpected for-each-ref line {line:?}"
                )));
            };
            refs.insert(ref_name.to_owned(), Oid::parse(oid_str)?);
        }
        Ok(refs)
    }

    async fn resolve_ref(&self, ref_name: &str) -> Result<Option<Oid>, GitError> {
        validate_ref_name(ref_name)?;
        let output = run_git_bytes(
            &self.repo_dir,
            &["rev-parse", "--verify", "--quiet", ref_name],
            None,
            &[],
        )
        .await?;
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            Ok(Some(Oid::parse(text.trim())?))
        } else if output.status.code() == Some(1) && output.stderr.is_empty() {
            Ok(None)
        } else {
            Err(GitError::CommandFailed {
                command: "git rev-parse".to_owned(),
                status: output.status.code(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            })
        }
    }

    async fn update_ref_cas(
        &self,
        ref_name: &str,
        new_oid: Option<&Oid>,
        expected_old_oid: Option<&Oid>,
    ) -> Result<(), GitError> {
        validate_ref_name(ref_name)?;
        let mut cmd_args: Vec<String> = vec!["update-ref".to_owned()];
        match (new_oid, expected_old_oid) {
            (Some(new), Some(old)) => {
                cmd_args.push(ref_name.to_owned());
                cmd_args.push(new.as_str().to_owned());
                cmd_args.push(old.as_str().to_owned());
            }
            (Some(new), None) => {
                cmd_args.push(ref_name.to_owned());
                cmd_args.push(new.as_str().to_owned());
                cmd_args.push(String::new());
            }
            (None, Some(old)) => {
                cmd_args.push("-d".to_owned());
                cmd_args.push(ref_name.to_owned());
                cmd_args.push(old.as_str().to_owned());
            }
            (None, None) => {
                cmd_args.push("-d".to_owned());
                cmd_args.push(ref_name.to_owned());
            }
        }
        let arg_refs: Vec<&str> = cmd_args.iter().map(String::as_str).collect();
        let output = run_git_bytes(&self.repo_dir, &arg_refs, None, &[]).await?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
            if stderr.contains("cannot lock ref")
                || stderr.contains("is at")
                || stderr.contains("expected")
                || stderr.contains("already exists")
                || stderr.contains("unable to resolve reference")
            {
                return Err(GitError::CasConflict {
                    ref_name: ref_name.to_owned(),
                    details: stderr.trim().to_owned(),
                });
            }
            return Err(GitError::CommandFailed {
                command: "git update-ref".to_owned(),
                status: output.status.code(),
                stderr,
            });
        }
        Ok(())
    }

    async fn read_object(&self, oid: &Oid) -> Result<GitObject, GitError> {
        let type_out =
            run_git_bytes(&self.repo_dir, &["cat-file", "-t", oid.as_str()], None, &[]).await?;
        if !type_out.status.success() {
            let stderr = String::from_utf8_lossy(&type_out.stderr).into_owned();
            if stderr.contains("Not a valid object name") || stderr.contains("bad file") {
                return Err(GitError::ObjectNotFound(oid.to_string()));
            }
            return Err(GitError::CommandFailed {
                command: "git cat-file -t".to_owned(),
                status: type_out.status.code(),
                stderr,
            });
        }
        let kind = GitObjectKind::parse(&String::from_utf8_lossy(&type_out.stdout))?;
        let data_out = run_git_bytes(
            &self.repo_dir,
            &["cat-file", kind.as_str(), oid.as_str()],
            None,
            &[],
        )
        .await?;
        if !data_out.status.success() {
            return Err(GitError::CommandFailed {
                command: "git cat-file".to_owned(),
                status: data_out.status.code(),
                stderr: String::from_utf8_lossy(&data_out.stderr).into_owned(),
            });
        }
        Ok(GitObject {
            kind,
            bytes: data_out.stdout,
        })
    }

    async fn write_blob(&self, data: &[u8]) -> Result<Oid, GitError> {
        let output = run_git_bytes(
            &self.repo_dir,
            &["hash-object", "-w", "--stdin"],
            Some(data),
            &[],
        )
        .await?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: "git hash-object".to_owned(),
                status: output.status.code(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            });
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        Oid::parse(stdout.trim())
    }

    async fn object_exists(&self, oid: &Oid) -> Result<bool, GitError> {
        let target = format!("{}^{{object}}", oid.as_str());
        let output = run_git_bytes(&self.repo_dir, &["cat-file", "-e", &target], None, &[]).await?;
        if output.status.success() {
            Ok(true)
        } else if output.status.code() == Some(1) {
            Ok(false)
        } else {
            // `git cat-file -e` exits 128 on missing loose/packed object in some Git versions.
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("Not a valid object name") || stderr.is_empty() {
                Ok(false)
            } else {
                Err(GitError::CommandFailed {
                    command: "git cat-file -e".to_owned(),
                    status: output.status.code(),
                    stderr: stderr.into_owned(),
                })
            }
        }
    }

    async fn merge_base(&self, a: &Oid, b: &Oid) -> Result<Option<Oid>, GitError> {
        let output = run_git_bytes(
            &self.repo_dir,
            &["merge-base", a.as_str(), b.as_str()],
            None,
            &[],
        )
        .await?;
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            Ok(Some(Oid::parse(stdout.trim())?))
        } else if output.status.code() == Some(1) {
            Ok(None)
        } else {
            Err(GitError::CommandFailed {
                command: "git merge-base".to_owned(),
                status: output.status.code(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            })
        }
    }

    async fn rev_list(&self, include: &[Oid], exclude: &[Oid]) -> Result<Vec<Oid>, GitError> {
        if include.is_empty() {
            return Ok(Vec::new());
        }
        let mut args: Vec<String> = vec!["rev-list".to_owned()];
        for oid in include {
            args.push(oid.as_str().to_owned());
        }
        for oid in exclude {
            args.push(format!("^{}", oid.as_str()));
        }
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let output = run_git_bytes(&self.repo_dir, &arg_refs, None, &[]).await?;
        if !output.status.success() {
            return Err(GitError::CommandFailed {
                command: "git rev-list".to_owned(),
                status: output.status.code(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            });
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut out = Vec::new();
        for line in stdout.lines() {
            let trimmed = line.trim();
            if !trimmed.is_empty() {
                out.push(Oid::parse(trimmed)?);
            }
        }
        Ok(out)
    }
}

#[cfg(test)]
pub(crate) mod test_helpers {
    use super::*;

    pub async fn create_commit_in_bare(
        bare_dir: &Path,
        ref_name: &str,
        parents: &[&Oid],
        files: &[(&str, &[u8])],
        message: &str,
    ) -> Oid {
        let work = tempfile::tempdir().unwrap();
        let mut init = clean_git_command();
        init.arg("init")
            .arg("--initial-branch=main")
            .arg(work.path());
        assert!(init.output().await.unwrap().status.success());

        for (k, v) in [
            ("user.name", "Tester"),
            ("user.email", "tester@example.com"),
        ] {
            let out = run_git_bytes(work.path(), &["config", k, v], None, &[])
                .await
                .unwrap();
            assert!(out.status.success());
        }

        for (rel_path, content) in files {
            let full = work.path().join(rel_path);
            if let Some(parent) = full.parent() {
                tokio::fs::create_dir_all(parent).await.unwrap();
            }
            tokio::fs::write(&full, content).await.unwrap();
        }
        let add = run_git_bytes(work.path(), &["add", "-A"], None, &[])
            .await
            .unwrap();
        assert!(add.status.success());

        let write_tree = run_git_bytes(work.path(), &["write-tree"], None, &[])
            .await
            .unwrap();
        assert!(write_tree.status.success());
        let tree_oid = Oid::parse(String::from_utf8_lossy(&write_tree.stdout).trim()).unwrap();

        // Pack the tree and all reachable blobs/subtrees into the bare repo.
        let pack = run_git_bytes(
            work.path(),
            &["pack-objects", "--revs", "--stdout", "-q"],
            Some(format!("{}\n", tree_oid.as_str()).as_bytes()),
            &[],
        )
        .await
        .unwrap();
        assert!(pack.status.success());
        let unpack = run_git_bytes(bare_dir, &["unpack-objects", "-q"], Some(&pack.stdout), &[])
            .await
            .unwrap();
        assert!(unpack.status.success());

        let mut args = vec!["commit-tree", tree_oid.as_str(), "-m", message];
        for p in parents {
            args.push("-p");
            args.push(p.as_str());
        }
        let mut commit_cmd = clean_git_command();
        commit_cmd
            .arg("-C")
            .arg(bare_dir)
            .args(&args)
            .env("GIT_AUTHOR_NAME", "Tester")
            .env("GIT_AUTHOR_EMAIL", "tester@example.com")
            .env("GIT_AUTHOR_DATE", "1700000000 +0000")
            .env("GIT_COMMITTER_NAME", "Tester")
            .env("GIT_COMMITTER_EMAIL", "tester@example.com")
            .env("GIT_COMMITTER_DATE", "1700000000 +0000");
        let commit_out = commit_cmd.output().await.unwrap();
        assert!(
            commit_out.status.success(),
            "commit-tree failed: {}",
            String::from_utf8_lossy(&commit_out.stderr)
        );
        let commit_oid = Oid::parse(String::from_utf8_lossy(&commit_out.stdout).trim()).unwrap();

        let store = CliGitStore::new(bare_dir);
        let existing = store.resolve_ref(ref_name).await.unwrap();
        store
            .update_ref_cas(ref_name, Some(&commit_oid), existing.as_ref())
            .await
            .unwrap();
        commit_oid
    }
}

#[cfg(test)]
mod tests {
    use super::test_helpers::create_commit_in_bare;
    use super::*;

    #[tokio::test]
    async fn cli_git_store_crud_cas_merge_base_and_rev_list() {
        let dir = tempfile::tempdir().unwrap();
        let store = CliGitStore::init_bare_at(dir.path()).await.unwrap();

        assert!(store.list_refs(None).await.unwrap().is_empty());
        assert_eq!(store.resolve_ref("refs/heads/main").await.unwrap(), None);

        let blob_oid = store.write_blob(b"hello gitiverse\n").await.unwrap();
        assert!(store.object_exists(&blob_oid).await.unwrap());
        let obj = store.read_object(&blob_oid).await.unwrap();
        assert_eq!(obj.kind, GitObjectKind::Blob);
        assert_eq!(obj.bytes, b"hello gitiverse\n");

        let fake_missing = Oid::parse(&"f".repeat(40)).unwrap();
        assert!(!store.object_exists(&fake_missing).await.unwrap());

        let c1 = create_commit_in_bare(
            dir.path(),
            "refs/heads/main",
            &[],
            &[("README.md", b"# Hello\n")],
            "initial",
        )
        .await;
        let c2 = create_commit_in_bare(
            dir.path(),
            "refs/heads/main",
            &[&c1],
            &[("README.md", b"# Hello v2\n")],
            "second",
        )
        .await;
        let c3 = create_commit_in_bare(
            dir.path(),
            "refs/heads/feature",
            &[&c1],
            &[("README.md", b"# Hello\n"), ("feat.txt", b"feature\n")],
            "feature",
        )
        .await;

        assert_eq!(store.merge_base(&c2, &c3).await.unwrap(), Some(c1.clone()));
        let revs = store
            .rev_list(std::slice::from_ref(&c2), std::slice::from_ref(&c1))
            .await
            .unwrap();
        assert_eq!(revs, vec![c2.clone()]);

        // CAS conflict when expected_old_oid is stale.
        let err = store
            .update_ref_cas("refs/heads/main", Some(&c3), Some(&c1))
            .await
            .unwrap_err();
        assert!(matches!(err, GitError::CasConflict { .. }), "got {err:?}");

        // CAS create fails when ref already exists.
        let err_create = store
            .update_ref_cas("refs/heads/main", Some(&c3), None)
            .await
            .unwrap_err();
        assert!(
            matches!(err_create, GitError::CasConflict { .. }),
            "got {err_create:?}"
        );

        // CAS update and delete succeed with accurate old OID.
        store
            .update_ref_cas("refs/heads/feature", None, Some(&c3))
            .await
            .unwrap();
        assert_eq!(store.resolve_ref("refs/heads/feature").await.unwrap(), None);
    }

    #[test]
    fn ref_name_validation_blocks_injection_and_traversal() {
        assert!(validate_ref_name("refs/heads/main").is_ok());
        assert!(validate_ref_name("refs/cobs/issue/abc123").is_ok());
        assert!(validate_ref_name("-bad").is_err());
        assert!(validate_ref_name("refs/heads/a..b").is_err());
        assert!(validate_ref_name("refs/heads/main.lock").is_err());
        assert!(validate_ref_name("foo").is_err());
    }
}