OXYGENHUB

Coverage / crates/oxy-core/src/repo/sync.rs 89.3%

1387 of 1553 lines run, 198 of 282 functions · run #250 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
}
34
35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub struct PullReport {
37
    /// The current bookmark's heads after the pull.
38
    pub heads: Vec<ChangeHash>,
39
    /// Whether the current bookmark changed.
40
    pub changed: bool,
41
    pub checked_out: bool,
42
    /// Other bookmarks the pull moved: each local bookmark tracks the
43
    /// remote's of the same name.
44
    pub others: Vec<String>,
45
}
46
47
impl Repo {
48
    // ------------------------------------------------------------ serving (spec §16)
49
501222×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
511222×
        self.oxy.join("attest").join(name_file(bookmark))
521222×
    }
53
54
    /// The latest reference attestation stored for a bookmark.
551148×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
561148×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
57195×
            Ok(h) => {
58195×
                let r = ObjectRef::from_hex(h.trim())
59195×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
60
                Ok(Some((
61195×
                    r,
62
                    SignedAttest {
63195×
                        attest: self.store.get_attest(&r)?,
64195×
                        sigs: self.store.signatures(&r)?,
65
                    },
66
                )))
67
            }
68953×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
690×
            Err(e) => Err(e.into()),
70
        }
711148×
    }
72
7374×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7474×
        fs::create_dir_all(self.oxy.join("attest"))?;
7574×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
7674×
    }
77
78941×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
79941×
        let view = self.view()?;
80941×
        let mut out = Vec::new();
81963×
        for (name, state) in &view.bookmarks {
82963×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
83963×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
84104×
                AttestBody::Ref { serial, .. } => Some(serial),
850×
                _ => None,
86104×
            });
87963×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
88963×
            out.push(RemoteRef {
89963×
                name: name.clone(),
90963×
                state: *state,
91963×
                heads: self.store.get_state(state)?.heads,
92963×
                attestation,
93963×
                last_serial,
94
            });
95
        }
96941×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
97941×
        let history = self
98941×
            .policy_history()?
99941×
            .into_iter()
100941×
            .filter(|sp| {
10166×
                policy
10266×
                    .as_ref()
10366×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10466×
            })
105941×
            .collect();
106
        Ok(RefsResponse {
107941×
            refs: out,
108941×
            policy,
109941×
            tags: self.tag_refs()?,
110941×
            history,
111941×
            default_bookmark: Some(self.config.bookmark.clone()),
112
        })
113941×
    }
114
115
    /// Every change reachable from `heads` that is in the store.
1161231×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1171231×
        let mut seen = BTreeSet::new();
1181231×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1194414×
        while let Some(h) = stack.pop() {
1203183×
            if seen.contains(&h) || !self.store.has(&h) {
121950×
                continue;
1222233×
            }
1232233×
            seen.insert(h);
1242233×
            stack.extend(self.store.get_change_meta(&h)?.deps);
125
        }
1261231×
        Ok(seen)
1271231×
    }
128
129
    /// The changes within `depth` dependency steps of `heads` (spec §17),
130
    /// nearest first; depth 1 is the heads themselves.
1313×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1323×
        let mut out = Vec::new();
1333×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1343×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1353×
        for _ in 0..depth.max(1) {
1368×
            let mut next = Vec::new();
13712×
            for h in layer {
13812×
                if !seen.insert(h) || !self.store.has(&h) {
1392×
                    continue;
14010×
                }
14110×
                let c = self.store.get_change(&h)?;
14210×
                next.extend(c.deps.iter().copied());
14310×
                out.push(h);
144
            }
1458×
            if next.is_empty() {
1461×
                break;
1477×
            }
1487×
            layer = next;
149
        }
1503×
        out.reverse();
1513×
        Ok(out)
1523×
    }
153
1541771×
    fn shallow_path(&self) -> PathBuf {
1551771×
        self.oxy.join("shallow")
1561771×
    }
157
158
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1591768×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1601768×
        fs::read_to_string(self.shallow_path())
1611768×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1621768×
            .unwrap_or_default()
1631768×
    }
164
165166×
    pub fn is_shallow(&self) -> bool {
166166×
        !self.boundary().is_empty()
167166×
    }
168
1693×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1703×
        if boundary.is_empty() {
1711×
            let _ = fs::remove_file(self.shallow_path());
1721×
            return Ok(());
1732×
        }
1742×
        let text: String = boundary
1752×
            .iter()
1762×
            .map(|h| format!("{}\n", h.to_hex()))
1772×
            .collect();
1782×
        write_atomic(&self.shallow_path(), text.as_bytes())
1793×
    }
180
181
    /// Recompute the boundary from what is stored: every dependency of a
182
    /// stored change that is not itself stored.
1833×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1843×
        let mut boundary = self.boundary();
1853×
        boundary.retain(|h| !self.store.has(h));
18610×
        for h in imported {
18713×
            for d in self.store.get_change_meta(h)?.deps {
18813×
                if !self.store.has(&d) {
1892×
                    boundary.insert(d);
19011×
                }
191
            }
192
        }
1933×
        self.write_boundary(&boundary)
1943×
    }
195
196
    /// Fetch `depth` more levels of history below the shallow boundary.
1972×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
1982×
        let boundary = self.boundary();
1992×
        if boundary.is_empty() {
2000×
            return Ok(0);
2012×
        }
2022×
        let remote = self.open_named_remote(remote_name)?;
2032×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2042×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2052×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2062×
        if self.config.max_blob.is_some() {
2070×
            self.register_missing_blobs(&imported, remote_name)?;
2082×
        }
2092×
        self.refresh_boundary(&imported)?;
2102×
        Ok(imported.len())
2112×
    }
212
213
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
214701×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
215701×
        let have = self.closure_in_store(have)?;
216
        // In a shallow repository the walk stops at the boundary, whose
217
        // changes the remote is assumed to hold.
218701×
        let boundary = self.boundary();
219701×
        let mut out = Vec::new();
220701×
        let mut done: BTreeSet<ChangeHash> = have.clone();
221701×
        done.extend(boundary.iter().copied());
222
        // Iterative post-order DFS.
2231139×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2243016×
        while let Some((h, expanded)) = stack.pop() {
2252315×
            if done.contains(&h) {
226371×
                continue;
2271944×
            }
2281944×
            if !self.store.has(&h) {
2290×
                return fail(format!("change {} is not in this repository", h.short(12)));
2301944×
            }
2311944×
            if expanded {
232972×
                done.insert(h);
233972×
                out.push(h);
234972×
                continue;
235972×
            }
236972×
            stack.push((h, true));
237972×
            for d in self.store.get_change_meta(&h)?.deps {
238697×
                if !done.contains(&d) {
239204×
                    stack.push((d, false));
240493×
                }
241
            }
242
        }
243701×
        Ok(out)
244701×
    }
245
246
    /// Bundle changes (in the given dependency order) with their signatures,
247
    /// seals, identities, blobs, chunks.
248346×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
249346×
        self.bundle_for_filtered(changes, None)
250346×
    }
251
252
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2534×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2544×
        let mut out = Vec::new();
2554×
        for r in refs {
2564×
            let (ty, body) = match self.store.get(r) {
2574×
                Ok(x) => x,
2580×
                Err(StoreError::NotFound(_)) => continue,
2590×
                Err(e) => return Err(e.into()),
260
            };
2614×
            if ty == ObjectType::Blob {
2625×
                for c in Blob::decode(&body)?.chunks {
2635×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2645×
                        out.push((cty, cb));
2655×
                    }
266
                }
2670×
            }
2684×
            out.push((ty, body));
269
        }
2704×
        Ok(out)
2714×
    }
272
273
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
274
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
275393×
    pub fn bundle_for_filtered(
276393×
        &self,
277393×
        changes: &[ChangeHash],
278393×
        max_blob: Option<u64>,
279393×
    ) -> Result<Bundle> {
280393×
        self.bundle_of(changes, max_blob, false)
281393×
    }
282
283
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
284
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
285
    /// with their text blobs and chunks among the objects, so neither side
286
    /// decodes or encodes their text.
