OXYGENHUB

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

1418 of 1590 lines run, 206 of 292 functions · run #259 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
501247×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
511247×
        self.oxy.join("attest").join(name_file(bookmark))
521247×
    }
53
54
    /// The latest reference attestation stored for a bookmark.
551173×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
561173×
        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
            }
68978×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
690×
            Err(e) => Err(e.into()),
70
        }
711173×
    }
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
78966×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
79966×
        let view = self.view()?;
80966×
        let mut out = Vec::new();
81988×
        for (name, state) in &view.bookmarks {
82988×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
83988×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
84104×
                AttestBody::Ref { serial, .. } => Some(serial),
850×
                _ => None,
86104×
            });
87988×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
88988×
            out.push(RemoteRef {
89988×
                name: name.clone(),
90988×
                state: *state,
91988×
                heads: self.store.get_state(state)?.heads,
92988×
                attestation,
93988×
                last_serial,
94
            });
95
        }
96966×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
97966×
        let history = self
98966×
            .policy_history()?
99966×
            .into_iter()
100966×
            .filter(|sp| {
10166×
                policy
10266×
                    .as_ref()
10366×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10466×
            })
105966×
            .collect();
106
        Ok(RefsResponse {
107966×
            refs: out,
108966×
            policy,
109966×
            tags: self.tag_refs()?,
110966×
            history,
111966×
            default_bookmark: Some(self.config.bookmark.clone()),
112
        })
113966×
    }
114
115
    /// Every change reachable from `heads` that is in the store.
1161267×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1171267×
        let mut seen = BTreeSet::new();
1181267×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1194474×
        while let Some(h) = stack.pop() {
1203207×
            if seen.contains(&h) || !self.store.has(&h) {
121962×
                continue;
1222245×
            }
1232245×
            seen.insert(h);
1242245×
            stack.extend(self.store.get_change_meta(&h)?.deps);
125
        }
1261267×
        Ok(seen)
1271267×
    }
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
1541832×
    fn shallow_path(&self) -> PathBuf {
1551832×
        self.oxy.join("shallow")
1561832×
    }
157
158
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1591829×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1601829×
        fs::read_to_string(self.shallow_path())
1611829×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1621829×
            .unwrap_or_default()
1631829×
    }
164
165174×
    pub fn is_shallow(&self) -> bool {
166174×
        !self.boundary().is_empty()
167174×
    }
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).
214725×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
215725×
        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.
218725×
        let boundary = self.boundary();
219725×
        let mut out = Vec::new();
220725×
        let mut done: BTreeSet<ChangeHash> = have.clone();
221725×
        done.extend(boundary.iter().copied());
222
        // Iterative post-order DFS.
2231160×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2243048×
        while let Some((h, expanded)) = stack.pop() {
2252323×
            if done.contains(&h) {
226375×
                continue;
2271948×
            }
2281948×
            if !self.store.has(&h) {
2290×
                return fail(format!("change {} is not in this repository", h.short(12)));
2301948×
            }
2311948×
            if expanded {
232974×
                done.insert(h);
233974×
                out.push(h);
234974×
                continue;
235974×
            }
236974×
            stack.push((h, true));
237974×
            for d in self.store.get_change_meta(&h)?.deps {
238694×
                if !done.contains(&d) {
239189×
                    stack.push((d, false));
240505×
                }
241
            }
242
        }
243725×
        Ok(out)
244725×
    }
245
246
    /// Bundle changes (in the given dependency order) with their signatures,
247
    /// seals, identities, blobs, chunks.
248352×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
249352×
        self.bundle_for_filtered(changes, None)
250352×
    }
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).
275398×
    pub fn bundle_for_filtered(
276398×
        &self,
277398×
        changes: &[ChangeHash],
278398×
        max_blob: Option<u64>,
279398×
    ) -> Result<Bundle> {
280398×
        self.bundle_of(changes, max_blob, false)
281398×
    }
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.
287309×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
288309×
        self.bundle_of(changes, max_blob, true)
289309×
    }
290
291707×
    fn bundle_of(
292707×
        &self,
293707×
        changes: &[ChangeHash],
294707×
        max_blob: Option<u64>,
295707×
        raw: bool,
296707×
    ) -> Result<Bundle> {
297707×
        let mut bundle = Bundle::default();
298707×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
299707×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3001084×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3011084×
            if !r.is_zero() && self.store.has(r) {
302263×
                objects.insert(*r);
303821×
            }
3041084×
        };
305973×
        for h in changes {
306
            // Raw: the stored bytes, and a skeleton for the rest.
307973×
            let (c, encoded) = if raw {
308486×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
309486×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3104942×
                for t in texts {
3114942×
                    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);
3154939×
                    }
316
                }
317486×
                (skel, Some(bytes))
318
            } else {
319487×
                (self.store.get_change(h)?, None)
320
            };
321973×
            let sigs = self.store.signatures(h)?;
322973×
            add_object(&c.author, &mut objects);
323973×
            for s in &sigs {
32436×
                add_object(&s.key, &mut objects);
32536×
            }
3265991×
            for e in &c.edits {
3275991×
                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
                    }
3415978×
                }
342
            }
343973×
            for s in self.store.seals_for(h)? {
34479×
                seals.insert(s);
34579×
            }
346973×
            match encoded {
347486×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
348487×
                None => {
349487×
                    bundle.changes.push((c, sigs));
350487×
                    bundle.hashes.push(*h);
351487×
                }
352
            }
353
        }
354707×
        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
        }
362707×
        for r in objects {
363170×
            let (ty, body) = self.store.get(&r)?;
364170×
            bundle.objects.push((ty, body));
365
        }
366707×
        Ok(bundle)
367707×
    }
368
369
    /// Store a bundle's contents. With `strict`, every change must
370
    /// authenticate (signature or seal by its author or a delegate).
371677×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
372677×
        self.import_bundle_inner(bundle, strict, false)
373677×
    }
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
381680×
    fn import_bundle_inner(
382680×
        &self,
383680×
        bundle: &Bundle,
384680×
        strict: bool,
385680×
        shallow: bool,
386680×
    ) -> Result<Vec<ChangeHash>> {
387680×
        let batch = self.store.begin_batch()?;
388680×
        let result = self.import_bundle_batched(bundle, strict, shallow);
389680×
        batch.finish()?;
390678×
        result
391680×
    }
