amiss-git 0.1.0

Read-only Git object store behind a no-follow handle boundary, for Amiss
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use amiss_git::{Error, GitLimits, GitResources, ObjectKind, Repository, parse_commit, parse_tree};
use amiss_wire::controls::ResourceName;
use amiss_wire::model::{ObjectFormat, Oid};
use tempfile::TempDir;

#[expect(clippy::expect_used, reason = "test fixture helper")]
fn git(dir: &Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .args(args)
        .current_dir(dir)
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", dir.join("absent-global-config"))
        .env("GIT_AUTHOR_NAME", "t")
        .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
        .env("GIT_AUTHOR_DATE", "2026-01-01T00:00:00Z")
        .env("GIT_COMMITTER_NAME", "t")
        .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
        .env("GIT_COMMITTER_DATE", "2026-01-01T00:00:00Z")
        .output()
        .expect("run git");
    assert!(
        output.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).expect("git output utf-8")
}

fn file_v(version: usize) -> String {
    (0..200_usize)
        .map(|line| {
            if line == 100 {
                format!("changed line for version {version}\n")
            } else {
                format!("stable line {line} with shared content\n")
            }
        })
        .collect()
}

#[expect(clippy::unwrap_used, reason = "test fixture helper")]
fn packed_repo(config: &[&str]) -> (TempDir, String, String) {
    let dir = TempDir::new().unwrap();
    git(dir.path(), &["init", "-q"]);
    fs::write(dir.path().join("doc.md"), file_v(1)).unwrap();
    git(dir.path(), &["add", "."]);
    git(dir.path(), &["commit", "-qm", "one"]);
    let blob_v1 = git(dir.path(), &["rev-parse", "HEAD:doc.md"])
        .trim()
        .to_owned();
    fs::write(dir.path().join("doc.md"), file_v(2)).unwrap();
    git(dir.path(), &["add", "."]);
    git(dir.path(), &["commit", "-qm", "two"]);
    let blob_v2 = git(dir.path(), &["rev-parse", "HEAD:doc.md"])
        .trim()
        .to_owned();
    let mut repack: Vec<&str> = config.to_vec();
    repack.extend_from_slice(&["repack", "-adfq", "--window=10", "--depth=16"]);
    git(dir.path(), &repack);
    (dir, blob_v1, blob_v2)
}

#[expect(clippy::unwrap_used, reason = "test fixture helper")]
fn pack_paths(dir: &Path) -> Vec<PathBuf> {
    let mut out: Vec<PathBuf> = fs::read_dir(dir.join(".git/objects/pack"))
        .unwrap()
        .map(|entry| entry.unwrap().path())
        .collect();
    out.sort();
    out
}

#[expect(clippy::unwrap_used, reason = "test fixture helper")]
fn deltified_oid(dir: &Path) -> Option<String> {
    let idx = pack_paths(dir)
        .into_iter()
        .find(|path| path.extension().is_some_and(|e| e == "idx"))?;
    let listing = git(dir, &["verify-pack", "-v", idx.to_str().unwrap()]);
    for line in listing.lines() {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() >= 7 && matches!(fields.get(1), Some(&"blob")) {
            return fields.first().map(|oid| (*oid).to_owned());
        }
    }
    None
}

fn read_blob(repo: &Repository, hex: &str) -> Result<Vec<u8>, Error> {
    let oid = Oid::new(ObjectFormat::Sha1, hex.to_owned()).ok_or(Error::ObjectUnreadable)?;
    let mut res = GitResources::new(GitLimits::CONTRACT);
    repo.read_expected(&mut res, &oid, ObjectKind::Blob)
        .map(|object| object.body)
}