287297×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
288297×
        self.bundle_of(changes, max_blob, true)
289297×
    }
290
291690×
    fn bundle_of(
292690×
        &self,
293690×
        changes: &[ChangeHash],
294690×
        max_blob: Option<u64>,
295690×
        raw: bool,
296690×
    ) -> Result<Bundle> {
297690×
        let mut bundle = Bundle::default();
298690×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
299690×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3001085×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3011085×
            if !r.is_zero() && self.store.has(r) {
302263×
                objects.insert(*r);
303822×
            }
3041085×
        };
305974×
        for h in changes {
306
            // Raw: the stored bytes, and a skeleton for the rest.
307974×
            let (c, encoded) = if raw {
308490×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
309490×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3104974×
                for t in texts {
3114974×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3123×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3133×
                        objects.insert(r);
3143×
                        objects.extend(blob.chunks);
3154971×
                    }
316
                }
317490×
                (skel, Some(bytes))
318
            } else {
319484×
                (self.store.get_change(h)?, None)
320
            };
321974×
            let sigs = self.store.signatures(h)?;
322974×
            add_object(&c.author, &mut objects);
323974×
            for s in &sigs {
32436×
                add_object(&s.key, &mut objects);
32536×
            }
3266003×
            for e in &c.edits {
3276003×
                if let Edit::Replace { old, new, .. } = e {
32815×
                    for b in [old, new].into_iter().flatten() {
32915×
                        if self.store.has(b) {
33015×
                            if let Ok(blob) =
33115×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
332
                            {
33315×
                                if max_blob.is_some_and(|m| blob.length > m) {
3344×
                                    continue;
33511×
                                }
33611×
                                objects.insert(*b);
33711×
                                objects.extend(blob.chunks.iter().copied());
3380×
                            }
3390×
                        }
340
                    }
3415990×
                }
342
            }
343974×
            for s in self.store.seals_for(h)? {
34479×
                seals.insert(s);
34579×
            }
346974×
            match encoded {
347490×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
348484×
                None => {
349484×
                    bundle.changes.push((c, sigs));
350484×
                    bundle.hashes.push(*h);
351484×
                }
352
            }
353
        }
354690×
        for r in seals {
35575×
            let attest = self.store.get_attest(&r)?;
35675×
            let sigs = self.store.signatures(&r)?;
35775×
            for s in &sigs {
35875×
                add_object(&s.key, &mut objects);
35975×
            }
36075×
            bundle.attests.push(SignedAttest { attest, sigs });
361
        }
362690×
        for r in objects {
363170×
            let (ty, body) = self.store.get(&r)?;
364170×
            bundle.objects.push((ty, body));
365
        }
366690×
        Ok(bundle)
367690×
    }
368
369
    /// Store a bundle's contents. With `strict`, every change must
370
    /// authenticate (signature or seal by its author or a delegate).
371660×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
372660×
        self.import_bundle_inner(bundle, strict, false)
373660×
    }
374
375
    /// Like `import_bundle`, accepting changes whose dependencies are absent
376
    /// (they join the shallow boundary).
3773×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
3783×
        self.import_bundle_inner(bundle, strict, true)
3793×
    }
380
381663×
    fn import_bundle_inner(
382663×
        &self,
383663×
        bundle: &Bundle,
384663×
        strict: bool,
385663×
        shallow: bool,
386663×
    ) -> Result<Vec<ChangeHash>> {
387663×
        let batch = self.store.begin_batch()?;
388663×
        let result = self.import_bundle_batched(bundle, strict, shallow);
389663×
        batch.finish()?;
390661×
        result
391663×
    }
392
393663×
    fn import_bundle_batched(
394663×
        &self,
395663×
        bundle: &Bundle,
396663×
        strict: bool,
397663×
        shallow: bool,
398663×
    ) -> Result<Vec<ChangeHash>> {
399663×
        for (ty, _) in &bundle.objects {
4000×
            if !matches!(
401440×
                ty,
402
                ObjectType::Chunk
403
                    | ObjectType::Blob
404
                    | ObjectType::Identity
405
                    | ObjectType::State
406
                    | ObjectType::Checkpoint
407
            ) {
4080×
                return fail(format!("bundle may not carry {} objects", ty.name()));
409440×
            }
410
        }
411
        // All at once: in a large batch they are compressed on every core.
412663×
        let objects: Vec<(ObjectType, &[u8])> = bundle
413663×
            .objects
414663×
            .iter()
415663×
            .map(|(ty, body)| (*ty, body.as_slice()))
416663×
            .collect();
417663×
        self.store.put_many(&objects)?;
418663×
        for sa in &bundle.attests {
41964×
            let r = self.store.put_attest(&sa.attest)?;
42064×
            for sig in &sa.sigs {
42164×
                self.store.put_signature(&r, sig)?;
422
            }
42364×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
42468×
                for h in hashes {
42568×
                    self.store.index_seal(h, &r)?;
426
                }
4270×
            }
428
        }
429
        // Each change's hash: from the bundle when its maker knew it, else
430
        // worked out once (for a change adding a whole tree, hashing is
431
        // chunking all its text).
432663×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
433654×
            bundle.hashes.clone()
434
        } else {
4359×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
436
        };
437663×
        let raw_hashes: Vec<ChangeHash> = bundle
438663×
            .raw_changes
439663×
            .iter()
440663×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
441663×
            .collect();
442663×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
443663×
        let boundary = self.boundary();
444663×
        let mut imported = Vec::new();
445
        // Changes as stored: checked, then stored as they are, their text
446
        // blobs having come with the objects.
447663×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
448491×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
449491×
            for d in &skel.deps {
450372×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
451
                {
4520×
                    return fail(format!(
453
                        "change {} depends on {}, which is neither stored nor in the bundle",
4540×
                        h.short(12),
4550×
                        d.short(12)
456
                    ));
457372×
                }
458
            }
4594975×
            for t in texts {
4604975×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
4614×
                    if !self.store.has(&r) {
4621×
                        return fail(format!(
463
                            "change {} came without its text blob {}",
4641×
                            h.short(12),
4651×
                            r.short(12)
466
                        ));
4673×
                    }
4684971×
                }
469
            }
470490×
            self.store.put(ObjectType::Change, bytes)?;
471490×
            for sig in sigs {
4724×
                self.store.put_signature(&h, sig)?;
473
            }
474490×
            imported.push(h);
475
        }
476662×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
477445×
            for d in &c.deps {
478279×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
479
                {
4803×
                    return fail(format!(
481
                        "change {} depends on {}, which is neither stored nor in the bundle",
4823×
                        h.short(12),
4833×
                        d.short(12)
484
                    ));
485276×
                }
486
            }
487442×
            let stored = self.store.put_change(c)?;
488442×
            if stored != h {
4890×
                return fail(format!(
490
                    "change {} is not the change the bundle names",
4910×
                    h.short(12)
492
                ));
493442×
            }
494442×
            for sig in sigs {
49525×
                self.store.put_signature(&h, sig)?;
496
            }
497442×
            imported.push(h);
498
        }
499659×
        if strict {
50028×
            for h in &imported {
50119×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
5021×
                    return fail(format!(
503
                        "change {} is not authenticated by its author",
5041×
                        h.short(12)
505
                    ));
50618×
                }
507
            }
508631×
        }
509658×
        Ok(imported)
510663×
    }
511
512
    /// Verify a reference attestation against an update it claims to describe.
513
    /// `allow_equal` lets a client re-read the attestation it already has; a
514
    /// server receiving a push requires a strictly greater serial.
515
    /// A reference attestation signed by a delegate of an identity the
516
    /// rule lists is authorized as that identity (spec §14.5): the identity
517
    /// named the delegate with the `refs` scope, still in force at `at_ms`
518
    /// (the attestation's wall time), and the policy names the identity.
519
    /// Revoked keys authorize nothing either way.