392
393680×
    fn import_bundle_batched(
394680×
        &self,
395680×
        bundle: &Bundle,
396680×
        strict: bool,
397680×
        shallow: bool,
398680×
    ) -> Result<Vec<ChangeHash>> {
399680×
        for (ty, _) in &bundle.objects {
4000×
            if !matches!(
401446×
                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()));
409446×
            }
410
        }
411
        // All at once: in a large batch they are compressed on every core.
412680×
        let objects: Vec<(ObjectType, &[u8])> = bundle
413680×
            .objects
414680×
            .iter()
415680×
            .map(|(ty, body)| (*ty, body.as_slice()))
416680×
            .collect();
417680×
        self.store.put_many(&objects)?;
418680×
        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).
432680×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
433671×
            bundle.hashes.clone()
434
        } else {
4359×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
436
        };
437680×
        let raw_hashes: Vec<ChangeHash> = bundle
438680×
            .raw_changes
439680×
            .iter()
440680×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
441680×
            .collect();
442680×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
443680×
        let boundary = self.boundary();
444680×
        let mut imported = Vec::new();
445
        // Changes as stored: checked, then stored as they are, their text
446
        // blobs having come with the objects.
447680×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
448487×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
449487×
            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
            }
4594943×
            for t in texts {
4604943×
                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×
                    }
4684939×
                }
469
            }
470486×
            self.store.put(ObjectType::Change, bytes)?;
471486×
            for sig in sigs {
4724×
                self.store.put_signature(&h, sig)?;
473
            }
474486×
            imported.push(h);
475
        }
476679×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
477448×
            for d in &c.deps {
478276×
                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
                    ));
485273×
                }
486
            }
487445×
            let stored = self.store.put_change(c)?;
488445×
            if stored != h {
4890×
                return fail(format!(
490
                    "change {} is not the change the bundle names",
4910×
                    h.short(12)
492
                ));
493445×
            }
494445×
            for sig in sigs {
49525×
                self.store.put_signature(&h, sig)?;
496
            }
497445×
            imported.push(h);
498
        }
499676×
        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
            }
508648×
        }
509675×
        Ok(imported)
510680×
    }
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.
588258×
    pub fn receive_push(
589258×
        &self,
590258×
        bundle: Bundle,
591258×
        updates: Vec<RefUpdate>,
592258×
        policy: Option<SignedPolicy>,
593258×
        tags: Vec<crate::protocol::TagRef>,
594258×
    ) -> Result<Vec<RefResult>> {
595258×
        Ok(self
596258×
            .receive_push_report(bundle, updates, policy, tags)?
597
            .results)
598258×
    }
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).
603298×
    pub fn receive_push_report(
604298×
        &self,
605298×
        bundle: Bundle,
606298×
        updates: Vec<RefUpdate>,
607298×
        policy: Option<SignedPolicy>,
608298×
        tags: Vec<crate::protocol::TagRef>,
609298×
    ) -> Result<PushReport> {
610298×
        let mut report = PushReport::default();
611298×
        let results = &mut report.results;
612298×
        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
            }
637280×
        }
638296×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
639296×
        match self.import_bundle(&bundle, policy.is_some()) {
640293×
            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
        }
652293×
        let (op_ref, op) = self.head_op()?;
653293×
        let mut view = op.view.clone();
654293×
        let mut names = Vec::new();
655293×
        for u in updates {
656290×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
657290×
            let (ok, reason) = match outcome {
658265×
                Ok(()) => (true, String::new()),
65925×
                Err(e) => (false, e),
660
            };
661290×
            if ok {
662265×
                names.push(u.name.clone());
663265×
                let heads = self
664265×
                    .store
665265×
                    .get_state(&u.new_state)
666265×
                    .map(|s| s.heads)
667265×
                    .unwrap_or_default();
668265×
                report.updated.push(RefUpdated {
669265×
                    name: u.name.clone(),
670265×
                    old_state: u.old_state,
671265×
                    new_state: u.new_state,
672265×
                    heads,
673265×
                });
67425×
            }
675290×
            results.push(RefResult {
676290×
                name: u.name,
677290×
                ok,
678290×
                reason,
679290×
            });
680
        }
681293×
        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
        }
711293×
        if !names.is_empty() {
712265×
            self.record_op(
713265×
                &[op_ref],
714265×
                &format!("push received: {}", names.join(" ")),
715265×
                view,
7163×
            )?;
71728×
        }
718290×
        Ok(report)
719298×
    }
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
801290×
    fn apply_update(
802290×
        &self,
803290×
        view: &mut View,
804290×
        u: &RefUpdate,
805290×
        policy: Option<&crate::policy::Policy>,
806290×
    ) -> std::result::Result<(), String> {
807290×
        if u.name == "policy" {
8080×
            return Err(
8090×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
8100×
            );
811290×
        }
812290×
        let empty = self
813290×
            .store
814290×
            .put_state(&StateObject::new(vec![]))
815290×
            .map_err(|e| e.to_string())?;
816290×
        if u.new_state.is_zero() {
8173×
            return self.apply_deletion(view, u, policy);
818287×
        }
819287×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
820287×
        if current != u.old_state {
82110×
            return Err("stale: the remote bookmark has moved; pull first".into());
822277×
        }
823277×
        let new_state = self
824277×
            .store
825277×
            .get_state(&u.new_state)
826277×
            .map_err(|_| "new state object is missing".to_string())?;
827535×
        for h in &new_state.heads {
828535×
            if !self.store.has(h) {
8291×
                return Err(format!("head {} is missing", h.short(12)));
830534×
            }
831
        }
832276×
        if !u.force {
833275×
            let old_heads = self
834275×
                .store
835275×
                .get_state(&current)
836275×
                .map_err(|e| e.to_string())?
837
                .heads;
838275×
            let closure = self
839275×
                .closure_in_store(&new_state.heads)
840275×
                .map_err(|e| e.to_string())?;
841291×
            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×
                ));
846274×
            }
8471×
        }
848275×
        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)?;
875249×
        }
876269×
        if let Some(sa) = &u.attestation {
87773×
            self.record_update_attest(u, sa)?;
878196×
        }
879263×
        view.bookmarks.insert(u.name.clone(), u.new_state);
880263×
        Ok(())
881290×
    }
882
883
    // ------------------------------------------------------------ client side
884
885944×
    fn remote_url(&self, name: &str) -> Result<String> {
886944×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
8873×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
8883×
            RepoError::Msg(match names.as_slice() {
8893×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
8901×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
891
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
8921×
                    names.join(", "),
8931×
                    names[0],
8941×
                    names[0]
895
                ),
8960×
                _ => format!(
897
                    "no remote named {name:?}; this repository has {}",
8980×
                    names.join(", ")
899
                ),
900
            })