#[test]
fn reads_packed_objects_differentially() {
    let (dir, blob_v1, blob_v2) = packed_repo(&[]);
    assert!(
        deltified_oid(dir.path()).is_some(),
        "fixture must contain at least one delta"
    );
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    assert_eq!(read_blob(&repo, &blob_v1).unwrap(), file_v(1).into_bytes());
    assert_eq!(read_blob(&repo, &blob_v2).unwrap(), file_v(2).into_bytes());

    let head = git(dir.path(), &["rev-parse", "HEAD"]).trim().to_owned();
    let tree = git(dir.path(), &["rev-parse", "HEAD^{tree}"])
        .trim()
        .to_owned();
    let mut res = GitResources::new(GitLimits::CONTRACT);
    let head_oid = Oid::new(ObjectFormat::Sha1, head).unwrap();
    let commit_obj = repo
        .read_expected(&mut res, &head_oid, ObjectKind::Commit)
        .unwrap();
    let commit = parse_commit(ObjectFormat::Sha1, &commit_obj.body).unwrap();
    assert_eq!(commit.tree.as_str(), tree);
    assert_eq!(commit.parents.len(), 1);
    let tree_obj = repo
        .read_expected(&mut res, &commit.tree, ObjectKind::Tree)
        .unwrap();
    let entries = parse_tree(ObjectFormat::Sha1, &tree_obj.body).unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries.first().unwrap().name, b"doc.md");

    let absent = Oid::new(ObjectFormat::Sha1, "c".repeat(40)).unwrap();
    assert_eq!(
        repo.read_object(&mut res, &absent).unwrap_err(),
        Error::ObjectMissing
    );
}

#[test]
fn reads_ref_delta_packs() {
    let (dir, blob_v1, blob_v2) = packed_repo(&["-c", "pack.useDeltaBaseOffset=false"]);
    assert!(
        deltified_oid(dir.path()).is_some(),
        "fixture must contain a delta"
    );
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    assert_eq!(read_blob(&repo, &blob_v1).unwrap(), file_v(1).into_bytes());
    assert_eq!(read_blob(&repo, &blob_v2).unwrap(), file_v(2).into_bytes());
}

#[test]
fn reads_index_v1_packs() {
    let (dir, blob_v1, _) = packed_repo(&["-c", "pack.indexVersion=1"]);
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    assert_eq!(read_blob(&repo, &blob_v1).unwrap(), file_v(1).into_bytes());
}

#[test]
fn reads_sha256_packs() {
    let dir = TempDir::new().unwrap();
    git(dir.path(), &["init", "-q", "--object-format=sha256"]);
    fs::write(dir.path().join("doc.md"), b"sha256 body\n").unwrap();
    git(dir.path(), &["add", "."]);
    git(dir.path(), &["commit", "-qm", "one"]);
    let blob = git(dir.path(), &["rev-parse", "HEAD:doc.md"])
        .trim()
        .to_owned();
    git(dir.path(), &["repack", "-adq"]);
    let repo = Repository::open(dir.path(), ObjectFormat::Sha256).unwrap();
    let oid = Oid::new(ObjectFormat::Sha256, blob).unwrap();
    let mut res = GitResources::new(GitLimits::CONTRACT);
    let object = repo
        .read_expected(&mut res, &oid, ObjectKind::Blob)
        .unwrap();
    assert_eq!(object.body, b"sha256 body\n");
}

#[test]
fn rejects_orphans_and_corruption() {
    let (dir, blob_v1, _) = packed_repo(&[]);
    let idx = pack_paths(dir.path())
        .into_iter()
        .find(|path| path.extension().is_some_and(|e| e == "idx"))
        .unwrap();
    let pack = idx.with_extension("pack");

    let saved = fs::read(&pack).unwrap();
    fs::remove_file(&pack).unwrap();
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    assert_eq!(
        read_blob(&repo, &blob_v1).unwrap_err(),
        Error::ObjectUnreadable,
        "orphan idx without its pack is fatal"
    );
    fs::write(&pack, &saved).unwrap();

    let mut corrupt = fs::read(&idx).unwrap();
    let middle = corrupt.len() / 2;
    if let Some(byte) = corrupt.get_mut(middle) {
        *byte = byte.wrapping_add(1);
    }
    fs::remove_file(&idx).unwrap();
    fs::write(&idx, &corrupt).unwrap();
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    assert_eq!(
        read_blob(&repo, &blob_v1).unwrap_err(),
        Error::ObjectUnreadable,
        "index checksum mismatch is fatal"
    );
}

