grit-lib 0.5.29

Core library for the grit Git implementation
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
//! Upload-pack configuration: capabilities, want validation, filters.

use std::collections::{HashSet, VecDeque};

use super::{Result, ServeError};
use crate::config::ConfigSet;
use crate::objects::{ObjectId, ObjectKind};
use crate::repo::Repository;
use crate::rev_list::ObjectFilter;
use crate::upload_filter::{validate_upload_filter_request, UploadFilterError};

/// Policy derived from repository config for one upload-pack session.
pub(crate) struct UploadPackPolicy {
    pub allow_filter: bool,
    pub allow_tip_sha1_in_want: bool,
    pub allow_reachable_sha1_in_want: bool,
    /// `uploadpack.allowAnySHA1InWant`: any object present in the repository may
    /// be wanted, reachable or not. A large-object promisor that holds blobs no
    /// ref points at needs this to answer lazy fetches.
    pub allow_any_sha1_in_want: bool,
    pub ref_in_want: bool,
    pub allow_sideband_all: bool,
    /// `transfer.advertiseObjectInfo`: advertise and serve the v2 `object-info`
    /// command. Off by default, as in Git.
    pub advertise_object_info: bool,
    /// `uploadpack.lazyFetch` (grit only): before answering a client that accepted
    /// no promisor remote, fetch the promised objects the repository lacks from its
    /// own promisor remotes. Off by default, like Git's upload-pack.
    pub lazy_fetch: bool,
}

impl UploadPackPolicy {
    pub fn from_config(config: &ConfigSet) -> Self {
        let flag = |key: &str| config.get_bool(key).and_then(|v| v.ok()).unwrap_or(false);
        Self {
            allow_filter: flag("uploadpack.allowfilter"),
            allow_tip_sha1_in_want: flag("uploadpack.allowtipsha1inwant"),
            allow_reachable_sha1_in_want: flag("uploadpack.allowreachablesha1inwant"),
            allow_any_sha1_in_want: flag("uploadpack.allowanysha1inwant"),
            ref_in_want: flag("uploadpack.allowrefinwant"),
            allow_sideband_all: flag("uploadpack.allowsidebandall"),
            advertise_object_info: flag("transfer.advertiseobjectinfo"),
            lazy_fetch: flag("uploadpack.lazyfetch"),
        }
    }

    pub fn v0_capability_tokens(&self) -> Vec<&'static str> {
        let mut caps = vec!["shallow", "deepen-since", "deepen-not", "deepen-relative"];
        if self.allow_filter {
            caps.push("filter");
        }
        // As in Git, allowing any object implies both narrower capabilities.
        if self.allow_tip_sha1_in_want || self.allow_any_sha1_in_want {
            caps.push("allow-tip-sha1-in-want");
        }
        if self.allow_reachable_sha1_in_want || self.allow_any_sha1_in_want {
            caps.push("allow-reachable-sha1-in-want");
        }
        caps
    }

    /// Features for the v2 `fetch=` capability line.
    ///
    /// Only v2 features belong here. Request arguments every v2 server accepts
    /// (`thin-pack`, `ofs-delta`, `deepen-not`, ...) are not advertised.
    pub fn v2_fetch_features(&self) -> Vec<&'static str> {
        let mut f = vec!["shallow", "wait-for-done"];
        if self.allow_filter {
            f.push("filter");
        }
        if self.ref_in_want {
            f.push("ref-in-want");
        }
        if self.allow_sideband_all {
            f.push("sideband-all");
        }
        f
    }

    pub fn parse_filter(&self, config: &ConfigSet, spec: &str) -> Result<ObjectFilter> {
        if !self.allow_filter {
            return Err(ServeError::Protocol(
                "filter not supported (uploadpack.allowFilter is false)".into(),
            ));
        }
        validate_upload_filter_request(config, spec).map_err(ServeError::UploadFilter)?;
        ObjectFilter::parse(spec)
            .map_err(|e| ServeError::UploadFilter(UploadFilterError::InvalidFilterSpec(e)))
    }
}