9013×
        })
902944×
    }
903
904
    /// Refuse a remote that is another repository. An **unbound** remote
905
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
906
    /// for pushes, which bind it to this repository's id (spec §16.1).
907703×
    fn check_remote_id(
908703×
        &self,
909703×
        remote: &dyn crate::protocol::Remote,
910703×
        remote_name: &str,
911703×
        allow_unbound: bool,
912703×
    ) -> Result<()> {
913703×
        let theirs = remote.repo_id()?;
914702×
        if theirs == self.id()? {
915682×
            return Ok(());
91620×
        }
91720×
        if theirs == crate::protocol::UNBOUND_ID {
91817×
            if allow_unbound {
91916×
                return Ok(());
9201×
            }
9211×
            return fail(format!(
922
                "remote {remote_name:?} is empty and unbound: push to it first"
923
            ));
9243×
        }
9253×
        fail(format!(
926
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
927
        ))
928703×
    }
929
930
    /// Credentials and trust for a remote: `remote.<name>.token` and
931
    /// `remote.<name>.ca`, else the defaults for its URL
932
    /// ([`Repo::fill_credentials`]).
933960×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
934960×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
935960×
        let mut options = RemoteOptions {
936960×
            repo_id: self.id().ok(),
937960×
            token: self.config.remote_tokens.get(name).cloned(),
938960×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
939960×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
940960×
        };
941960×
        self.fill_credentials(&url, &mut options);
942960×
        options
943960×
    }
944
945
    /// The user's credential store (`credentials.toml` beside the user
946
    /// configuration file).
947977×
    pub fn credentials(&self) -> crate::credentials::Credentials {
948977×
        crate::credentials::Credentials::at(
949977×
            self.user_config
950977×
                .parent()
951977×
                .map(Path::to_path_buf)
952977×
                .unwrap_or_else(default_home),
953
        )
954977×
    }
955
956
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
957
    /// then the user's credential store for its hub, then a remote on the
958
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
959978×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
960978×
        if options.token.is_some() && options.ca.is_some() {
9611×
            return;
962977×
        }
963977×
        let stored = self.credentials().options_for(url);
964977×
        options.token = options.token.take().or(stored.token);
965977×
        options.ca = options.ca.take().or(stored.ca);
966977×
        if options.token.is_some() && options.ca.is_some() {
9670×
            return;
968977×
        }
969977×
        let Some(hub) = crate::credentials::hub_of(url) else {
970846×
            return;
971
        };
972131×
        let mut at = self.root.parent();
973522×
        while let Some(dir) = at {
974391×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
9750×
                break;
976
            };
977391×
            for (key, remote_url) in &cfg {
9785×
                let Some(name) = key
9795×
                    .strip_prefix("remote.")
9805×
                    .and_then(|k| k.strip_suffix(".url"))
981
                else {
9822×
                    continue;
983
                };
9843×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
9851×
                    continue;
9862×
                }
9872×
                if options.token.is_none() {
9882×
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
9892×
                }
9902×
                if options.ca.is_none() {
9912×
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
9922×
                }
993
            }
994391×
            if options.token.is_some() && options.ca.is_some() {
9950×
                return;
996391×
            }
997391×
            at = dir.parent();
998
        }
999978×
    }
1000
1001
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1002
    /// no changes and no reference updates, which the receiver stores.
10030×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
10040×
        let remote = self.open_named_remote(remote_name)?;
10050×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
10060×
        let mut bundle = Bundle::default();
10070×
        for r in seals {
10080×
            let attest = self.store.get_attest(r)?;
10090×
            let sigs = self.store.signatures(r)?;
10100×
            bundle
10110×
                .attests
10120×
                .push(crate::protocol::SignedAttest { attest, sigs });
1013
        }
10140×
        let results = remote.push(bundle, vec![], None, vec![])?;
10150×
        if let Some(r) = results.iter().find(|r| !r.ok) {
10160×
            return fail(format!("{}: {}", r.name, r.reason));
10170×
        }
10180×
        Ok(())
10190×
    }
1020
1021
    /// The remote whose URL starts with `base` (a hub), if configured.
10223×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
10233×
        let base = base.trim_end_matches('/');
10243×
        self.config
10253×
            .remotes
10263×
            .iter()
10273×
            .find(|(_, url)| url.trim_end_matches('/') == base)
10283×
            .map(|(name, _)| name.clone())
10293×
    }
1030
1031
    /// Open a remote by name or, failing that, by URL with the default
1032
    /// credentials (see [`Repo::credentials_for`]).
10330×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
10340×
        if let Some(name) = self.remote_for_url(url) {
10350×
            return Ok((name.clone(), self.open_named_remote(&name)?));
10360×
        }
10370×
        let options = RemoteOptions {
10380×
            repo_id: self.id().ok(),
10390×
            ..self.credentials_for(url)
10400×
        };
10410×
        Ok((url.to_string(), open_remote(url, &options)?))
10420×
    }
1043
1044
    /// Credentials for a URL: those of the configured remote with that
1045
    /// URL, else the environment's.
10463×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
10473×
        match self.remote_for_url(url) {
10483×
            Some(name) => self.remote_options(&name),
10490×
            None => RemoteOptions {
10500×
                repo_id: self.id().ok(),
10510×
                ..self.credentials_for(url)
10520×
            },
1053
        }
10543×
    }
1055
1056944×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1057944×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1058944×
    }
1059
106092×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
106192×
        self.oxy
106292×
            .join("remotes")
106392×
            .join(remote)
106492×
            .join(format!("{bookmark}.serial"))
106592×
    }
1066
106719×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
106819×
        fs::read_to_string(self.serial_path(remote, bookmark))
106919×
            .ok()
107019×
            .and_then(|s| s.trim().parse().ok())
107119×
    }
1072
107373×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
107473×
        let p = self.serial_path(remote, bookmark);
107573×
        fs::create_dir_all(p.parent().unwrap())?;
107673×
        write_atomic(&p, serial.to_string().as_bytes())
107773×
    }
1078
1079368×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1080368×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1081368×
    }
1082
1083
    /// The highest policy serial `remote` has ever presented.
1084344×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1085344×
        fs::read_to_string(self.policy_serial_path(remote))
1086344×
            .ok()