#[test]
fn enforces_pack_resource_caps() {
    let (dir, blob_v1, _) = packed_repo(&[]);

    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    let oid = Oid::new(ObjectFormat::Sha1, blob_v1.clone()).unwrap();
    let mut res = GitResources::new(GitLimits {
        pack_directory_entries: 1,
        ..GitLimits::CONTRACT
    });
    let Err(Error::ResourceLimit { resource, .. }) = repo.read_object(&mut res, &oid) else {
        panic!("expected the directory-entry cap");
    };
    assert_eq!(resource, ResourceName::GitPackDirectoryEntries);

    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    let mut res = GitResources::new(GitLimits {
        pack_files: 0,
        ..GitLimits::CONTRACT
    });
    let Err(Error::ResourceLimit { resource, .. }) = repo.read_object(&mut res, &oid) else {
        panic!("expected the pack-files cap");
    };
    assert_eq!(resource, ResourceName::GitPackFiles);

    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    let mut res = GitResources::new(GitLimits {
        pack_index_bytes: 8,
        ..GitLimits::CONTRACT
    });
    let Err(Error::ResourceLimit { resource, .. }) = repo.read_object(&mut res, &oid) else {
        panic!("expected the index-bytes cap");
    };
    assert_eq!(resource, ResourceName::GitPackIndexBytes);

    let deltified = deltified_oid(dir.path()).unwrap();
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    let delta_oid = Oid::new(ObjectFormat::Sha1, deltified).unwrap();
    let mut res = GitResources::new(GitLimits {
        delta_depth: 1,
        ..GitLimits::CONTRACT
    });
    let Err(Error::ResourceLimit {
        resource,
        configured_limit,
        observed_lower_bound,
    }) = repo.read_object(&mut res, &delta_oid)
    else {
        panic!("expected the delta-depth cap");
    };
    assert_eq!(resource, ResourceName::GitDeltaDepth);
    assert_eq!(configured_limit, 1);
    assert_eq!(observed_lower_bound, 2);
}

#[test]
fn duplicate_objects_across_packs_resolve() {
    let (dir, blob_v1, _) = packed_repo(&[]);
    fs::write(dir.path().join("extra.md"), b"more\n").unwrap();
    git(dir.path(), &["add", "."]);
    git(dir.path(), &["commit", "-qm", "three"]);
    git(dir.path(), &["repack", "-aq"]);
    assert!(pack_paths(dir.path()).len() >= 4, "two pack pairs expected");
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    assert_eq!(read_blob(&repo, &blob_v1).unwrap(), file_v(1).into_bytes());
}

/// The concurrent-repack fixture the spec's E0 set requires.
///
/// A repack moves an object out of the loose store into a pack that did not
/// exist when the scanner enumerated the pack directory, and prunes the loose
/// copy. A reader that enumerates once and never again sees a present object
/// as missing, which is a false failure on a healthy repository. This is not
/// hypothetical: git runs `gc --auto` from an ordinary commit, detached, and
/// it repacked this repository underneath a live scan.
///
/// The spec tolerates the loss ("a repack race may yield missing/unreadable
/// but never a different valid object's bytes"). Git re-reads its pack
/// directory on a miss rather than taking the loss, and so does this, which is
/// what the read below proves. The safety half of that sentence is proven with
/// it: what the re-read finds is content-addressed before it is returned, so a
/// race can cost a directory read and can never substitute another object.
#[test]
fn a_repack_under_a_live_reader_never_loses_a_present_object() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    git(root, &["init", "-q"]);
    fs::write(root.join("first.txt"), "first\n").unwrap();
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "first"]);
    git(root, &["repack", "-adq"]);

    let repo = Repository::open(root, ObjectFormat::Sha1).unwrap();
    let mut resources = GitResources::new(GitLimits::CONTRACT);
    let first = Oid::new(
        ObjectFormat::Sha1,
        git(root, &["rev-parse", "HEAD"]).trim().to_owned(),
    )
    .unwrap();
    repo.read_expected(&mut resources, &first, ObjectKind::Commit)
        .expect("the packed commit reads, which enumerates the pack directory");

    fs::write(root.join("second.txt"), "second\n").unwrap();
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "second"]);
    let second = Oid::new(
        ObjectFormat::Sha1,
        git(root, &["rev-parse", "HEAD"]).trim().to_owned(),
    )
    .unwrap();
    git(root, &["repack", "-adq"]);

    let object = repo
        .read_expected(&mut resources, &second, ObjectKind::Commit)
        .expect("an object repacked out from under the reader is still found");
    let commit = parse_commit(ObjectFormat::Sha1, &object.body).expect("the commit grammar holds");
    assert_eq!(
        commit.parents.first().map(Oid::as_str),
        Some(first.as_str()),
        "the object found after the repack is the one that was asked for"
    );
    assert!(
        repo.has_object(&mut resources, &second).unwrap(),
        "presence agrees with the read"
    );
}