5206×
    pub(crate) fn delegate_authorized(
5216×
        &self,
5226×
        p: &crate::policy::Policy,
5236×
        signer: &KeyId,
5246×
        reference: &str,
5256×
        at_ms: u64,
5266×
    ) -> bool {
5276×
        if p.is_revoked(signer) {
5281×
            return false;
5295×
        }
5305×
        let Some(rule) = p.rule_for(reference) else {
5310×
            return false;
532
        };
5336×
        rule.keys.iter().any(|k| {
5346×
            !p.is_revoked(k)
5356×
                && p.identity(k)
5366×
                    .cloned()
5376×
                    .or_else(|| self.store.get_identity(k).ok())
5386×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
5396×
        })
5406×
    }
541
54293×
    fn check_ref_attest(
54393×
        &self,
54493×
        sa: &SignedAttest,
54593×
        name: &str,
54693×
        old_state: &ObjectRef,
54793×
        new_state: &ObjectRef,
54893×
        last_serial: Option<u64>,
54993×
        allow_equal: bool,
55093×
    ) -> std::result::Result<u64, String> {
551
        let AttestBody::Ref {
55293×
            name: n,
55393×
            old_state: o,
55493×
            new_state: nw,
55593×
            serial,
55693×
        } = &sa.attest.body
557
        else {
5580×
            return Err("attestation is not a ref attestation".into());
559
        };
56093×
        if n != name || o != old_state || nw != new_state {
5611×
            return Err("attestation does not describe this update".into());
56292×
        }
56392×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
5640×
            return Err("attestation is for a different repository".into());
56592×
        }
56692×
        if let Some(last) = last_serial {
56759×
            if *serial < last || (*serial == last && !allow_equal) {
5681×
                return Err(format!(
5691×
                    "attestation serial {serial} is not greater than the last seen {last}"
5701×
                ));
57158×
            }
57233×
        }
57391×
        let r = sa.attest.hash();
57491×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
57591×
        let id = self
57691×
            .store
57791×
            .get_identity(&sig.key)
57891×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
57991×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
58091×
        Ok(*serial)
58193×
    }
582
583
    /// Accept a push (spec §16.4). Without a trust policy every repository
584
    /// is unverified, so unsigned changes and unattested updates are accepted;
585
    /// attestations that are present must still be valid. With a policy,
586
    /// every change and update is checked against it. A newer policy in the
587
    /// push is applied first when it is signed by the current roots.
588252×
    pub fn receive_push(
589252×
        &self,
590252×
        bundle: Bundle,
591252×
        updates: Vec<RefUpdate>,
592252×
        policy: Option<SignedPolicy>,
593252×
        tags: Vec<crate::protocol::TagRef>,
594252×
    ) -> Result<Vec<RefResult>> {
595252×
        Ok(self
596252×
            .receive_push_report(bundle, updates, policy, tags)?
597
            .results)
598252×
    }
599
600
    /// `receive_push` with what a host wants to log: each accepted
601
    /// reference's old and new state and heads, and the changes this push
602
    /// stored (hub spec §6.12).
603292×
    pub fn receive_push_report(
604292×
        &self,
605292×
        bundle: Bundle,
606292×
        updates: Vec<RefUpdate>,
607292×
        policy: Option<SignedPolicy>,
608292×
        tags: Vec<crate::protocol::TagRef>,
609292×
    ) -> Result<PushReport> {
610292×
        let mut report = PushReport::default();
611292×
        let results = &mut report.results;
612292×
        if let Some(sp) = policy {
61318×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
61416×
                Ok(()) => {
61516×
                    results.push(RefResult {
61616×
                        name: "policy".into(),
61716×
                        ok: true,
61816×
                        reason: format!("serial {}", sp.policy.serial),
61916×
                    });
62016×
                }
6212×
                Err(e) => {
6222×
                    results.push(RefResult {
6232×
                        name: "policy".into(),
6242×
                        ok: false,
6252×
                        reason: e,
6262×
                    });
6272×
                    for u in updates {
6280×
                        results.push(RefResult {
6290×
                            name: u.name,
6300×
                            ok: false,
6310×
                            reason: "policy update was rejected".into(),
6320×
                        });
6330×
                    }
6342×
                    return Ok(report);
635
                }
636
            }
637274×
        }
638290×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
639290×
        match self.import_bundle(&bundle, policy.is_some()) {
640287×
            Ok(imported) => report.imported = imported,
6413×
            Err(e) => {
6423×
                for u in updates {
6433×
                    results.push(RefResult {
6443×
                        name: u.name,
6453×
                        ok: false,
6463×
                        reason: e.to_string(),
6473×
                    });
6483×
                }
6493×
                return Ok(report);
650
            }
651
        }
652287×
        let (op_ref, op) = self.head_op()?;
653287×
        let mut view = op.view.clone();
654287×
        let mut names = Vec::new();
655287×
        for u in updates {
656284×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
657284×
            let (ok, reason) = match outcome {
658259×
                Ok(()) => (true, String::new()),
65925×
                Err(e) => (false, e),
660
            };
661284×
            if ok {
662259×
                names.push(u.name.clone());
663259×
                let heads = self
664259×
                    .store
665259×
                    .get_state(&u.new_state)
666259×
                    .map(|s| s.heads)
667259×
                    .unwrap_or_default();
668259×
                report.updated.push(RefUpdated {
669259×
                    name: u.name.clone(),
670259×
                    old_state: u.old_state,
671259×
                    new_state: u.new_state,
672259×
                    heads,
673259×
                });
67425×
            }
675284×
            results.push(RefResult {
676284×
                name: u.name,
677284×
                ok,
678284×
                reason,
679284×
            });
680
        }
681287×
        for t in &tags {
6828×
            let name = format!("tags/{}", t.name);
6838×
            let new = !view.tags.contains_key(&t.name);
6848×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
685
                Ok(()) => {
686
                    // A tag new here is an update too, so a hub can start
687
                    // its pipeline's tag jobs (oxygenflow#24); one it
688
                    // already had, sent again, is not.
6896×
                    if new {
6906×
                        report.updated.push(RefUpdated {
6916×
                            name: name.clone(),
6926×
                            old_state: ObjectRef::ZERO,
6936×
                            new_state: t.state,
6946×
                            heads: t.heads.clone(),
6956×
                        });
6966×
                    }
6976×
                    names.push(name.clone());
6986×
                    results.push(RefResult {
6996×
                        name,
7006×
                        ok: true,
7016×
                        reason: String::new(),
7026×
                    });
703
                }
7042×
                Err(e) => results.push(RefResult {
7052×
                    name,
7062×
                    ok: false,
7072×
                    reason: e,
7082×
                }),
709
            }
710
        }
711287×
        if !names.is_empty() {
712259×
            self.record_op(
713259×
                &[op_ref],
714259×
                &format!("push received: {}", names.join(" ")),
715259×
                view,
7163×
            )?;
71728×
        }
718284×
        Ok(report)
719292×
    }
720
721
    /// Check an update's attestation against the latest one for its
722
    /// reference and store it as the new latest. Failures say what was
723
    /// being done, for which reference, so a refused push can be diagnosed
724
    /// from its reason alone.
72574×
    fn record_update_attest(
72674×
        &self,
72774×
        u: &RefUpdate,
72874×
        sa: &SignedAttest,
72974×
    ) -> std::result::Result<(), String> {
73074×
        let name = &u.name;
73174×
        let last = self
73274×
            .latest_ref_attest(name)
73374×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
73474×
            .and_then(|(_, a)| match a.attest.body {
73549×
                AttestBody::Ref { serial, .. } => Some(serial),
7360×
                _ => None,
73749×
            });
73874×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
73972×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
74072×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
74171×
        for sig in &sa.sigs {
74271×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
743
        }
74471×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
74574×
    }
746
747
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
748
    /// at `old_state`, is never the bookmark a non-bare repository has
749
    /// checked out (a bare one's default is its host's to protect, see
750
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
751
    /// an attestation by a key that may update it.
752
    /// The deletion's attestation stays the bookmark's latest, so an older
753
    /// one cannot be replayed to bring it back.
7543×
    fn apply_deletion(
7553×
        &self,
7563×
        view: &mut View,
7573×
        u: &RefUpdate,
7583×
        policy: Option<&crate::policy::Policy>,
7593×
    ) -> std::result::Result<(), String> {
7603×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
7610×
            return Err(format!("no bookmark {:?} to delete", u.name));
762
        };