1087344×
            .and_then(|s| s.trim().parse().ok())
1088344×
    }
1089
109024×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
109124×
        let p = self.policy_serial_path(remote);
109224×
        fs::create_dir_all(p.parent().unwrap())?;
109324×
        write_atomic(&p, serial.to_string().as_bytes())
109424×
    }
1095
109627×
    fn lazy_dir(&self) -> PathBuf {
109727×
        self.oxy.join("lazy")
109827×
    }
1099
1100
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
11014×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
11024×
        fs::create_dir_all(self.lazy_dir())?;
11034×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
11044×
    }
1105
1106
    /// Which remote promised an absent blob, if any.
110715×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
110815×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
110915×
            .ok()
111015×
            .map(|s| s.trim().to_string())
111115×
    }
1112
1113
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
11144×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
11154×
        let Some(remote_name) = self.lazy_remote(blob) else {
11160×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1117
        };
11184×
        let remote = self.open_named_remote(&remote_name)?;
11194×
        let objects = remote.objects(&[*blob])?;
11209×
        for (ty, body) in objects {
11219×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
11229×
                self.store.put(ty, &body)?;
11230×
            }
1124
        }
11254×
        if !self.store.has(blob) {
11260×
            return fail(format!(
1127
                "{remote_name} did not send blob {}",
11280×
                blob.short(12)
1129
            ));
11304×
        }
11314×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
11324×
        Ok(())
11334×
    }
1134
1135
    /// After importing from `remote`, record every blob the changes reference
1136
    /// that the store lacks as lazily available from that remote.
11374×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
11384×
        let mut n = 0;
11394×
        for h in changes {
11404×
            let c = self.store.get_change(h)?;
114113×
            for e in &c.edits {
114213×
                if let Edit::Replace { old, new, .. } = e {
11436×
                    for b in [old, new].into_iter().flatten() {
11446×
                        if !self.store.has(b) {
11454×
                            self.register_lazy(b, remote)?;
11464×
                            n += 1;
11472×
                        }
1148
                    }
11497×
                }
1150
            }
1151
        }
11524×
        Ok(n)
11534×
    }
1154
1155
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1156344×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1157344×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1158466×
        for st in view
1159344×
            .bookmarks
1160344×
            .values()
1161344×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1162
        {
1163466×
            if let Ok(s) = self.store.get_state(st) {
1164466×
                have.extend(s.heads);
1165466×
            }
1166
        }
1167344×
        have.extend(view.workspaces.values().copied());
1168344×
        Ok(have.into_iter().collect())
1169344×
    }
1170
1171
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1172350×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1173350×
        let remote = self.open_named_remote(remote_name)?;
1174347×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1175345×
        let resp = remote.refs()?;
1176
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1177
        // and signed by roots we trust, or on first contact. A remote that
1178
        // once presented a policy may never present none or an older one:
1179
        // that is a downgrade. A remote that never presented one is
1180
        // unverified, and this fetch is checked only as far as possible.
1181344×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1182344×
        let seen = self.remote_policy_serial(remote_name);
1183344×
        let mut unverified = false;
1184344×
        match &resp.policy {
11858×
            Some(sp) => {
11868×
                if seen.is_some_and(|s| sp.policy.serial < s) {
11870×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
11888×
                }
11895×
                match &local_policy {
11905×
                    Some(l) if sp.policy.serial < l.serial => {}
11915×
                    Some(l) if sp.policy.serial == l.serial => {
11921×
                        if sp.policy.hash() != l.hash() {
11930×
                            return fail(format!(
1194
                                "{remote_name} presents a different policy with the same serial {}",
1195
                                l.serial
1196
                            ));
11971×
                        }
1198
                    }
1199
                    _ => {
12007×
                        self.adopt_policy_chain(
12017×
                            &resp.history,
12027×
                            sp,
12037×
                            &format!("oxy fetch {remote_name}"),
1204
                        )
12057×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1206
                    }
1207
                }
12088×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1209
            }
1210
            None => {
1211336×
                if seen.is_some() {
12120×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1213336×
                }
1214336×
                unverified = true;
1215
            }
1216
        }
1217344×
        let policy = if unverified {
1218336×
            None
1219
        } else {
12208×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1221
        };
1222344×
        let (op_ref, op) = self.head_op()?;
1223344×
        let mut view = op.view.clone();
1224344×
        let have = self.known_heads(&view)?;
1225344×
        let mut report = Vec::new();
1226344×
        let max_blob = self.config.max_blob;
1227351×
        for r in resp.refs {
1228351×
            let needed = {
1229351×
                let _t = crate::timing::phase("fetch: negotiate");
1230351×
                remote.negotiate(&have, &r.heads)?
1231
            };
1232351×
            let bundle = {
1233351×
                let _t = crate::timing::phase("fetch: bundle");
1234351×
                remote.fetch(&needed, max_blob)?
1235
            };
1236
            // Changes are not individually re-verified here: the bookmark's
1237
            // attestation (checked below) binds its whole state, and the
1238
            // receiver of the push verified the added changes at that time.
1239351×
            let imported = {
1240351×
                let _t = crate::timing::phase("fetch: import");
1241351×
                self.import_bundle(&bundle, false)?
1242
            };
1243351×
            if max_blob.is_some() {
12444×
                self.register_missing_blobs(&imported, remote_name)?;
1245347×
            }
1246494×
            for h in &r.heads {
1247494×
                if !self.store.has(h) {
12480×
                    return fail(format!("remote did not send head {}", h.short(12)));
1249494×
                }
1250
            }
1251351×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1252351×
            if state != r.state {
12530×
                return fail(format!(
1254
                    "remote state {} does not match its heads",
12550×
                    r.state.short(12)
1256
                ));
1257351×
            }
1258351×
            if let Some(p) = &policy {
12598×
                let Some(sa) = &r.attestation else {
12600×
                    return fail(format!(
1261
                        "{remote_name}/{} has no attestation, which its policy requires",
1262
                        r.name
1263
                    ));
1264
                };
12658×
                let signer = sa
12668×
                    .sigs
12678×
                    .first()
12688×
                    .map(|s| s.key)
12698×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
12708×
                if !p.authorizes(&signer, &r.name)
12710×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1272
                {
12730×
                    return fail(format!(
1274
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1275
                        r.name,
12760×
                        signer.short(12)
1277
                    ));
12788×
                }
1279343×
            }
1280351×
            if let Some(sa) = &r.attestation {
1281
                let AttestBody::Ref {
128219×
                    old_state,
128319×
                    new_state,
1284
                    ..
128519×
                } = &sa.attest.body
1286
                else {
12870×
                    return fail("remote sent a non-ref attestation for a bookmark");
1288
                };
128919×
                let (old_state, new_state) = (*old_state, *new_state);
129019×
                let serial = self
129119×
                    .check_ref_attest(
129219×
                        sa,
129319×
                        &r.name,
129419×
                        &old_state,
129519×
                        &new_state,
129619×
                        self.last_seen_serial(remote_name, &r.name),
1297
                        true,
1298
                    )
129919×
                    .map_err(|e| {
13000×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
13010×
                    })?;
130219×
                if new_state != r.state {
13030×
                    return fail(format!(
1304
                        "attestation for {}/{} does not cover its current state",
1305
                        remote_name, r.name
1306
                    ));
130719×
                }
130819×
                let ar = self.store.put_attest(&sa.attest)?;
130919×
                for sig in &sa.sigs {
131019×
                    self.store.put_signature(&ar, sig)?;
1311
                }
131219×
                self.record_serial(remote_name, &r.name, serial)?;
1313332×
            }
1314351×
            view.remotes
1315351×
                .entry(remote_name.to_string())
1316351×
                .or_default()
1317351×
                .insert(r.name.clone(), state);
1318351×
            report.push((r.name, r.heads, imported.len()));
1319
        }