/// Builds a repository with two separate pack files by packing twice, once per
/// commit, and returns it with the byte size one index occupies.
#[expect(clippy::unwrap_used, reason = "test fixture helper")]
fn two_pack_repo() -> (TempDir, u64) {
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    git(root, &["init", "-q"]);
    fs::write(root.join("a.md"), "content a ".repeat(300)).unwrap();
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "a"]);
    git(root, &["repack", "-dq"]);
    fs::write(root.join("b.md"), "content b ".repeat(300)).unwrap();
    git(root, &["add", "."]);
    git(root, &["commit", "-qm", "b"]);
    git(root, &["repack", "-dq"]);
    let indices: Vec<u64> = pack_paths(root)
        .into_iter()
        .filter(|path| path.extension().is_some_and(|ext| ext == "idx"))
        .map(|path| fs::metadata(&path).unwrap().len())
        .collect();
    assert_eq!(indices.len(), 2, "the repository has two packs");
    let one_index = indices.into_iter().next().unwrap();
    (dir, one_index)
}

/// One pack index is allowed to be large. The sum of them is not, because a
/// repository can carry many packs and index bytes are the memory the scanner
/// spends before it reads a single object. The per-index cap and the aggregate
/// cap are different limits, and this pins the aggregate: two indices that each
/// clear the per-index ceiling still cross the running total, and the crossing
/// names the aggregate resource rather than the per-index one.
#[test]
fn the_running_total_of_pack_index_bytes_is_bounded_across_packs() {
    let (dir, one_index) = two_pack_repo();
    let repo = Repository::open(dir.path(), ObjectFormat::Sha1).unwrap();
    let mut resources = GitResources::new(GitLimits {
        pack_index_bytes: one_index.saturating_mul(2),
        aggregate_pack_index_bytes: one_index.saturating_add(one_index / 2),
        ..GitLimits::CONTRACT
    });

    let absent = Oid::new(ObjectFormat::Sha1, "d".repeat(40)).unwrap();
    let Err(Error::ResourceLimit {
        resource,
        configured_limit,
        observed_lower_bound,
    }) = repo.read_object(&mut resources, &absent)
    else {
        panic!("two indices past the aggregate ceiling must cross it");
    };
    assert_eq!(resource, ResourceName::AggregateGitPackIndexBytes);
    assert_eq!(configured_limit, one_index.saturating_add(one_index / 2));
    assert!(
        observed_lower_bound > configured_limit,
        "the crossing reports the running total that overran"
    );
}

/// The pack-directory entry cap counts what is on disk, not what survives
/// filtering. An attacker who floods `objects/pack` with files that are not
/// packs at all still makes the scanner enumerate every one of them, so the
/// bound has to be charged before the junk is discarded. A sibling test proves
/// junk names are ignored for lookup; this proves they are counted for the cap,
/// which is the difference between a bound that holds and one a directory of
/// noise walks straight through.
#[test]
fn junk_pack_directory_entries_are_counted_before_they_are_discarded() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    git(root, &["init", "-q"]);
    let pack_dir = root.join(".git/objects/pack");
    fs::create_dir_all(&pack_dir).unwrap();
    for name in ["noise-1.tmp", "noise-2.tmp", "noise-3.tmp", "not-a-pack"] {
        fs::write(pack_dir.join(name), b"junk").unwrap();
    }

    let repo = Repository::open(root, ObjectFormat::Sha1).unwrap();
    let mut resources = GitResources::new(GitLimits {
        pack_directory_entries: 2,
        ..GitLimits::CONTRACT
    });
    let absent = Oid::new(ObjectFormat::Sha1, "e".repeat(40)).unwrap();
    let Err(Error::ResourceLimit {
        resource,
        configured_limit,
        observed_lower_bound,
    }) = repo.read_object(&mut resources, &absent)
    else {
        panic!("four junk entries past a cap of two must cross it");
    };
    assert_eq!(resource, ResourceName::GitPackDirectoryEntries);
    assert_eq!(configured_limit, 2);
    assert!(
        observed_lower_bound > 2,
        "the junk was counted, not silently dropped before the tally"
    );
}