/// Resolve `want-ref` names to OIDs and record them for the `wanted-refs` section.
pub(crate) fn resolve_want_ref(
    repo: &Repository,
    hidden: &[String],
    name: &str,
) -> Result<ObjectId> {
    if matches!(name, "HEAD" | "refs/HEAD") {
        let head = super::head_info(repo);
        return head
            .oid
            .ok_or_else(|| ServeError::Protocol("unknown ref HEAD".into()));
    }
    let full = if name.starts_with("refs/") {
        name.to_owned()
    } else {
        format!("refs/{name}")
    };
    if crate::hide_refs::ref_is_hidden(name, &full, hidden) {
        return Err(ServeError::Protocol(format!("unknown ref {name}")));
    }
    crate::refs::resolve_ref_in(repo, &full)
        .or_else(|_| crate::refs::resolve_ref_in(repo, name))
        .map_err(|_| ServeError::Protocol(format!("unknown ref {name}")))
}

/// Validate `want` OIDs for a filtered fetch (object must exist in the ODB).
pub(crate) fn validate_wants_filtered(repo: &Repository, wants: &[ObjectId]) -> Result<()> {
    for w in wants {
        if !repo.odb().contains(w)? {
            return Err(ServeError::NotOurRef(*w));
        }
    }
    Ok(())
}

/// Validate `want` OIDs against advertisement, config rules, and session mode.
///
/// Stateful sessions only accept wants that appeared in the ref advertisement
/// (plus `HEAD`). Stateless RPC (smart HTTP POST) matches Git: objects reachable
/// from current ref tips are allowed without extra config, but wants that are
/// already advertised ref tips skip reachability work.
pub(crate) fn validate_wants(
    repo: &Repository,
    advertised_tips: &HashSet<ObjectId>,
    head: Option<ObjectId>,
    wants: &[ObjectId],
    policy: &UploadPackPolicy,
    stateless_rpc: bool,
) -> Result<()> {
    if policy.allow_any_sha1_in_want {
        return validate_wants_filtered(repo, wants);
    }
    if policy.allow_reachable_sha1_in_want {
        let reachable = reachable_from_repository_tips(repo)?;
        for w in wants {
            if !reachable.contains(w) {
                return Err(ServeError::NotOurRef(*w));
            }
        }
        return Ok(());
    }

    let advertised = advertised_object_ids(advertised_tips, head);
    let extra: Vec<ObjectId> = wants
        .iter()
        .copied()
        .filter(|w| !advertised.contains(w))
        .collect();
    if extra.is_empty() {
        return Ok(());
    }

    if stateless_rpc {
        validate_stateless_extra_wants(repo, &extra)?;
        return Ok(());
    }

    if policy.allow_tip_sha1_in_want {
        let tips = repository_tip_commits(repo)?;
        for w in &extra {
            if !tips.contains(w) {
                return Err(ServeError::NotOurRef(*w));
            }
        }
        return Ok(());
    }

    Err(ServeError::NotOurRef(extra[0]))
}

fn advertised_object_ids(tips: &HashSet<ObjectId>, head: Option<ObjectId>) -> HashSet<ObjectId> {
    let mut allowed = tips.clone();
    if let Some(h) = head {
        allowed.insert(h);
    }
    allowed
}

/// Extra wants in stateless RPC: reachable from ref tips (Git smart HTTP race case).
fn validate_stateless_extra_wants(repo: &Repository, wants: &[ObjectId]) -> Result<()> {
    let tips = repository_tip_commits(repo)?;
    let ref_objects = repository_ref_object_ids(repo)?;
    for w in wants {
        if ref_objects.contains(w) {
            continue;
        }
        if !object_reachable_from_tip_commits(repo, *w, &tips)? {
            return Err(ServeError::NotOurRef(*w));
        }
    }
    Ok(())
}

/// Direct ref targets (unpeeled), including annotated tag objects on refs.
fn repository_ref_object_ids(repo: &Repository) -> Result<HashSet<ObjectId>> {
    let mut ids = HashSet::new();
    for (_, oid) in crate::refs::list_refs_in(repo, "refs/")? {
        ids.insert(oid);
    }
    if let Ok(head) = crate::refs::resolve_ref_in(repo, "HEAD") {
        ids.insert(head);
    }
    Ok(ids)
}