1320344×
        let mut new_tags = 0;
1321344×
        for t in &resp.tags {
132210×
            if view.tags.contains_key(&t.name) {
13234×
                continue;
13246×
            }
1325
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
13266×
            let missing: Vec<ChangeHash> = t
13276×
                .heads
13286×
                .iter()
13296×
                .filter(|h| !self.store.has(h))
13306×
                .copied()
13316×
                .collect();
13326×
            if !missing.is_empty() {
13330×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
13340×
                let bundle = remote.fetch(&needed, max_blob)?;
13350×
                self.import_bundle(&bundle, false)?;
13366×
            }
13376×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
13386×
            self.adopt_tag(&mut view, t, policy.as_ref())
13396×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
13406×
            new_tags += 1;
1341
        }
1342344×
        if view != op.view {
1343334×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
134410×
        }
1345344×
        let _ = self.run_hook(
1346344×
            "post-fetch",
1347344×
            &format!(
1348
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1349344×
                json_str(remote_name),
1350351×
                json_array(report.iter().map(|(n, heads, _)| format!(
1351
                    "{{\"name\":{},\"heads\":{}}}",
1352351×
                    json_str(n),
1353494×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1354
                )))
1355
            ),
1356
        );
1357344×
        Ok(FetchReport {
1358344×
            refs: report,
1359344×
            unverified,
1360344×
            new_tags,
1361344×
        })
1362350×
    }
1363
1364
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1365
    /// the changes within `depth` steps of its heads, and the boundary below.
13661×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
13671×
        let remote = self.open_named_remote(remote_name)?;
13681×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13691×
        let resp = remote.refs()?;
13701×
        let bookmark = self.config.bookmark.clone();
13711×
        if let Some(sp) = &resp.policy {
13720×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
13730×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
13740×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
13751×
        }
13761×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
13770×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1378
        };
13791×
        if r.heads.is_empty() {
13800×
            return Ok(0);
13811×
        }
1382
        // Base: the remote's checkpoint of exactly these heads.
13831×
        let cp_bundle = remote.checkpoint(&r.heads)?;
13841×
        let mut cp_ref = None;
13853×
        for (ty, body) in &cp_bundle.objects {
13863×
            let put = self.store.put(*ty, body)?;
13873×
            if *ty == ObjectType::Checkpoint {
13881×
                cp_ref = Some(put);
13892×
            }
1390
        }
13911×
        let Some(cp_ref) = cp_ref else {
13920×
            return fail(format!("{remote_name} sent no checkpoint"));
1393
        };
13941×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1395
        // History window.
13961×
        let wanted = remote.shallow(&r.heads, depth)?;
13971×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
13981×
        let imported = self.import_bundle_shallow(&bundle, false)?;
13991×
        if self.config.max_blob.is_some() {
14000×
            self.register_missing_blobs(&imported, remote_name)?;
14011×
        }
14021×
        self.refresh_boundary(&imported)?;
14031×
        if let Some(sa) = &r.attestation {
14040×
            let ar = self.store.put_attest(&sa.attest)?;
14050×
            for sig in &sa.sigs {
14060×
                self.store.put_signature(&ar, sig)?;
1407
            }
14080×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
14090×
                self.record_serial(remote_name, &r.name, serial)?;
14100×
            }
14111×
        }
14121×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
14131×
        let (op_ref, op) = self.head_op()?;
14141×
        let mut view = op.view.clone();
14151×
        view.remotes
14161×
            .entry(remote_name.to_string())
14171×
            .or_default()
14181×
            .insert(r.name.clone(), state);
14191×
        self.record_op(
14201×
            &[op_ref],
14211×
            &format!("oxy fetch {remote_name} --depth {depth}"),
14221×
            view,
14230×
        )?;
14241×
        Ok(imported.len())
14251×
    }
1426
1427
    /// Fetch, then take the union of the local bookmark's state with the
1428
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1429105×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1430105×
        let _wc = self.lock_working_copy()?;
1431105×
        self.fetch(remote_name)?;
1432102×
        let (op_ref, op) = self.head_op()?;
1433102×
        let current = self.config.bookmark.clone();
1434102×
        let mut local_current = self.heads_of(&op.view, &current)?;
1435102×
        local_current.sort();
1436102×
        let mut view = op.view.clone();
1437102×
        let mut current_heads = local_current.clone();
1438102×
        let mut changed = false;
1439102×
        let mut others = Vec::new();
1440102×
        let tracked = op
1441102×
            .view
1442102×
            .remotes
1443102×
            .get(remote_name)
1444102×
            .cloned()
1445102×
            .unwrap_or_default();