7633×
        if current != u.old_state {
7640×
            return Err("stale: the remote bookmark has moved; pull first".into());
7653×
        }
7663×
        if !self.is_bare() && u.name == self.config.bookmark {
7671×
            return Err(format!(
7681×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
7691×
                u.name
7701×
            ));
7712×
        }
7722×
        if let Some(p) = policy {
7730×
            let Some(sa) = &u.attestation else {
7740×
                return Err(format!(
7750×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
7760×
                    u.name
7770×
                ));
778
            };
7790×
            let signer = sa
7800×
                .sigs
7810×
                .first()
7820×
                .map(|s| s.key)
7830×
                .ok_or("attestation carries no signature")?;
7840×
            if !p.authorizes(&signer, &u.name)
7850×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
786
            {
7870×
                return Err(format!(
7880×
                    "key {} may not delete {:?} under this repository's policy",
7890×
                    signer.short(12),
7900×
                    u.name
7910×
                ));
7920×
            }
7932×
        }
7942×
        if let Some(sa) = &u.attestation {
7951×
            self.record_update_attest(u, sa)?;
7961×
        }
7972×
        view.bookmarks.remove(&u.name);
7982×
        Ok(())
7993×
    }
800
801284×
    fn apply_update(
802284×
        &self,
803284×
        view: &mut View,
804284×
        u: &RefUpdate,
805284×
        policy: Option<&crate::policy::Policy>,
806284×
    ) -> std::result::Result<(), String> {
807284×
        if u.name == "policy" {
8080×
            return Err(
8090×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
8100×
            );
811284×
        }
812284×
        let empty = self
813284×
            .store
814284×
            .put_state(&StateObject::new(vec![]))
815284×
            .map_err(|e| e.to_string())?;
816284×
        if u.new_state.is_zero() {
8173×
            return self.apply_deletion(view, u, policy);
818281×
        }
819281×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
820281×
        if current != u.old_state {
82110×
            return Err("stale: the remote bookmark has moved; pull first".into());
822271×
        }
823271×
        let new_state = self
824271×
            .store
825271×
            .get_state(&u.new_state)
826271×
            .map_err(|_| "new state object is missing".to_string())?;
827522×
        for h in &new_state.heads {
828522×
            if !self.store.has(h) {
8291×
                return Err(format!("head {} is missing", h.short(12)));
830521×
            }
831
        }
832270×
        if !u.force {
833269×
            let old_heads = self
834269×
                .store
835269×
                .get_state(&current)
836269×
                .map_err(|e| e.to_string())?
837
                .heads;
838269×
            let closure = self
839269×
                .closure_in_store(&new_state.heads)
840269×
                .map_err(|e| e.to_string())?;
841286×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
8421×
                return Err(format!(
8431×
                    "not a fast-forward: current head {} would be dropped (use --force)",
8441×
                    h.short(12)
8451×
                ));
846268×
            }
8471×
        }
848269×
        if let Some(p) = policy {
84926×
            let Some(sa) = &u.attestation else {
8501×
                return Err(format!(
8511×
                    "{:?} requires a signed reference attestation under this repository's policy",
8521×
                    u.name
8531×
                ));
854
            };
85525×
            let signer = sa
85625×
                .sigs
85725×
                .first()
85825×
                .map(|s| s.key)
85925×
                .ok_or("attestation carries no signature")?;
86025×
            if !p.authorizes(&signer, &u.name)
8616×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
862
            {
8635×
                return Err(format!(
8645×
                    "key {} may not update {:?} under this repository's policy",
8655×
                    signer.short(12),
8665×
                    u.name
8675×
                ));
86820×
            }
86920×
            let old_heads = self
87020×
                .store
87120×
                .get_state(&current)
87220×
                .map_err(|e| e.to_string())?
873
                .heads;
87420×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
875243×
        }
876263×
        if let Some(sa) = &u.attestation {
87773×
            self.record_update_attest(u, sa)?;
878190×
        }
879257×
        view.bookmarks.insert(u.name.clone(), u.new_state);
880257×
        Ok(())
881284×
    }
882
883
    // ------------------------------------------------------------ client side
884
885918×
    fn remote_url(&self, name: &str) -> Result<String> {
886918×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
8872×
            RepoError::Msg(format!(
8882×
                "no remote named {name:?}; add one with `oxy remote add`"
8892×
            ))
8902×
        })
891918×
    }
892
893
    /// Refuse a remote that is another repository. An **unbound** remote
894
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
895
    /// for pushes, which bind it to this repository's id (spec §16.1).
896688×
    fn check_remote_id(
897688×
        &self,
898688×
        remote: &dyn crate::protocol::Remote,
899688×
        remote_name: &str,
900688×
        allow_unbound: bool,
901688×
    ) -> Result<()> {
902688×
        let theirs = remote.repo_id()?;
903687×
        if theirs == self.id()? {
904667×
            return Ok(());
90520×
        }
90620×
        if theirs == crate::protocol::UNBOUND_ID {
90717×
            if allow_unbound {
90816×
                return Ok(());
9091×
            }
9101×
            return fail(format!(
911
                "remote {remote_name:?} is empty and unbound: push to it first"
912
            ));
9133×
        }
9143×
        fail(format!(
915
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
916
        ))
917688×
    }
918
919
    /// Credentials and trust for a remote: `remote.<name>.token` and
920
    /// `remote.<name>.ca`, else the defaults for its URL
921
    /// ([`Repo::fill_credentials`]).
922935×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
923935×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
924935×
        let mut options = RemoteOptions {
925935×
            repo_id: self.id().ok(),
926935×
            token: self.config.remote_tokens.get(name).cloned(),
927935×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
928935×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
929935×
        };
930935×
        self.fill_credentials(&url, &mut options);
931935×
        options
932935×
    }
933
934
    /// The user's credential store (`credentials.toml` beside the user
935
    /// configuration file).
936946×
    pub fn credentials(&self) -> crate::credentials::Credentials {
937946×
        crate::credentials::Credentials::at(
938946×
            self.user_config
939946×
                .parent()
940946×
                .map(Path::to_path_buf)
941946×
                .unwrap_or_else(default_home),
942
        )
943946×
    }
944
945
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
946
    /// then the user's credential store for its hub, then a remote on the
947
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
948947×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
949947×
        if options.token.is_some() && options.ca.is_some() {
9501×
            return;
951946×
        }
952946×
        let stored = self.credentials().options_for(url);
953946×
        options.token = options.token.take().or(stored.token);
954946×
        options.ca = options.ca.take().or(stored.ca);
955946×
        if options.token.is_some() && options.ca.is_some() {
9560×
            return;
957946×
        }
958946×
        let Some(hub) = crate::credentials::hub_of(url) else {
959813×
            return;
960
        };
961133×
        let mut at = self.root.parent();
962530×
        while let Some(dir) = at {
963397×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
9640×
                break;
965
            };
966397×
            for (key, remote_url) in &cfg {
9675×
                let Some(name) = key
9685×
                    .strip_prefix("remote.")
9695×
                    .and_then(|k| k.strip_suffix(".url"))
970
                else {
9712×
                    continue;
972
                };
9733×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
9741×
                    continue;
9752×
                }
9762×
                if options.token.is_none() {
9772×
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
9782×
                }
9792×
                if options.ca.is_none() {
9802×
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
9812×
                }
982
            }
983397×
            if options.token.is_some() && options.ca.is_some() {
9840×
                return;
985397×
            }
986397×
            at = dir.parent();
987
        }
988947×
    }
989
990
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
991
    /// no changes and no reference updates, which the receiver stores.
9920×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
9930×
        let remote = self.open_named_remote(remote_name)?;
9940×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
9950×
        let mut bundle = Bundle::default();
9960×
        for r in seals {
9970×
            let attest = self.store.get_attest(r)?;
9980×
            let sigs = self.store.signatures(r)?;
9990×
            bundle
10000×
                .attests
10010×
                .push(crate::protocol::SignedAttest { attest, sigs });
1002
        }
10030×
        let results = remote.push(bundle, vec![], None, vec![])?;