/// Whether `want` is reachable from current tip commits (ancestor of some tip).
fn object_reachable_from_tip_commits(
    repo: &Repository,
    want: ObjectId,
    tips: &HashSet<ObjectId>,
) -> Result<bool> {
    if tips.contains(&want) {
        return Ok(true);
    }
    if !repo.odb().contains(&want)? {
        return Ok(false);
    }
    let Ok(obj) = repo.odb().read(&want) else {
        return Ok(false);
    };
    match obj.kind {
        ObjectKind::Commit => commit_is_ancestor_of_some_tip(repo, want, tips),
        ObjectKind::Tag => {
            let Ok(tag) = crate::objects::parse_tag(&obj.data) else {
                return Ok(false);
            };
            reachable_object_from_tips(repo, tag.object, tips)
        }
        ObjectKind::Tree | ObjectKind::Blob => object_reachable_in_tip_closure(repo, want, tips),
    }
}

/// Reachability of a non-tag object from ref tips (tag targets and nested tags).
fn reachable_object_from_tips(
    repo: &Repository,
    object: ObjectId,
    tips: &HashSet<ObjectId>,
) -> Result<bool> {
    if tips.contains(&object) {
        return Ok(true);
    }
    if !repo.odb().contains(&object)? {
        return Ok(false);
    }
    let Ok(obj) = repo.odb().read(&object) else {
        return Ok(false);
    };
    match obj.kind {
        ObjectKind::Commit => commit_is_ancestor_of_some_tip(repo, object, tips),
        ObjectKind::Tree | ObjectKind::Blob => object_reachable_in_tip_closure(repo, object, tips),
        ObjectKind::Tag => {
            let Ok(tag) = crate::objects::parse_tag(&obj.data) else {
                return Ok(false);
            };
            reachable_object_from_tips(repo, tag.object, tips)
        }
    }
}