1446106×
        for (name, remote_state) in tracked {
1447
            // Every local bookmark tracks the remote's of the same name;
1448
            // the current one may be new here.
1449106×
            let local_state = op.view.bookmarks.get(&name).copied();
1450106×
            if local_state.is_none() && name != current {
14510×
                continue;
1452106×
            }
1453106×
            if local_state == Some(remote_state) {
14548×
                continue;
145598×
            }
145698×
            let local = self.heads_of(&op.view, &name)?;
145798×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1458119×
            if remote_heads.iter().all(|h| local.contains(h)) {
14590×
                continue;
146098×
            }
146198×
            let mut all = local.clone();
146298×
            all.extend(remote_heads);
146398×
            let st = self.load_state_history(&all)?;
146498×
            let mut heads = st.maximal(&all);
146598×
            heads.sort();
146698×
            let mut sorted_local = local;
146798×
            sorted_local.sort();
146898×
            if heads == sorted_local {
14691×
                continue;
147097×
            }
147197×
            view.bookmarks.insert(
147297×
                name.clone(),
147397×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1474
            );
147597×
            if name == current {
147695×
                changed = true;
147795×
                current_heads = heads;
147895×
            } else {
14792×
                others.push(name);
14802×
            }
1481
        }
1482102×
        if changed || !others.is_empty() {
148396×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
14846×
        }
1485
        // The working copy follows its bookmark whenever nothing would be
1486
        // lost, also when this pull brought nothing new but it had been
1487
        // left behind (oxygen#89).
1488102×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1489
        Ok(PullReport {
1490102×
            heads: if changed {
149195×
                current_heads
1492
            } else {
14937×
                local_current
1494
            },
1495102×
            changed,
1496102×
            checked_out,
1497102×
            others,
1498
        })
1499105×
    }
1500
1501
    /// How many changes the working copy's bookmark has that its base
1502
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1503
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1504
    /// the bookmark or holds changes the bookmark lacks. History is read
1505
    /// only when the base and the bookmark's heads differ (oxygen#89).
15067×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
15077×
        let (_, wc) = self.working_copy()?;
15087×
        let mut base = wc.deps.clone();
15097×
        base.sort();
15107×
        let mut heads = self.bookmark_heads()?;
15117×
        heads.sort();
15127×
        if base == heads || heads.is_empty() {
15136×
            return Ok(None);
15141×
        }
15151×
        let state = self.load_state_history(&heads)?;
15161×
        if !base.iter().all(|h| state.contains(h)) {
15170×
            return Ok(None);
15181×
        }
15191×
        let had = if base.is_empty() {
15200×
            0
1521
        } else {
15221×
            self.load_state_history(&base)?.len()
1523
        };
15241×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
15257×
    }
1526
1527
    /// Bring the working copy to `heads`, the state of its bookmark
1528
    /// `bookmark`, when nothing would be lost: its base is part of that
1529
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1530
    /// with uncommitted work, the work comes along when the new changes
1531
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1532
    /// it followed only from exactly the bookmark's old heads, so a working
1533
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1534
    /// or a pull from another workspace) never caught up, and nothing said
1535
    /// so (oxygen#74, #89). Returns whether it moved.
1536102×
    pub fn follow_bookmark(
1537102×
        &self,
1538102×
        heads: &[ChangeHash],
1539102×
        bookmark: &str,
1540102×
        command: &str,
1541102×
    ) -> Result<bool> {
1542102×
        let snap = self.snapshot(command)?;
1543102×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1544102×
        let mut base = snap.base.maximal(&snap.wc.deps);
1545102×
        base.sort();
1546102×
        let mut target = heads.to_vec();
1547102×
        target.sort();
1548102×
        if base == target {
15496×
            return Ok(false);
155096×
        }
155196×
        let state = self.load_state_history(heads)?;
1552178×
        if !base.iter().all(|h| state.contains(h)) {
1553
            // The working copy holds changes the bookmark lacks: not ours to move.
15540×
            return Ok(false);
155596×
        }
155696×
        if clean {
155796×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
155896×
            Ok(true)
1559
        } else {
15600×
            Ok(self
15610×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
15620×
                .is_ok())
1563
        }
1564102×
    }
1565
1566
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1567
    /// changes and attesting the reference when a key is available.
1568
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1569
    /// state, attested when we have an identity. The local bookmark, if
1570
    /// any, is kept; only the remote-tracking entry goes.
15715×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
15725×
        let remote = self.open_named_remote(remote_name)?;
15735×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
15745×
        let resp = remote.refs()?;
15757×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
15761×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1577
        };
15784×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
15790×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
15804×
        }
15814×
        let attestation = match self.secret_key()? {
15822×
            Some(_) => Some(self.sign_attest(&Attest {
15832×
                repo: self.id()?,
15842×
                hlc: Hlc::now(),
15852×
                body: AttestBody::Ref {
15862×
                    name: bookmark.to_string(),
15872×
                    old_state: r.state,
15882×
                    new_state: ObjectRef::ZERO,
15892×
                    serial: r.last_serial.unwrap_or(0) + 1,
15902×
                },
15910×
            })?),
15922×
            None => None,
1593
        };
15944×
        let results = remote.push(
15954×
            Bundle::default(),
15964×
            vec![RefUpdate {
15974×
                name: bookmark.to_string(),
15984×
                old_state: r.state,
15994×
                new_state: ObjectRef::ZERO,
16004×
                force: true,
16014×
                attestation,
16024×
            }],
16034×
            None,
16044×
            vec![],
16050×
        )?;
16064×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
16072×
            let (op_ref, op) = self.head_op()?;
16082×
            let mut view = op.view.clone();
16092×
            if let Some(m) = view.remotes.get_mut(remote_name) {
16102×
                m.remove(bookmark);
16112×
            }
16122×
            self.record_op(
16132×
                &[op_ref],
16142×
                &format!("oxy push {remote_name} --delete {bookmark}"),
16152×
                view,
16160×
            )?;
16172×
        }
16184×
        Ok(results)
16195×
    }
1620
1621343×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1622343×
        let bookmark = self.config.bookmark.clone();
1623343×
        self.push_bookmark(remote_name, &bookmark, force)
1624343×
    }
1625
1626
    /// `push` for a named bookmark (`oxy push -b NAME`).