10040×
        if let Some(r) = results.iter().find(|r| !r.ok) {
10050×
            return fail(format!("{}: {}", r.name, r.reason));
10060×
        }
10070×
        Ok(())
10080×
    }
1009
1010
    /// The remote whose URL starts with `base` (a hub), if configured.
10113×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
10123×
        let base = base.trim_end_matches('/');
10133×
        self.config
10143×
            .remotes
10153×
            .iter()
10163×
            .find(|(_, url)| url.trim_end_matches('/') == base)
10173×
            .map(|(name, _)| name.clone())
10183×
    }
1019
1020
    /// Open a remote by name or, failing that, by URL with the default
1021
    /// credentials (see [`Repo::credentials_for`]).
10220×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
10230×
        if let Some(name) = self.remote_for_url(url) {
10240×
            return Ok((name.clone(), self.open_named_remote(&name)?));
10250×
        }
10260×
        let options = RemoteOptions {
10270×
            repo_id: self.id().ok(),
10280×
            ..self.credentials_for(url)
10290×
        };
10300×
        Ok((url.to_string(), open_remote(url, &options)?))
10310×
    }
1032
1033
    /// Credentials for a URL: those of the configured remote with that
1034
    /// URL, else the environment's.
10353×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
10363×
        match self.remote_for_url(url) {
10373×
            Some(name) => self.remote_options(&name),
10380×
            None => RemoteOptions {
10390×
                repo_id: self.id().ok(),
10400×
                ..self.credentials_for(url)
10410×
            },
1042
        }
10433×
    }
1044
1045918×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1046918×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1047918×
    }
1048
104992×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
105092×
        self.oxy
105192×
            .join("remotes")
105292×
            .join(remote)
105392×
            .join(format!("{bookmark}.serial"))
105492×
    }
1055
105619×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
105719×
        fs::read_to_string(self.serial_path(remote, bookmark))
105819×
            .ok()
105919×
            .and_then(|s| s.trim().parse().ok())
106019×
    }
1061
106273×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
106373×
        let p = self.serial_path(remote, bookmark);
106473×
        fs::create_dir_all(p.parent().unwrap())?;
106573×
        write_atomic(&p, serial.to_string().as_bytes())
106673×
    }
1067
1068357×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1069357×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1070357×
    }
1071
1072
    /// The highest policy serial `remote` has ever presented.
1073333×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1074333×
        fs::read_to_string(self.policy_serial_path(remote))
1075333×
            .ok()
1076333×
            .and_then(|s| s.trim().parse().ok())
1077333×
    }
1078
107924×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
108024×
        let p = self.policy_serial_path(remote);
108124×
        fs::create_dir_all(p.parent().unwrap())?;
108224×
        write_atomic(&p, serial.to_string().as_bytes())
108324×
    }
1084
108527×
    fn lazy_dir(&self) -> PathBuf {
108627×
        self.oxy.join("lazy")
108727×
    }
1088
1089
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
10904×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
10914×
        fs::create_dir_all(self.lazy_dir())?;
10924×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
10934×
    }
1094
1095
    /// Which remote promised an absent blob, if any.
109615×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
109715×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
109815×
            .ok()
109915×
            .map(|s| s.trim().to_string())
110015×
    }
1101
1102
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
11034×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
11044×
        let Some(remote_name) = self.lazy_remote(blob) else {
11050×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1106
        };
11074×
        let remote = self.open_named_remote(&remote_name)?;
11084×
        let objects = remote.objects(&[*blob])?;
11099×
        for (ty, body) in objects {
11109×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
11119×
                self.store.put(ty, &body)?;
11120×
            }
1113
        }
11144×
        if !self.store.has(blob) {
11150×
            return fail(format!(
1116
                "{remote_name} did not send blob {}",
11170×
                blob.short(12)
1118
            ));
11194×
        }
11204×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
11214×
        Ok(())
11224×
    }
1123
1124
    /// After importing from `remote`, record every blob the changes reference
1125
    /// that the store lacks as lazily available from that remote.
11264×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
11274×
        let mut n = 0;
11284×
        for h in changes {
11294×
            let c = self.store.get_change(h)?;
113013×
            for e in &c.edits {
113113×
                if let Edit::Replace { old, new, .. } = e {
11326×
                    for b in [old, new].into_iter().flatten() {
11336×
                        if !self.store.has(b) {
11344×
                            self.register_lazy(b, remote)?;
11354×
                            n += 1;
11362×
                        }
1137
                    }
11387×
                }
1139
            }
1140
        }
11414×
        Ok(n)
11424×
    }
1143
1144
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1145333×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1146333×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1147454×
        for st in view
1148333×
            .bookmarks
1149333×
            .values()
1150333×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1151
        {
1152454×
            if let Ok(s) = self.store.get_state(st) {
1153454×
                have.extend(s.heads);
1154454×
            }
1155
        }
1156333×
        have.extend(view.workspaces.values().copied());
1157333×
        Ok(have.into_iter().collect())
1158333×
    }
1159
1160
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1161338×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1162338×
        let remote = self.open_named_remote(remote_name)?;
1163336×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1164334×
        let resp = remote.refs()?;
1165
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1166
        // and signed by roots we trust, or on first contact. A remote that
1167
        // once presented a policy may never present none or an older one:
1168
        // that is a downgrade. A remote that never presented one is
1169
        // unverified, and this fetch is checked only as far as possible.
1170333×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1171333×
        let seen = self.remote_policy_serial(remote_name);
1172333×
        let mut unverified = false;
1173333×
        match &resp.policy {
11748×
            Some(sp) => {
11758×
                if seen.is_some_and(|s| sp.policy.serial < s) {
11760×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
11778×
                }
11785×
                match &local_policy {
11795×
                    Some(l) if sp.policy.serial < l.serial => {}
11805×
                    Some(l) if sp.policy.serial == l.serial => {
11811×
                        if sp.policy.hash() != l.hash() {
11820×
                            return fail(format!(
1183
                                "{remote_name} presents a different policy with the same serial {}",
1184
                                l.serial
1185
                            ));
11861×
                        }
1187
                    }
1188
                    _ => {
11897×
                        self.adopt_policy_chain(
11907×
                            &resp.history,
11917×
                            sp,
11927×
                            &format!("oxy fetch {remote_name}"),
1193
                        )
11947×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1195
                    }
1196
                }
11978×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1198
            }
1199
            None => {
1200325×
                if seen.is_some() {
12010×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1202325×
                }
1203325×
                unverified = true;
1204
            }
1205
        }
1206333×
        let policy = if unverified {
1207325×
            None
1208
        } else {
12098×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1210
        };
1211333×
        let (op_ref, op) = self.head_op()?;
1212333×
        let mut view = op.view.clone();
1213333×
        let have = self.known_heads(&view)?;
1214333×
        let mut report = Vec::new();
1215333×
        let max_blob = self.config.max_blob;