fn commit_is_ancestor_of_some_tip(
    repo: &Repository,
    want: ObjectId,
    tips: &HashSet<ObjectId>,
) -> Result<bool> {
    for tip in tips {
        if want == *tip || crate::merge_base::is_ancestor(repo, want, *tip)? {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Tree/blob wants: walk from tips until `target` appears (early exit).
fn object_reachable_in_tip_closure(
    repo: &Repository,
    target: ObjectId,
    tips: &HashSet<ObjectId>,
) -> Result<bool> {
    let mut seen = HashSet::new();
    let mut queue: VecDeque<ObjectId> = tips.iter().copied().collect();
    while let Some(oid) = queue.pop_front() {
        if oid == target {
            return Ok(true);
        }
        if !seen.insert(oid) {
            continue;
        }
        let Ok(obj) = repo.odb().read(&oid) else {
            continue;
        };
        match obj.kind {
            ObjectKind::Commit => {
                if let Ok(c) = crate::objects::parse_commit(&obj.data) {
                    queue.extend(c.parents);
                    queue.push_back(c.tree);
                }
            }
            ObjectKind::Tree => {
                if let Ok(entries) = crate::objects::parse_tree(&obj.data) {
                    for entry in entries {
                        queue.push_back(entry.oid);
                    }
                }
            }
            ObjectKind::Tag => {
                if let Ok(tag) = crate::objects::parse_tag(&obj.data) {
                    queue.push_back(tag.object);
                }
            }
            ObjectKind::Blob => {}
        }
    }
    Ok(false)
}

/// Peeled commit tips for every ref in the repository (including hidden refs).
fn repository_tip_commits(repo: &Repository) -> Result<HashSet<ObjectId>> {
    let mut tips = HashSet::new();
    for (_, oid) in crate::refs::list_refs_in(repo, "refs/")? {
        if let Ok(p) = repo.odb().peel_tags(oid).map(|(p, _)| p) {
            tips.insert(p);
        }
    }
    if let Ok(head) = crate::refs::resolve_ref_in(repo, "HEAD") {
        if let Ok(p) = repo.odb().peel_tags(head).map(|(p, _)| p) {
            tips.insert(p);
        }
    }
    Ok(tips)
}

fn reachable_from_repository_tips(repo: &Repository) -> Result<HashSet<ObjectId>> {
    let tips = repository_tip_commits(repo)?;
    let mut seen = HashSet::new();
    let mut q: VecDeque<ObjectId> = tips.iter().copied().collect();
    while let Some(oid) = q.pop_front() {
        if !seen.insert(oid) {
            continue;
        }
        let Ok(obj) = repo.odb().read(&oid) else {
            continue;
        };
        match obj.kind {
            ObjectKind::Commit => {
                if let Ok(c) = crate::objects::parse_commit(&obj.data) {
                    q.extend(c.parents);
                    q.push_back(c.tree);
                }
            }
            ObjectKind::Tree => {
                if let Ok(entries) = crate::objects::parse_tree(&obj.data) {
                    for entry in entries {
                        q.push_back(entry.oid);
                    }
                }
            }
            ObjectKind::Tag => {
                if let Ok(tag) = crate::objects::parse_tag(&obj.data) {
                    q.push_back(tag.object);
                }
            }
            ObjectKind::Blob => {}
        }
    }
    Ok(seen)
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::config::environment::RepositoryOptions;
    use crate::objects::{ObjectId, ObjectKind};
    use crate::refs::store::{
        Expected, MemoryRefStore, RawRef, RefStore, RefTransaction, RefUpdate,
    };
    use crate::repo::{InitOptions, Repository, RepositoryBuilder};

    use super::{repository_ref_object_ids, resolve_want_ref};

    fn memory_serve_repo() -> (tempfile::TempDir, Repository, Arc<MemoryRefStore>, ObjectId) {
        let dir = tempfile::tempdir().expect("tempdir");
        Repository::init(
            dir.path(),
            &InitOptions::new()
                .with_bare(true)
                .with_initial_branch("master"),
        )
        .expect("init");
        let store = Arc::new(MemoryRefStore::new());
        let repo = RepositoryBuilder::new(RepositoryOptions::empty())
            .ref_store(store.clone())
            .initial_branch("master")
            .open(dir.path(), None)
            .expect("open");
        let tree = repo.odb().write(ObjectKind::Tree, b"").expect("tree");
        let commit = repo
            .odb()
            .write(
                ObjectKind::Commit,
                format!(
                    "tree {tree}\nauthor T <t@e.com> 1 +0000\ncommitter T <t@e.com> 1 +0000\n\ninit\n"
                )
                .as_bytes(),
            )
            .expect("commit");
        store
            .prepare(
                RefTransaction::new()
                    .update(RefUpdate {
                        name: "refs/heads/master".into(),
                        new_value: Some(RawRef::Direct(commit)),
                        expected: Expected::Missing,
                        reflog: None,
                        flags: Default::default(),
                    })
                    .expect("txn"),
            )
            .expect("prepare")
            .commit()
            .expect("commit");
        (dir, repo, store, commit)
    }

    #[test]
    fn resolve_want_ref_head_uses_injected_store() {
        let (_dir, repo, _store, commit) = memory_serve_repo();
        let oid = resolve_want_ref(&repo, &[], "HEAD").expect("HEAD");
        assert_eq!(oid, commit);
    }

    #[test]
    fn resolve_want_ref_memory_only_branch() {
        let (_dir, repo, store, commit) = memory_serve_repo();
        store
            .prepare(
                RefTransaction::new()
                    .update(RefUpdate {
                        name: "refs/heads/only-memory".into(),
                        new_value: Some(RawRef::Direct(commit)),
                        expected: Expected::Missing,
                        reflog: None,
                        flags: Default::default(),
                    })
                    .expect("txn"),
            )
            .expect("prepare")
            .commit()
            .expect("commit");
        let oid = resolve_want_ref(&repo, &[], "heads/only-memory").expect("ref");
        assert_eq!(oid, commit);
    }

    #[test]
    fn repository_ref_object_ids_includes_injected_head() {
        let (_dir, repo, _store, commit) = memory_serve_repo();
        let ids = repository_ref_object_ids(&repo).expect("ids");
        assert!(ids.contains(&commit));
    }
}