1627351×
    pub fn push_bookmark(
1628351×
        &self,
1629351×
        remote_name: &str,
1630351×
        bookmark: &str,
1631351×
        force: bool,
1632351×
    ) -> Result<Vec<RefResult>> {
1633351×
        let (op_ref, op) = self.head_op()?;
1634351×
        if !op.view.bookmarks.contains_key(bookmark) {
16350×
            return fail(format!("no bookmark {bookmark}"));
1636351×
        }
1637351×
        let bookmark = bookmark.to_string();
1638351×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1639
        // pre-push hook: may veto before the remote is contacted.
1640351×
        self.run_hook(
1641351×
            "pre-push",
1642351×
            &format!(
1643
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1644351×
                json_str(remote_name),
1645351×
                json_str(&bookmark),
1646723×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1647
            ),
16481×
        )?;
1649350×
        let remote = self.open_named_remote(remote_name)?;
1650350×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1651347×
        let resp = remote.refs()?;
1652347×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1653347×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1654347×
        let policy_to_send = match (&local_policy, &resp.policy) {
165517×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
16567×
            (Some(l), None) => Some(l.clone()),
16578×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
16581×
                return fail(format!(
1659
                    "{remote_name} has a newer policy (serial {}); fetch first",
1660
                    r.policy.serial
1661
                ));
1662
            }
1663330×
            _ => None,
1664
        };
1665346×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1666346×
        if remote_has_policy && self.secret_key()?.is_none() {
16671×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1668345×
        }
1669345×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1670345×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1671345×
            .tag_refs()?
1672345×
            .into_iter()
1673345×
            .filter(|t| !remote_tags.contains(&t.name))
1674345×
            .collect();
1675345×
        let refs = resp.refs;
1676345×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1677345×
        let (remote_state, remote_heads, last_serial) =
1678345×
            match refs.iter().find(|r| r.name == bookmark) {
1679329×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
168016×
                None => (empty, vec![], None),
1681
            };
1682345×
        let new_state = self
1683345×
            .store
1684345×
            .put_state(&StateObject::new(local_heads.clone()))?;
1685
        // A push that carries a policy re-attests the bookmark even when its
1686
        // state is unchanged, so the current attestation is always by a key
1687
        // the current policy authorizes (a revoked key's attestation would
1688
        // otherwise be refused by every later fetch).
1689345×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
169010×
            return Ok(vec![RefResult {
169110×
                name: bookmark,
169210×
                ok: true,
169310×
                reason: "already up to date".into(),
169410×
            }]);
1695335×
        }
1696366×
        for h in &remote_heads {
1697366×
            if !self.store.has(h) {
169868×
                return fail(format!(
1699
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
170068×
                    h.short(12)
1701
                ));
1702298×
            }
1703
        }
1704267×
        if !force {
1705267×
            let closure = self.closure_in_store(&local_heads)?;
1706286×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
17070×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1708267×
            }
17090×
        }
1710267×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1711267×
        let mut bundle = self.bundle_for(&to_send)?;
1712267×
        let key = self.secret_key()?.map(|(k, _)| k);
1713267×
        if let Some(key) = key {
1714
            // Seal this author's changes that carry no valid authenticator,
1715
            // and adopt anonymous ones (zero author, spec §14.4).
171672×
            let mut unsigned = Vec::new();
171772×
            for h in &to_send {
171868×
                let c = self.store.get_change(h)?;
171968×
                if (c.author == key || c.author.is_zero())
172065×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
172138×
                {
172238×
                    unsigned.push(*h);
172338×
                }
1724
            }
172572×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
172635×
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
172734×
                bundle.attests.push(sa);
1728
            }
172971×
            bundle = self.bundle_for(&to_send)?;
1730195×
        }
1731266×
        bundle.objects.push((
1732266×
            ObjectType::State,
1733266×
            StateObject::new(local_heads.clone()).encode(),
1734266×
        ));
1735266×
        let attestation = match key {
173671×
            Some(_) => Some(self.sign_attest(&Attest {
173771×
                repo: self.id()?,
173871×
                hlc: Hlc::now(),
173971×
                body: AttestBody::Ref {
174071×
                    name: bookmark.clone(),
174171×
                    old_state: remote_state,
174271×
                    new_state,
174371×
                    serial: next_serial(last_serial),
174471×
                },
17451×
            })?),
1746195×
            None => None,
1747
        };
1748265×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
174970×
            AttestBody::Ref { serial, .. } => Some(serial),
17500×
            _ => None,
175170×
        });
1752265×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1753
        // Tag states must be present on the remote: bundle their changes too.
1754265×
        for t in &tags_to_send {
17556×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
17566×
            let extra: Vec<ChangeHash> =
17576×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
17586×
            if !extra.is_empty() {
17590×
                let more = self.bundle_for(&extra)?;
17600×
                bundle.changes.extend(more.changes);
17610×
                bundle.hashes.extend(more.hashes);
17620×
                bundle.attests.extend(more.attests);
17630×
                bundle.objects.extend(more.objects);
17646×
            }
17656×
            bundle.objects.push((
17666×
                ObjectType::State,
17676×
                StateObject::new(t.heads.clone()).encode(),
17686×
            ));
1769
        }
1770265×
        if let Some(l) = &policy_to_send {
177116×
            let remote_serial = resp_policy_serial;
177216×
            bundle.policies = self
177316×
                .policy_history()?
177416×
                .into_iter()
177539×
                .filter(|sp| {
177639×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
177718×
                        && sp.policy.serial < l.policy.serial
177839×
                })
177916×
                .collect();
1780249×
        }
1781265×
        let results = remote.push(
1782265×
            bundle,
1783265×
            vec![RefUpdate {
1784265×
                name: bookmark.clone(),
1785265×
                old_state: remote_state,
1786265×
                new_state,
1787265×
                force,
1788265×
                attestation,
1789265×
            }],
1790265×
            policy_to_send,
1791265×
            tags_to_send,
17926×
        )?;
179316×
        if let (Some(serial), true) = (
1794259×
            sent_serial,
1795265×
            results.iter().any(|r| r.ok && r.name == "policy"),
1796
        ) {
179716×
            self.record_policy_serial(remote_name, serial)?;
1798243×
        }
1799275×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1800240×
            let mut view = op.view.clone();
1801240×
            view.remotes
1802240×
                .entry(remote_name.to_string())
1803240×
                .or_default()
1804240×
                .insert(bookmark.clone(), new_state);
1805240×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1806237×
            if let Some(s) = serial {
180754×
                self.record_serial(remote_name, &bookmark, s)?;
1808183×
            }
180919×
        }
1810254×
        Ok(results)
1811351×
    }
1812
1813
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1814
    /// bookmark set to the remote's, working copy checked out.
1815222×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1816222×
        Self::clone_with(url, dest, None, &[])
1817222×
    }
1818
1819
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1820
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1821
    /// unless a size is given, so out-of-scope binaries are never fetched).