1216340×
        for r in resp.refs {
1217340×
            let needed = {
1218340×
                let _t = crate::timing::phase("fetch: negotiate");
1219340×
                remote.negotiate(&have, &r.heads)?
1220
            };
1221340×
            let bundle = {
1222340×
                let _t = crate::timing::phase("fetch: bundle");
1223340×
                remote.fetch(&needed, max_blob)?
1224
            };
1225
            // Changes are not individually re-verified here: the bookmark's
1226
            // attestation (checked below) binds its whole state, and the
1227
            // receiver of the push verified the added changes at that time.
1228340×
            let imported = {
1229340×
                let _t = crate::timing::phase("fetch: import");
1230340×
                self.import_bundle(&bundle, false)?
1231
            };
1232340×
            if max_blob.is_some() {
12334×
                self.register_missing_blobs(&imported, remote_name)?;
1234336×
            }
1235489×
            for h in &r.heads {
1236489×
                if !self.store.has(h) {
12370×
                    return fail(format!("remote did not send head {}", h.short(12)));
1238489×
                }
1239
            }
1240340×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1241340×
            if state != r.state {
12420×
                return fail(format!(
1243
                    "remote state {} does not match its heads",
12440×
                    r.state.short(12)
1245
                ));
1246340×
            }
1247340×
            if let Some(p) = &policy {
12488×
                let Some(sa) = &r.attestation else {
12490×
                    return fail(format!(
1250
                        "{remote_name}/{} has no attestation, which its policy requires",
1251
                        r.name
1252
                    ));
1253
                };
12548×
                let signer = sa
12558×
                    .sigs
12568×
                    .first()
12578×
                    .map(|s| s.key)
12588×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
12598×
                if !p.authorizes(&signer, &r.name)
12600×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1261
                {
12620×
                    return fail(format!(
1263
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1264
                        r.name,
12650×
                        signer.short(12)
1266
                    ));
12678×
                }
1268332×
            }
1269340×
            if let Some(sa) = &r.attestation {
1270
                let AttestBody::Ref {
127119×
                    old_state,
127219×
                    new_state,
1273
                    ..
127419×
                } = &sa.attest.body
1275
                else {
12760×
                    return fail("remote sent a non-ref attestation for a bookmark");
1277
                };
127819×
                let (old_state, new_state) = (*old_state, *new_state);
127919×
                let serial = self
128019×
                    .check_ref_attest(
128119×
                        sa,
128219×
                        &r.name,
128319×
                        &old_state,
128419×
                        &new_state,
128519×
                        self.last_seen_serial(remote_name, &r.name),
1286
                        true,
1287
                    )
128819×
                    .map_err(|e| {
12890×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
12900×
                    })?;
129119×
                if new_state != r.state {
12920×
                    return fail(format!(
1293
                        "attestation for {}/{} does not cover its current state",
1294
                        remote_name, r.name
1295
                    ));
129619×
                }
129719×
                let ar = self.store.put_attest(&sa.attest)?;
129819×
                for sig in &sa.sigs {
129919×
                    self.store.put_signature(&ar, sig)?;
1300
                }
130119×
                self.record_serial(remote_name, &r.name, serial)?;
1302321×
            }
1303340×
            view.remotes
1304340×
                .entry(remote_name.to_string())
1305340×
                .or_default()
1306340×
                .insert(r.name.clone(), state);
1307340×
            report.push((r.name, r.heads, imported.len()));
1308
        }
1309333×
        let mut new_tags = 0;
1310333×
        for t in &resp.tags {
131110×
            if view.tags.contains_key(&t.name) {
13124×
                continue;
13136×
            }
1314
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
13156×
            let missing: Vec<ChangeHash> = t
13166×
                .heads
13176×
                .iter()
13186×
                .filter(|h| !self.store.has(h))
13196×
                .copied()
13206×
                .collect();
13216×
            if !missing.is_empty() {
13220×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
13230×
                let bundle = remote.fetch(&needed, max_blob)?;
13240×
                self.import_bundle(&bundle, false)?;
13256×
            }
13266×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
13276×
            self.adopt_tag(&mut view, t, policy.as_ref())
13286×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
13296×
            new_tags += 1;
1330
        }
1331333×
        if view != op.view {
1332324×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
13339×
        }
1334333×
        let _ = self.run_hook(
1335333×
            "post-fetch",
1336333×
            &format!(
1337
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1338333×
                json_str(remote_name),
1339340×
                json_array(report.iter().map(|(n, heads, _)| format!(
1340
                    "{{\"name\":{},\"heads\":{}}}",
1341340×
                    json_str(n),
1342489×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1343
                )))
1344
            ),
1345
        );
1346333×
        Ok(FetchReport {
1347333×
            refs: report,
1348333×
            unverified,
1349333×
            new_tags,
1350333×
        })
1351338×
    }
1352
1353
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1354
    /// the changes within `depth` steps of its heads, and the boundary below.
13551×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
13561×
        let remote = self.open_named_remote(remote_name)?;
13571×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13581×
        let resp = remote.refs()?;
13591×
        let bookmark = self.config.bookmark.clone();
13601×
        if let Some(sp) = &resp.policy {
13610×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
13620×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
13630×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
13641×
        }
13651×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
13660×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1367
        };
13681×
        if r.heads.is_empty() {
13690×
            return Ok(0);
13701×
        }
1371
        // Base: the remote's checkpoint of exactly these heads.
13721×
        let cp_bundle = remote.checkpoint(&r.heads)?;
13731×
        let mut cp_ref = None;
13743×
        for (ty, body) in &cp_bundle.objects {
13753×
            let put = self.store.put(*ty, body)?;
13763×
            if *ty == ObjectType::Checkpoint {
13771×
                cp_ref = Some(put);
13782×
            }
1379
        }
13801×
        let Some(cp_ref) = cp_ref else {
13810×
            return fail(format!("{remote_name} sent no checkpoint"));
1382
        };
13831×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1384
        // History window.
13851×
        let wanted = remote.shallow(&r.heads, depth)?;
13861×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
13871×
        let imported = self.import_bundle_shallow(&bundle, false)?;
13881×
        if self.config.max_blob.is_some() {
13890×
            self.register_missing_blobs(&imported, remote_name)?;
13901×
        }
13911×
        self.refresh_boundary(&imported)?;
13921×
        if let Some(sa) = &r.attestation {
13930×
            let ar = self.store.put_attest(&sa.attest)?;
13940×
            for sig in &sa.sigs {
13950×
                self.store.put_signature(&ar, sig)?;
1396
            }
13970×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
13980×
                self.record_serial(remote_name, &r.name, serial)?;
13990×
            }
14001×
        }
14011×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
14021×
        let (op_ref, op) = self.head_op()?;
14031×
        let mut view = op.view.clone();
14041×
        view.remotes
14051×
            .entry(remote_name.to_string())
14061×
            .or_default()
14071×
            .insert(r.name.clone(), state);
14081×
        self.record_op(
14091×
            &[op_ref],
14101×
            &format!("oxy fetch {remote_name} --depth {depth}"),
14111×
            view,
14120×
        )?;
14131×
        Ok(imported.len())
14141×
    }
1415
1416
    /// Fetch, then take the union of the local bookmark's state with the
1417
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1418107×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1419107×
        let _wc = self.lock_working_copy()?;
1420107×
        self.fetch(remote_name)?;
1421105×
        let (op_ref, op) = self.head_op()?;
1422105×
        let current = self.config.bookmark.clone();
1423105×
        let mut local_current = self.heads_of(&op.view, &current)?;
1424105×
        local_current.sort();
1425105×
        let mut view = op.view.clone();
1426105×
        let mut current_heads = local_current.clone();
1427105×
        let mut changed = false;
1428105×
        let mut others = Vec::new();
1429105×
        let tracked = op
1430105×
            .view
1431105×
            .remotes
1432105×
            .get(remote_name)
1433105×
            .cloned()
1434105×
            .unwrap_or_default();
1435109×
        for (name, remote_state) in tracked {
1436
            // Every local bookmark tracks the remote's of the same name;
1437
            // the current one may be new here.
1438109×
            let local_state = op.view.bookmarks.get(&name).copied();
1439109×
            if local_state.is_none() && name != current {
14400×
                continue;
1441109×
            }
1442109×
            if local_state == Some(remote_state) {
14437×
                continue;
1444102×
            }
1445102×
            let local = self.heads_of(&op.view, &name)?;
1446102×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1447131×
            if remote_heads.iter().all(|h| local.contains(h)) {
14480×
                continue;
1449102×
            }
1450102×
            let mut all = local.clone();
1451102×
            all.extend(remote_heads);
1452102×
            let st = self.load_state_history(&all)?;
1453102×
            let mut heads = st.maximal(&all);
1454102×
            heads.sort();
1455102×
            let mut sorted_local = local;
1456102×
            sorted_local.sort();
1457102×
            if heads == sorted_local {
14581×
                continue;
1459101×
            }
1460101×
            view.bookmarks.insert(
1461101×
                name.clone(),
1462101×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1463
            );
1464101×
            if name == current {
146599×
                changed = true;
146699×
                current_heads = heads;
146799×
            } else {
14682×
                others.push(name);
14692×
            }
1470
        }
1471105×
        if !changed && others.is_empty() {
14725×
            return Ok(PullReport {
14735×
                heads: local_current,
14745×
                changed: false,
14755×
                checked_out: false,
14765×
                others,
14775×
            });
1478100×
        }