1822230×
    pub fn clone_with(
1823230×
        url: &str,
1824230×
        dest: &Path,
1825230×
        max_blob: Option<u64>,
1826230×
        sparse: &[String],
1827230×
    ) -> Result<Repo> {
1828230×
        Self::clone_full(url, dest, max_blob, sparse, None)
1829230×
    }
1830
1831
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1832
    /// changes within `depth` steps of them; the rest is the boundary.
18331×
    pub fn clone_shallow(
18341×
        url: &str,
18351×
        dest: &Path,
18361×
        depth: u32,
18371×
        max_blob: Option<u64>,
18381×
        sparse: &[String],
18391×
    ) -> Result<Repo> {
18401×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
18411×
    }
1842
1843231×
    fn clone_full(
1844231×
        url: &str,
1845231×
        dest: &Path,
1846231×
        max_blob: Option<u64>,
1847231×
        sparse: &[String],
1848231×
        depth: Option<u32>,
1849231×
    ) -> Result<Repo> {
1850231×
        let options = crate::credentials::Credentials::user().options_for(url);
1851231×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1852231×
    }
1853
1854
    /// Clone a subrepo with the credentials the parent would use for its
1855
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1856
    /// subrepo: it finds the same ones again through its parent.
18578×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
18588×
        let options = self.credentials_for(url);
18598×
        Self::clone_using(url, dest, None, &[], None, &options)
18608×
    }
1861
1862
    /// The name of a remote of this repository on the same hub (scheme,
1863
    /// host and port) as `url`.
186419×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
186523×
        let origin = |u: &str| -> Option<String> {
186623×
            let (scheme, rest) = u.split_once("://")?;
18678×
            if !matches!(scheme, "http" | "https") {
18680×
                return None;
18698×
            }
18708×
            let host = rest.split('/').next()?;
18718×
            Some(format!(
18728×
                "{}://{}",
18738×
                scheme.to_ascii_lowercase(),
18748×
                host.to_ascii_lowercase()
18758×
            ))
187623×
        };
187719×
        let want = origin(url)?;
18784×
        self.config
18794×
            .remotes
18804×
            .iter()
18814×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
18824×
            .map(|(name, _)| name.clone())
188319×
    }
1884
1885
    /// The token and CA to reach `url` with: those of a remote of this
1886
    /// repository on the same hub (scheme, host and port), else the
1887
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
1888
    /// and enclosing checkouts', as a clone would use them.
188919×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
189019×
        match self.remote_on_same_hub(url) {
18911×
            Some(name) => RemoteOptions {
18921×
                repo_id: None,
18931×
                cache_dir: None,
18941×
                ..self.remote_options(&name)
18951×
            },
1896
            None => {
189718×
                let mut options = RemoteOptions::default();
189818×
                self.fill_credentials(url, &mut options);
189918×
                options
1900
            }
1901
        }
190219×
    }
1903
1904239×
    fn clone_using(
1905239×
        url: &str,
1906239×
        dest: &Path,
1907239×
        max_blob: Option<u64>,
1908239×
        sparse: &[String],
1909239×
        depth: Option<u32>,
1910239×
        options: &RemoteOptions,
1911239×
    ) -> Result<Repo> {
1912239×
        let remote = open_remote(url, options)?;
1913239×
        let id = remote.repo_id()?;
1914235×
        if id == crate::protocol::UNBOUND_ID {
19152×
            return fail(format!(
1916
                "{url} is empty and unbound: push a repository to it first"
1917
            ));
1918233×
        }
1919233×
        let mut repo = Repo::init_with_id(dest, id)?;
1920233×
        repo.config
1921233×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
1922233×
        if let Some(m) = max_blob {
19232×
            repo.config.set("filter.max-blob", &m.to_string())?;
1924231×
        } else if !sparse.is_empty() {
19251×
            repo.config.set("filter.max-blob", "0")?;
1926230×
        }
1927233×
        if !sparse.is_empty() {
19281×
            repo.config.set("filter.paths", &sparse.join(","))?;
1929232×
        }
1930233×
        repo.save_config()?;
1931233×
        if let Some(depth) = depth {
19321×
            repo.fetch_shallow("origin", depth)?;
1933
        } else {
1934232×
            repo.fetch("origin")?;
1935
        }
1936232×
        let (op_ref, op) = repo.head_op()?;
1937
        // The remote's default bookmark, else ours (main), else its only one.
1938232×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
1939
        // Asked of the remote as now configured, so a store-backed one
1940
        // answers from the mirror the fetch just filled.
1941232×
        let advertised = repo
1942232×
            .open_named_remote("origin")
1943232×
            .ok()
1944232×
            .and_then(|r| r.refs().ok())
1945232×
            .and_then(|r| r.default_bookmark);
1946232×
        let bookmark = advertised
1947232×
            .filter(|b| theirs.contains_key(b))
1948232×
            .or_else(|| {
19497×
                theirs
19507×
                    .contains_key(&repo.config.bookmark)
19517×
                    .then(|| repo.config.bookmark.clone())
19527×
            })
1953232×
            .or_else(|| {
19540×
                (theirs.len() == 1)
19550×
                    .then(|| theirs.keys().next().cloned())
19560×
                    .flatten()
19570×
            })
1958232×
            .unwrap_or_else(|| repo.config.bookmark.clone());
1959232×
        let initial = repo.config.bookmark.clone();
1960232×
        if bookmark != repo.config.bookmark {
19611×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
19621×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
19631×
            repo.config.bookmark = bookmark.clone();
1964231×
        }
1965232×
        if let Some(state) = theirs.get(&bookmark).copied() {
1966232×
            let heads = repo.store.get_state(&state)?.heads;
1967232×
            let mut view = op.view.clone();
1968
            // The empty bookmark `init` made goes when another is checked out.
1969232×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
19701×
                view.bookmarks.remove(&initial);
1971231×
            }
1972232×
            view.bookmarks.insert(bookmark, state);
1973232×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1974232×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
19750×
        }
1976232×
        Ok(repo)
1977239×
    }
1978
}
1979
1980
/// The serial of a reference's next attestation: one more than the last the
1981
/// remote reports, or, for a bookmark the remote does not have, the clock in
1982
/// milliseconds, so a bookmark created again after a deletion goes past the
1983
/// deletion's serial the remote keeps.
198471×
fn next_serial(last: Option<u64>) -> u64 {
198571×
    match last {
198645×
        Some(l) => l + 1,
198726×
        None => Hlc::now().wall_ms.max(1),
1988
    }
198971×
}