1479100×
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1480100×
        let mut checked_out = false;
1481100×
        if changed {
1482
            // Follow along if the working copy was clean and on the old heads.
148399×
            let snap = self.snapshot("oxy pull")?;
148499×
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
148599×
            let mut base = snap.base.maximal(&snap.wc.deps);
148699×
            base.sort();
148799×
            if clean && base == local_current {
148899×
                self.checkout(&current_heads, false, "oxy pull (checkout)")?;
148999×
                checked_out = true;
14900×
            }
14911×
        }
1492100×
        Ok(PullReport {
1493100×
            heads: current_heads,
1494100×
            changed,
1495100×
            checked_out,
1496100×
            others,
1497100×
        })
1498107×
    }
1499
1500
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1501
    /// changes and attesting the reference when a key is available.
1502
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1503
    /// state, attested when we have an identity. The local bookmark, if
1504
    /// any, is kept; only the remote-tracking entry goes.
15055×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
15065×
        let remote = self.open_named_remote(remote_name)?;
15075×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
15085×
        let resp = remote.refs()?;
15097×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
15101×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1511
        };
15124×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
15130×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
15144×
        }
15154×
        let attestation = match self.secret_key()? {
15162×
            Some(_) => Some(self.sign_attest(&Attest {
15172×
                repo: self.id()?,
15182×
                hlc: Hlc::now(),
15192×
                body: AttestBody::Ref {
15202×
                    name: bookmark.to_string(),
15212×
                    old_state: r.state,
15222×
                    new_state: ObjectRef::ZERO,
15232×
                    serial: r.last_serial.unwrap_or(0) + 1,
15242×
                },
15250×
            })?),
15262×
            None => None,
1527
        };
15284×
        let results = remote.push(
15294×
            Bundle::default(),
15304×
            vec![RefUpdate {
15314×
                name: bookmark.to_string(),
15324×
                old_state: r.state,
15334×
                new_state: ObjectRef::ZERO,
15344×
                force: true,
15354×
                attestation,
15364×
            }],
15374×
            None,
15384×
            vec![],
15390×
        )?;
15404×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
15412×
            let (op_ref, op) = self.head_op()?;
15422×
            let mut view = op.view.clone();
15432×
            if let Some(m) = view.remotes.get_mut(remote_name) {
15442×
                m.remove(bookmark);
15452×
            }
15462×
            self.record_op(
15472×
                &[op_ref],
15482×
                &format!("oxy push {remote_name} --delete {bookmark}"),
15492×
                view,
15500×
            )?;
15512×
        }
15524×
        Ok(results)
15535×
    }
1554
1555339×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1556339×
        let bookmark = self.config.bookmark.clone();
1557339×
        self.push_bookmark(remote_name, &bookmark, force)
1558339×
    }
1559
1560
    /// `push` for a named bookmark (`oxy push -b NAME`).
1561347×
    pub fn push_bookmark(
1562347×
        &self,
1563347×
        remote_name: &str,
1564347×
        bookmark: &str,
1565347×
        force: bool,
1566347×
    ) -> Result<Vec<RefResult>> {
1567347×
        let (op_ref, op) = self.head_op()?;
1568347×
        if !op.view.bookmarks.contains_key(bookmark) {
15690×
            return fail(format!("no bookmark {bookmark}"));
1570347×
        }
1571347×
        let bookmark = bookmark.to_string();
1572347×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1573
        // pre-push hook: may veto before the remote is contacted.
1574347×
        self.run_hook(
1575347×
            "pre-push",
1576347×
            &format!(
1577
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1578347×
                json_str(remote_name),
1579347×
                json_str(&bookmark),
1580721×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1581
            ),
15821×
        )?;
1583346×
        let remote = self.open_named_remote(remote_name)?;
1584346×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1585343×
        let resp = remote.refs()?;
1586343×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1587343×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1588343×
        let policy_to_send = match (&local_policy, &resp.policy) {
158917×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
15907×
            (Some(l), None) => Some(l.clone()),
15918×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
15921×
                return fail(format!(
1593
                    "{remote_name} has a newer policy (serial {}); fetch first",
1594
                    r.policy.serial
1595
                ));
1596
            }
1597326×
            _ => None,
1598
        };
1599342×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1600342×
        if remote_has_policy && self.secret_key()?.is_none() {
16011×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1602341×
        }
1603341×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1604341×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1605341×
            .tag_refs()?
1606341×
            .into_iter()
1607341×
            .filter(|t| !remote_tags.contains(&t.name))
1608341×
            .collect();
1609341×
        let refs = resp.refs;
1610341×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1611341×
        let (remote_state, remote_heads, last_serial) =
1612341×
            match refs.iter().find(|r| r.name == bookmark) {
1613325×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
161416×
                None => (empty, vec![], None),
1615
            };
1616341×
        let new_state = self
1617341×
            .store
1618341×
            .put_state(&StateObject::new(local_heads.clone()))?;
1619
        // A push that carries a policy re-attests the bookmark even when its
1620
        // state is unchanged, so the current attestation is always by a key
1621
        // the current policy authorizes (a revoked key's attestation would
1622
        // otherwise be refused by every later fetch).
1623341×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
16248×
            return Ok(vec![RefResult {
16258×
                name: bookmark,
16268×
                ok: true,
16278×
                reason: "already up to date".into(),
16288×
            }]);
1629333×
        }
1630385×
        for h in &remote_heads {
1631385×
            if !self.store.has(h) {
163272×
                return fail(format!(
1633
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
163472×
                    h.short(12)
1635
                ));
1636313×
            }
1637
        }
1638261×
        if !force {
1639261×
            let closure = self.closure_in_store(&local_heads)?;
1640291×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
16410×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1642261×
            }
16430×
        }
1644261×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1645261×
        let mut bundle = self.bundle_for(&to_send)?;
1646261×
        let key = self.secret_key()?.map(|(k, _)| k);
1647261×
        if let Some(key) = key {
1648
            // Seal this author's changes that carry no valid authenticator,
1649
            // and adopt anonymous ones (zero author, spec §14.4).
165072×
            let mut unsigned = Vec::new();
165172×
            for h in &to_send {
165268×
                let c = self.store.get_change(h)?;
165368×
                if (c.author == key || c.author.is_zero())
165465×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
165538×
                {
165638×
                    unsigned.push(*h);
165738×
                }
1658
            }
165972×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
166035×
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
166134×
                bundle.attests.push(sa);
1662
            }
166371×
            bundle = self.bundle_for(&to_send)?;
1664189×
        }
1665260×
        bundle.objects.push((
1666260×
            ObjectType::State,
1667260×
            StateObject::new(local_heads.clone()).encode(),
1668260×
        ));
1669260×
        let attestation = match key {
167071×
            Some(_) => Some(self.sign_attest(&Attest {
167171×
                repo: self.id()?,
167271×
                hlc: Hlc::now(),
167371×
                body: AttestBody::Ref {
167471×
                    name: bookmark.clone(),
167571×
                    old_state: remote_state,
167671×
                    new_state,
167771×
                    serial: next_serial(last_serial),
167871×
                },
16791×
            })?),
1680189×
            None => None,
1681
        };
1682259×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
168370×
            AttestBody::Ref { serial, .. } => Some(serial),
16840×
            _ => None,
168570×
        });
1686259×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1687
        // Tag states must be present on the remote: bundle their changes too.
1688259×
        for t in &tags_to_send {
16896×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
16906×
            let extra: Vec<ChangeHash> =
16916×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
16926×
            if !extra.is_empty() {
16930×
                let more = self.bundle_for(&extra)?;
16940×
                bundle.changes.extend(more.changes);
16950×
                bundle.hashes.extend(more.hashes);
16960×
                bundle.attests.extend(more.attests);
16970×
                bundle.objects.extend(more.objects);
16986×
            }
16996×
            bundle.objects.push((
17006×
                ObjectType::State,
17016×
                StateObject::new(t.heads.clone()).encode(),
17026×
            ));
1703
        }
1704259×
        if let Some(l) = &policy_to_send {
170516×
            let remote_serial = resp_policy_serial;
170616×
            bundle.policies = self
170716×
                .policy_history()?
170816×
                .into_iter()
170939×
                .filter(|sp| {
171039×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
171118×
                        && sp.policy.serial < l.policy.serial
171239×
                })
171316×
                .collect();
1714243×
        }
1715259×
        let results = remote.push(
1716259×
            bundle,
1717259×
            vec![RefUpdate {
1718259×
                name: bookmark.clone(),
1719259×
                old_state: remote_state,
1720259×
                new_state,
1721259×
                force,
1722259×
                attestation,
1723259×
            }],
1724259×
            policy_to_send,
1725259×
            tags_to_send,
17266×
        )?;
172716×
        if let (Some(serial), true) = (
1728253×
            sent_serial,
1729259×
            results.iter().any(|r| r.ok && r.name == "policy"),
1730
        ) {
173116×
            self.record_policy_serial(remote_name, serial)?;
1732237×
        }
1733269×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1734234×
            let mut view = op.view.clone();
1735234×
            view.remotes
1736234×
                .entry(remote_name.to_string())
1737234×
                .or_default()
1738234×
                .insert(bookmark.clone(), new_state);
1739234×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1740231×
            if let Some(s) = serial {
174154×
                self.record_serial(remote_name, &bookmark, s)?;
1742177×
            }
174319×
        }
1744248×
        Ok(results)
1745347×
    }
1746
1747
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1748
    /// bookmark set to the remote's, working copy checked out.
1749215×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1750215×
        Self::clone_with(url, dest, None, &[])
1751215×
    }
1752
1753
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1754
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1755
    /// unless a size is given, so out-of-scope binaries are never fetched).
1756223×
    pub fn clone_with(
1757223×
        url: &str,
1758223×
        dest: &Path,
1759223×
        max_blob: Option<u64>,
1760223×
        sparse: &[String],
1761223×
    ) -> Result<Repo> {
1762223×
        Self::clone_full(url, dest, max_blob, sparse, None)
1763223×
    }
1764
1765
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1766
    /// changes within `depth` steps of them; the rest is the boundary.
17671×
    pub fn clone_shallow(
17681×
        url: &str,
17691×
        dest: &Path,
17701×
        depth: u32,
17711×
        max_blob: Option<u64>,
17721×
        sparse: &[String],
17731×
    ) -> Result<Repo> {
17741×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
17751×
    }
1776
1777224×
    fn clone_full(
1778224×
        url: &str,
1779224×
        dest: &Path,
1780224×
        max_blob: Option<u64>,
1781224×
        sparse: &[String],
1782224×
        depth: Option<u32>,
1783224×
    ) -> Result<Repo> {
1784224×
        let options = crate::credentials::Credentials::user().options_for(url);
1785224×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1786224×
    }
1787
1788
    /// Clone a subrepo with the credentials the parent would use for its
1789
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1790
    /// subrepo: it finds the same ones again through its parent.
17915×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
17925×
        let options = self.credentials_for(url);
17935×
        Self::clone_using(url, dest, None, &[], None, &options)
17945×
    }
1795
1796
    /// The name of a remote of this repository on the same hub (scheme,
1797
    /// host and port) as `url`.
179813×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
179917×
        let origin = |u: &str| -> Option<String> {
180017×
            let (scheme, rest) = u.split_once("://")?;
18018×
            if !matches!(scheme, "http" | "https") {
18020×
                return None;
18038×
            }
18048×
            let host = rest.split('/').next()?;
18058×
            Some(format!(
18068×
                "{}://{}",
18078×
                scheme.to_ascii_lowercase(),
18088×
                host.to_ascii_lowercase()
18098×
            ))
181017×
        };
181113×
        let want = origin(url)?;
18124×
        self.config
18134×
            .remotes
18144×
            .iter()
18154×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
18164×
            .map(|(name, _)| name.clone())
181713×
    }
1818
1819
    /// The token and CA to reach `url` with: those of a remote of this
1820
    /// repository on the same hub (scheme, host and port), else the
1821
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
1822
    /// and enclosing checkouts', as a clone would use them.
182313×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
182413×
        match self.remote_on_same_hub(url) {
18251×
            Some(name) => RemoteOptions {
18261×
                repo_id: None,
18271×
                cache_dir: None,
18281×
                ..self.remote_options(&name)
18291×
            },
1830
            None => {
183112×
                let mut options = RemoteOptions::default();
183212×
                self.fill_credentials(url, &mut options);
183312×
                options
1834
            }
1835
        }
183613×
    }
1837
1838229×
    fn clone_using(
1839229×
        url: &str,
1840229×
        dest: &Path,
1841229×
        max_blob: Option<u64>,
1842229×
        sparse: &[String],
1843229×
        depth: Option<u32>,
1844229×
        options: &RemoteOptions,
1845229×
    ) -> Result<Repo> {
1846229×
        let remote = open_remote(url, options)?;
1847229×
        let id = remote.repo_id()?;
1848225×
        if id == crate::protocol::UNBOUND_ID {
18492×
            return fail(format!(
1850
                "{url} is empty and unbound: push a repository to it first"
1851
            ));
1852223×
        }
1853223×
        let mut repo = Repo::init_with_id(dest, id)?;
1854223×
        repo.config
1855223×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
1856223×
        if let Some(m) = max_blob {
18572×
            repo.config.set("filter.max-blob", &m.to_string())?;
1858221×
        } else if !sparse.is_empty() {
18591×
            repo.config.set("filter.max-blob", "0")?;
1860220×
        }
1861223×
        if !sparse.is_empty() {
18621×
            repo.config.set("filter.paths", &sparse.join(","))?;
1863222×
        }
1864223×
        repo.save_config()?;
1865223×
        if let Some(depth) = depth {
18661×
            repo.fetch_shallow("origin", depth)?;
1867
        } else {
1868222×
            repo.fetch("origin")?;
1869
        }
1870222×
        let (op_ref, op) = repo.head_op()?;
1871
        // The remote's default bookmark, else ours (main), else its only one.
1872222×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
1873
        // Asked of the remote as now configured, so a store-backed one
1874
        // answers from the mirror the fetch just filled.
1875222×
        let advertised = repo
1876222×
            .open_named_remote("origin")
1877222×
            .ok()
1878222×
            .and_then(|r| r.refs().ok())
1879222×
            .and_then(|r| r.default_bookmark);
1880222×
        let bookmark = advertised
1881222×
            .filter(|b| theirs.contains_key(b))
1882222×
            .or_else(|| {
18837×
                theirs
18847×
                    .contains_key(&repo.config.bookmark)
18857×
                    .then(|| repo.config.bookmark.clone())
18867×
            })
1887222×
            .or_else(|| {
18880×
                (theirs.len() == 1)
18890×
                    .then(|| theirs.keys().next().cloned())
18900×
                    .flatten()
18910×
            })
1892222×
            .unwrap_or_else(|| repo.config.bookmark.clone());
1893222×
        let initial = repo.config.bookmark.clone();
1894222×
        if bookmark != repo.config.bookmark {
18951×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
18961×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
18971×
            repo.config.bookmark = bookmark.clone();
1898221×
        }
1899222×
        if let Some(state) = theirs.get(&bookmark).copied() {
1900222×
            let heads = repo.store.get_state(&state)?.heads;
1901222×
            let mut view = op.view.clone();
1902
            // The empty bookmark `init` made goes when another is checked out.
1903222×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
19041×
                view.bookmarks.remove(&initial);
1905221×
            }
1906222×
            view.bookmarks.insert(bookmark, state);
1907222×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1908222×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
19090×
        }
1910222×
        Ok(repo)
1911229×
    }
1912
}
1913
1914
/// The serial of a reference's next attestation: one more than the last the
1915
/// remote reports, or, for a bookmark the remote does not have, the clock in
1916
/// milliseconds, so a bookmark created again after a deletion goes past the
1917
/// deletion's serial the remote keeps.
191871×
fn next_serial(last: Option<u64>) -> u64 {
191971×
    match last {
192045×
        Some(l) => l + 1,
192126×
        None => Hlc::now().wall_ms.max(1),
1922
    }
192371×
}