OXYGENHUB

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

2006 of 2227 lines run, 318 of 420 functions · run #368 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::tags::TagCheck;
4
use super::*;
5
6
/// What a push did, for hosts (hub spec §6.12).
7
#[derive(Clone, Debug, Default)]
8
pub struct PushReport {
9
    pub results: Vec<RefResult>,
10
    /// Accepted reference updates, in request order.
11
    pub updated: Vec<RefUpdated>,
12
    /// Changes this push stored that were not already present.
13
    pub imported: Vec<ChangeHash>,
14
}
15
16
#[derive(Clone, Debug)]
17
pub struct RefUpdated {
18
    pub name: String,
19
    pub old_state: ObjectRef,
20
    pub new_state: ObjectRef,
21
    pub heads: Vec<ChangeHash>,
22
}
23
24
/// What a fetch brought in.
25
#[derive(Debug, Clone, PartialEq, Eq, Default)]
26
pub struct FetchReport {
27
    /// Bookmark name, its heads, and how many changes were new.
28
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
29
    /// Tags adopted from the remote.
30
    pub new_tags: usize,
31
    /// Tags the remote withdrew, and so withdrawn here (oxygenhub#301).
32
    pub withdrawn_tags: Vec<String>,
33
    /// The remote has never presented a policy, so nothing was verified
34
    /// against one (spec §14.5: warn loudly).
35
    pub unverified: bool,
36
    /// What checking the host's transparency log found short of a fork
37
    /// (spec §14.8): attestations not logged yet, a log that could not be
38
    /// read. A fork fails the fetch instead.
39
    pub log_notes: Vec<String>,
40
    /// Bookmarks left as they were because their attestation could not be
41
    /// verified (its signer unknown here, or its signature bad), each with
42
    /// why (oxygenhub#266). The current bookmark is never skipped: its
43
    /// fetch fails instead.
44
    pub skipped: Vec<(String, String)>,
45
}
46
47
#[derive(Debug, Clone, PartialEq, Eq)]
48
pub struct PullReport {
49
    /// The current bookmark's heads after the pull.
50
    pub heads: Vec<ChangeHash>,
51
    /// Whether the current bookmark changed.
52
    pub changed: bool,
53
    pub checked_out: bool,
54
    /// Other bookmarks the pull moved: each local bookmark tracks the
55
    /// remote's of the same name.
56
    pub others: Vec<String>,
57
    /// What the fetch left as it was ([`FetchReport::skipped`]).
58
    pub skipped: Vec<(String, String)>,
59
}
60
61
/// The result a push of objects alone reports (a batch of a long history):
62
/// not a reference.
63
pub const OBJECTS_RESULT: &str = "objects";
64
65
impl Repo {
66
    // ------------------------------------------------------------ serving (spec §16)
67
681857×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
691857×
        self.oxy.join("attest").join(name_file(bookmark))
701857×
    }
71
72
    /// The latest reference attestation stored for a bookmark.
731438×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
741438×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
75345×
            Ok(h) => {
76345×
                let r = ObjectRef::from_hex(h.trim())
77345×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
78
                Ok(Some((
79345×
                    r,
80
                    SignedAttest {
81345×
                        attest: self.store.get_attest(&r)?,
82345×
                        sigs: self.store.signatures(&r)?,
83
                    },
84
                )))
85
            }
861093×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
870×
            Err(e) => Err(e.into()),
88
        }
891438×
    }
90
91109×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
92109×
        fs::create_dir_all(self.oxy.join("attest"))?;
93109×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
94109×
    }
95
961149×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
971149×
        let view = self.view()?;
981149×
        let mut out = Vec::new();
991202×
        for (name, state) in &view.bookmarks {
1001202×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
1011202×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
102230×
                AttestBody::Ref { serial, .. } => Some(serial),
1030×
                _ => None,
104230×
            });
1051202×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1061202×
            let accepted = match &attestation {
107219×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
108983×
                None => None,
109
            };
1101202×
            out.push(RemoteRef {
1111202×
                name: name.clone(),
1121202×
                state: *state,
1131202×
                heads: self.store.get_state(state)?.heads,
1141202×
                attestation,
1151202×
                last_serial,
1161202×
                accepted,
1171202×
                logged: None,
1181202×
                integration: vec![],
119
            });
120
        }
1211149×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1221149×
        let history = self
1231149×
            .policy_history()?
1241149×
            .into_iter()
1251149×
            .filter(|sp| {
126221×
                policy
127221×
                    .as_ref()
128221×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
129221×
            })
1301149×
            .collect();
131
        Ok(RefsResponse {
1321149×
            refs: out,
1331149×
            policy,
1341149×
            tags: self.tag_refs()?,
1351149×
            history,
1361149×
            default_bookmark: Some(self.config.bookmark.clone()),
1371149×
            log: None,
1381149×
            witnesses: vec![],
1391149×
            withdrawn: self.withdrawn_refs()?,
140
        })
1411149×
    }
142
143
    /// Every change reachable from `heads` that is in the store.
1441562×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1451562×
        let mut seen = BTreeSet::new();
1461562×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1475276×
        while let Some(h) = stack.pop() {
1483714×
            if seen.contains(&h) || !self.store.has(&h) {
1491082×
                continue;
1502632×
            }
1512632×
            seen.insert(h);
1522632×
            stack.extend(self.store.get_change_meta(&h)?.deps);
153
        }
1541562×
        Ok(seen)
1551562×
    }
156
157
    /// The changes within `depth` dependency steps of `heads` (spec §17),
158
    /// nearest first; depth 1 is the heads themselves.
1593×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1603×
        let mut out = Vec::new();
1613×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1623×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1633×
        for _ in 0..depth.max(1) {
1648×
            let mut next = Vec::new();
16512×
            for h in layer {
16612×
                if !seen.insert(h) || !self.store.has(&h) {
1672×
                    continue;
16810×
                }
16910×
                let c = self.store.get_change(&h)?;
17010×
                next.extend(c.deps.iter().copied());
17110×
                out.push(h);
172
            }
1738×
            if next.is_empty() {
1741×
                break;
1757×
            }
1767×
            layer = next;
177
        }
1783×
        out.reverse();
1793×
        Ok(out)
1803×
    }
181
1822199×
    fn shallow_path(&self) -> PathBuf {
1832199×
        self.oxy.join("shallow")
1842199×
    }
185
186
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1872196×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1882196×
        fs::read_to_string(self.shallow_path())
1892196×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1902196×
            .unwrap_or_default()
1912196×
    }
192
193190×
    pub fn is_shallow(&self) -> bool {
194190×
        !self.boundary().is_empty()
195190×
    }
196
1973×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1983×
        if boundary.is_empty() {
1991×
            let _ = fs::remove_file(self.shallow_path());
2001×
            return Ok(());
2012×
        }
2022×
        let text: String = boundary
2032×
            .iter()
2042×
            .map(|h| format!("{}\n", h.to_hex()))
2052×
            .collect();
2062×
        write_atomic(&self.shallow_path(), text.as_bytes())
2073×
    }
208
209
    /// Recompute the boundary from what is stored: every dependency of a
210
    /// stored change that is not itself stored.
2113×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2123×
        let mut boundary = self.boundary();
2133×
        boundary.retain(|h| !self.store.has(h));
21410×
        for h in imported {
21513×
            for d in self.store.get_change_meta(h)?.deps {
21613×
                if !self.store.has(&d) {
2172×
                    boundary.insert(d);
21811×
                }
219
            }
220
        }
2213×
        self.write_boundary(&boundary)
2223×
    }
223
224
    /// Fetch `depth` more levels of history below the shallow boundary.
2252×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2262×
        let boundary = self.boundary();
2272×
        if boundary.is_empty() {
2280×
            return Ok(0);
2292×
        }
2302×
        let remote = self.open_named_remote(remote_name)?;
2312×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2322×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2332×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2342×
        if self.config.max_blob.is_some() {
2350×
            self.register_missing_blobs(&imported, remote_name)?;
2362×
        }
2372×
        self.refresh_boundary(&imported)?;
2382×
        Ok(imported.len())
2392×
    }
240
241
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
242908×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
243908×
        let have = self.closure_in_store(have)?;
244
        // In a shallow repository the walk stops at the boundary, whose
245
        // changes the remote is assumed to hold.
246908×
        let boundary = self.boundary();
247908×
        let mut out = Vec::new();
248908×
        let mut done: BTreeSet<ChangeHash> = have.clone();
249908×
        done.extend(boundary.iter().copied());
250
        // Iterative post-order DFS.
2511396×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2523699×
        while let Some((h, expanded)) = stack.pop() {
2532791×
            if done.contains(&h) {
254479×
                continue;
2552312×
            }
2562312×
            if !self.store.has(&h) {
2570×
                return fail(format!("change {} is not in this repository", h.short(12)));
2582312×
            }
2592312×
            if expanded {
2601156×
                done.insert(h);
2611156×
                out.push(h);
2621156×
                continue;
2631156×
            }
2641156×
            stack.push((h, true));
2651156×
            for d in self.store.get_change_meta(&h)?.deps {
266769×
                if !done.contains(&d) {
267239×
                    stack.push((d, false));
268530×
                }
269
            }
270
        }
271908×
        Ok(out)
272908×
    }
273
274
    /// Bundle changes (in the given dependency order) with their signatures,
275
    /// seals, identities, blobs, chunks.
276345×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
277345×
        self.bundle_of(changes, None, false, false)
278345×
    }
279
280
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2814×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2824×
        let mut out = Vec::new();
2834×
        for r in refs {
2844×
            let (ty, body) = match self.store.get(r) {
2854×
                Ok(x) => x,
2860×
                Err(StoreError::NotFound(_)) => continue,
2870×
                Err(e) => return Err(e.into()),
288
            };
2894×
            if ty == ObjectType::Blob {
2905×
                for c in Blob::decode(&body)?.chunks {
2915×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2925×
                        out.push((cty, cb));
2935×
                    }
294
                }
2950×
            }
2964×
            out.push((ty, body));
297
        }
2984×
        Ok(out)
2994×
    }
300
301
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
302
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
303
    ///
304
    /// This is what a server answers a fetch with, so it also carries what
305
    /// verifies the attestations it serves beside it (see
306
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
30756×
    pub fn bundle_for_filtered(
30856×
        &self,
30956×
        changes: &[ChangeHash],
31056×
        max_blob: Option<u64>,
31156×
    ) -> Result<Bundle> {
31256×
        self.bundle_of(changes, max_blob, false, true)
31356×
    }
314
315
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
316
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
317
    /// with their text blobs and chunks among the objects, so neither side
318
    /// decodes or encodes their text.
319387×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
320387×
        self.bundle_of(changes, max_blob, true, true)
321387×
    }
322
323
    /// The keys that signed the attestations this repository serves with
324
    /// its references: each bookmark's latest and each tag's. A fetch
325
    /// bundle carries their identities and certificates (spec §16.2), so a
326
    /// client can check an attestation whose signer signed none of the
327
    /// changes it receives, a delegate or a short-lived key that only
328
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
329
    /// list per reference, computed once per operation head and kept
330
    /// (every bookmark move and tag is an operation): a client sends one
331
    /// fetch per bookmark, and on a bucket store each signature list is a
332
    /// LIST request, so recomputing per fetch cost metalgear2 (145
333
    /// bookmarks) 14 s a fetch.
334443×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
335
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
336
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
337443×
        let key = (self.oxy.clone(), self.head_op()?.0);
338443×
        if let Some(keys) = SERVED
339443×
            .lock()
340443×
            .unwrap_or_else(|p| p.into_inner())
341443×
            .as_ref()
342443×
            .and_then(|m| m.get(&key))
343
        {
344143×
            return Ok(keys.clone());
345300×
        }
346300×
        let keys = self.attest_signers_now()?;
347300×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
348300×
        let map = served.get_or_insert_with(Default::default);
349
        // One entry per repository: an older operation head is never asked
350
        // for again once a newer one is current.
3516186×
        map.retain(|(oxy, _), _| *oxy != key.0);
352300×
        if map.len() >= 1024 {
3530×
            map.clear();
354300×
        }
355300×
        map.insert(key, keys.clone());
356300×
        Ok(keys)
357443×
    }
358
359300×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
360300×
        let view = self.view()?;
361300×
        let pointers = view
362300×
            .bookmarks
363300×
            .keys()
364310×
            .map(|b| self.ref_attest_path(b))
365300×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
366300×
        let mut keys = BTreeSet::new();
367332×
        for p in pointers {
368332×
            let Ok(text) = fs::read_to_string(&p) else {
369269×
                continue;
370
            };
37163×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3720×
                continue;
373
            };
37463×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
375
        }
376300×
        Ok(keys)
377300×
    }
378
379
    /// `serving`: a fetch's answer, which carries the identities and
380
    /// certificates of [`Repo::served_attest_signers`] too.
381788×
    fn bundle_of(
382788×
        &self,
383788×
        changes: &[ChangeHash],
384788×
        max_blob: Option<u64>,
385788×
        raw: bool,
386788×
        serving: bool,
387788×
    ) -> Result<Bundle> {
388788×
        let mut bundle = Bundle::default();
389788×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
390788×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3911328×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3921328×
            if !r.is_zero() && self.store.has(r) {
393384×
                objects.insert(*r);
394944×
            }
3951328×
        };
3961070×
        for h in changes {
397
            // Raw: the stored bytes, and a skeleton for the rest.
3981070×
            let (c, encoded) = if raw {
399584×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
400584×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
4015073×
                for t in texts {
4025073×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
4033×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4043×
                        objects.insert(r);
4053×
                        objects.extend(blob.chunks);
4065070×
                    }
407
                }
408584×
                (skel, Some(bytes))
409
            } else {
410486×
                (self.store.get_change(h)?, None)
411
            };
4121070×
            let sigs = self.store.signatures(h)?;
4131070×
            add_object(&c.author, &mut objects);
4141070×
            for s in &sigs {
41537×
                add_object(&s.key, &mut objects);
41637×
            }
4176145×
            for e in &c.edits {
4186145×
                if let Edit::Replace { old, new, .. } = e {
41914×
                    for b in [old, new].into_iter().flatten() {
42014×
                        if self.store.has(b) {
42114×
                            if let Ok(blob) =
42214×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
423
                            {
42414×
                                if max_blob.is_some_and(|m| blob.length > m) {
4254×
                                    continue;
42610×
                                }
42710×
                                objects.insert(*b);
42810×
                                objects.extend(blob.chunks.iter().copied());
4290×
                            }
4300×
                        }
431
                    }
4326133×
                }
433
            }
4341070×
            for s in self.store.seals_for(h)? {
435110×
                seals.insert(s);
436110×
            }
4371070×
            match encoded {
438584×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
439486×
                None => {
440486×
                    bundle.changes.push((c, sigs));
441486×
                    bundle.hashes.push(*h);
442486×
                }
443
            }
444
        }
445788×
        for r in seals {
446105×
            let attest = self.store.get_attest(&r)?;
447105×
            let sigs = self.store.signatures(&r)?;
448105×
            for s in &sigs {
449105×
                add_object(&s.key, &mut objects);
450105×
            }
451105×
            bundle.attests.push(SignedAttest { attest, sigs });
452
        }
453788×
        let signers: Vec<KeyId> = if serving {
454443×
            let signers = self.served_attest_signers()?;
455443×
            for k in &signers {
456116×
                add_object(k, &mut objects);
457116×
            }
458443×
            signers.into_iter().collect()
459
        } else {
460345×
            Vec::new()
461
        };
462788×
        for r in objects {
463225×
            let (ty, body) = self.store.get(&r)?;
464225×
            bundle.objects.push((ty, body));
465
        }
466788×
        self.attach_certificates_for(&mut bundle, &signers)?;
467788×
        Ok(bundle)
468788×
    }
469
470
    /// Add the certificates of short-lived keys that signed what `bundle`
471
    /// carries, and their issuers' identities, so a receiver can tell who
472
    /// they stand for (spec §14.7). `also` names more signers (a reference
473
    /// attestation sent beside the bundle).
474915×
    pub(crate) fn attach_certificates_for(
475915×
        &self,
476915×
        bundle: &mut Bundle,
477915×
        also: &[KeyId],
478915×
    ) -> Result<()> {
479915×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
480915×
        keys.extend(
481915×
            bundle
482915×
                .changes
483915×
                .iter()
484915×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
485
        );
486915×
        keys.extend(
487915×
            bundle
488915×
                .raw_changes
489915×
                .iter()
490915×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
491
        );
492915×
        keys.extend(
493915×
            bundle
494915×
                .attests
495915×
                .iter()
496915×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
497
        );
498915×
        for k in keys {
499350×
            let Some(r) = self.store.certificate_of(&k)? else {
500301×
                continue;
501
            };
50249×
            let cert = self.store.get_certificate(&r)?;
50349×
            if bundle
50449×
                .certificates
50549×
                .iter()
50649×
                .any(|c| c.cert.hash() == cert.cert.hash())
507
            {
50812×
                continue;
50937×
            }
510
            // An agent's certificate brings its grant's signer too, so the
511
            // receiver can check the grant (oxygen#134).
51237×
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
51381×
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
51481×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
51580×
                    if !bundle
51680×
                        .objects
51780×
                        .iter()
518149×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
51935×
                    {
52035×
                        bundle.objects.push((ObjectType::Identity, body));
52145×
                    }
5221×
                }
523
            }
52437×
            bundle.certificates.push(cert);
525
        }
526915×
        Ok(())
527915×
    }
528
529
    /// Keep the certificates a bundle brings once each verifies with the
530
    /// identity of the issuer it names; one that does not refuses the bundle.
531832×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
532832×
        for c in certs {
53336×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5340×
                RepoError::Msg(format!(
5350×
                    "a certificate names issuer {}, whose identity did not come with it",
5360×
                    c.cert.issuer.short(12)
5370×
                ))
5380×
            })?;
53936×
            c.verify(&issuer)
54036×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
54136×
            self.store.put_identity(&c.cert.key)?;
54236×
            self.store.put_certificate(c)?;
543
        }
544832×
        Ok(())
545832×
    }
546
547
    /// A signer authorized for `reference` by what an issuer certified it
548
    /// as (spec §14.7): a short-lived key with a kept certificate that
549
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
550
    /// signer did not choose) and names a subject the policy grants.
55157×
    pub(crate) fn certified_authorized(
55257×
        &self,
55357×
        p: &crate::policy::Policy,
55457×
        signer: &KeyId,
55557×
        reference: &str,
55657×
        scope: Scope,
55757×
        at_ms: u64,
55857×
    ) -> bool {
55957×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5605×
            return false;
561
        };
56252×
        let Ok(c) = self.store.get_certificate(&r) else {
5630×
            return false;
564
        };
56552×
        let Some(issuer) = p
56652×
            .identity(&c.cert.issuer)
56752×
            .cloned()
56852×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
569
        else {
5700×
            return false;
571
        };
57252×
        c.verify(&issuer).is_ok()
57352×
            && c.cert.key_id() == *signer
57452×
            && c.cert.covers(scope, at_ms)
57542×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
57657×
    }
577
578
    /// Store a bundle's contents. With `strict`, every change must
579
    /// authenticate (signature or seal by its author or a delegate).
580829×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
581829×
        self.import_bundle_inner(bundle, strict, false)
582829×
    }
583
584
    /// Like `import_bundle`, accepting changes whose dependencies are absent
585
    /// (they join the shallow boundary).
5863×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5873×
        self.import_bundle_inner(bundle, strict, true)
5883×
    }
589
590832×
    fn import_bundle_inner(
591832×
        &self,
592832×
        bundle: &Bundle,
593832×
        strict: bool,
594832×
        shallow: bool,
595832×
    ) -> Result<Vec<ChangeHash>> {
596832×
        let batch = self.store.begin_batch()?;
597832×
        let result = self.import_bundle_batched(bundle, strict, shallow);
598832×
        batch.finish()?;
599830×
        result
600832×
    }
601
602832×
    fn import_bundle_batched(
603832×
        &self,
604832×
        bundle: &Bundle,
605832×
        strict: bool,
606832×
        shallow: bool,
607832×
    ) -> Result<Vec<ChangeHash>> {
608832×
        for (ty, _) in &bundle.objects {
6090×
            if !matches!(
610700×
                ty,
611
                ObjectType::Chunk
612
                    | ObjectType::Blob
613
                    | ObjectType::Identity
614
                    | ObjectType::State
615
                    | ObjectType::Checkpoint
616
            ) {
6170×
                return fail(format!("bundle may not carry {} objects", ty.name()));
618700×
            }
619
        }
620
        // All at once: in a large batch they are compressed on every core.
621832×
        let objects: Vec<(ObjectType, &[u8])> = bundle
622832×
            .objects
623832×
            .iter()
624832×
            .map(|(ty, body)| (*ty, body.as_slice()))
625832×
            .collect();
626832×
        self.store.put_many(&objects)?;
627832×
        self.adopt_certificates(&bundle.certificates)?;
628832×
        for sa in &bundle.attests {
629108×
            let r = self.store.put_attest(&sa.attest)?;
630108×
            for sig in &sa.sigs {
631108×
                self.store.put_signature(&r, sig)?;
632
            }
633108×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
634113×
                for h in hashes {
635113×
                    self.store.index_seal(h, &r)?;
636
                }
6370×
            }
638
        }
639
        // Each change's hash: from the bundle when its maker knew it, else
640
        // worked out once (for a change adding a whole tree, hashing is
641
        // chunking all its text).
642832×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
643823×
            bundle.hashes.clone()
644
        } else {
6459×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
646
        };
647832×
        let raw_hashes: Vec<ChangeHash> = bundle
648832×
            .raw_changes
649832×
            .iter()
650832×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
651832×
            .collect();
652832×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
653832×
        let boundary = self.boundary();
654832×
        let mut imported = Vec::new();
655
        // Changes as stored: checked, then stored as they are, their text
656
        // blobs having come with the objects.
657832×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
658585×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
659585×
            for d in &skel.deps {
660422×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
661
                {
6620×
                    return fail(format!(
663
                        "change {} depends on {}, which is neither stored nor in the bundle",
6640×
                        h.short(12),
6650×
                        d.short(12)
666
                    ));
667422×
                }
668
            }
6695074×
            for t in texts {
6705074×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6714×
                    if !self.store.has(&r) {
6721×
                        return fail(format!(
673
                            "change {} came without its text blob {}",
6741×
                            h.short(12),
6751×
                            r.short(12)
676
                        ));
6773×
                    }
6785070×
                }
679
            }
680584×
            self.store.put(ObjectType::Change, bytes)?;
681584×
            for sig in sigs {
68213×
                self.store.put_signature(&h, sig)?;
683
            }
684584×
            imported.push(h);
685
        }
686831×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
687513×
            for d in &c.deps {
688301×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
689
                {
6903×
                    return fail(format!(
691
                        "change {} depends on {}, which is neither stored nor in the bundle",
6923×
                        h.short(12),
6933×
                        d.short(12)
694
                    ));
695298×
                }
696
            }
697510×
            let stored = self.store.put_change(c)?;
698510×
            if stored != h {
6990×
                return fail(format!(
700
                    "change {} is not the change the bundle names",
7010×
                    h.short(12)
702
                ));
703510×
            }
704510×
            for sig in sigs {
70533×
                self.store.put_signature(&h, sig)?;
706
            }
707510×
            imported.push(h);
708
        }
709828×
        if strict {
71067×
            for h in &imported {
71139×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7124×
                    return fail(format!(
713
                        "change {} is not authenticated by its author",
7144×
                        h.short(12)
715
                    ));
71635×
                }
717
            }
718761×
        }
719824×
        Ok(imported)
720832×
    }
721
722
    /// Verify a reference attestation against an update it claims to describe.
723
    /// `allow_equal` lets a client re-read the attestation it already has; a
724
    /// server receiving a push requires a strictly greater serial.
725
    /// A reference attestation signed by a delegate of an identity the
726
    /// rule lists is authorized as that identity (spec §14.5): the identity
727
    /// named the delegate with the `refs` scope, still in force at `at_ms`
728
    /// (the attestation's wall time), and the policy names the identity.
729
    /// Revoked keys authorize nothing either way.
73072×
    pub(crate) fn delegate_authorized(
73172×
        &self,
73272×
        p: &crate::policy::Policy,
73372×
        signer: &KeyId,
73472×
        reference: &str,
73572×
        at_ms: u64,
73672×
    ) -> bool {
73772×
        if p.is_revoked(signer) {
7381×
            return false;
73971×
        }
74071×
        let Some(rule) = p.rule_for(reference) else {
7410×
            return false;
742
        };
74372×
        rule.keys.iter().any(|k| {
74472×
            !p.is_revoked(k)
74572×
                && p.identity(k)
74672×
                    .cloned()
74772×
                    .or_else(|| self.store.get_identity(k).ok())
74872×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
74972×
        })
75072×
    }
751
752
    /// A lasting attestation (a tag) signed by a key the policy has since
753
    /// rotated away from (spec §14.2) is authorized as the key that
754
    /// succeeded it: a key the rule lists reaches the signer through
755
    /// `previous` links, and the attestation is dated (`at_ms`) before the
756
    /// signer's successor was made, so a superseded key makes nothing new.
757
    /// Revoked keys authorize nothing.
75827×
    pub(crate) fn predecessor_authorized(
75927×
        &self,
76027×
        p: &crate::policy::Policy,
76127×
        signer: &KeyId,
76227×
        reference: &str,
76327×
        at_ms: u64,
76427×
    ) -> bool {
76527×
        if p.is_revoked(signer) {
7660×
            return false;
76727×
        }
76827×
        let Some(rule) = p.rule_for(reference) else {
7690×
            return false;
770
        };
77128×
        let identity = |k: &KeyId| {
77228×
            p.identity(k)
77328×
                .cloned()
77428×
                .or_else(|| self.store.get_identity(k).ok())
77528×
        };
77627×
        rule.keys.iter().any(|k| {
77727×
            if p.is_revoked(k) {
7780×
                return false;
77927×
            }
78027×
            let mut cur = identity(k);
78127×
            for _ in 0..32 {
78228×
                let Some(id) = cur else {
7830×
                    return false;
784
                };
7851×
                match id.previous {
7866×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7871×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
78822×
                    _ => return false,
789
                }
790
            }
7910×
            false
79227×
        })
79327×
    }
794
795106×
    fn check_ref_attest(
796106×
        &self,
797106×
        sa: &SignedAttest,
798106×
        name: &str,
799106×
        old_state: &ObjectRef,
800106×
        new_state: &ObjectRef,
801106×
        last_serial: Option<u64>,
802106×
        allow_equal: bool,
803106×
    ) -> std::result::Result<u64, String> {
804104×
        let serial =
805106×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
806104×
        self.verify_attest_signature(sa)?;
807104×
        Ok(serial)
808106×
    }
809
810
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
811
    /// attestation describes this update of this repository with a serial
812
    /// past the last seen.
813179×
    fn check_ref_attest_body(
814179×
        &self,
815179×
        sa: &SignedAttest,
816179×
        name: &str,
817179×
        old_state: &ObjectRef,
818179×
        new_state: &ObjectRef,
819179×
        last_serial: Option<u64>,
820179×
        allow_equal: bool,
821179×
    ) -> std::result::Result<u64, String> {
822
        let AttestBody::Ref {
823179×
            name: n,
824179×
            old_state: o,
825179×
            new_state: nw,
826179×
            serial,
827179×
        } = &sa.attest.body
828
        else {
8290×
            return Err("attestation is not a ref attestation".into());
830
        };
831179×
        if n != name || o != old_state || nw != new_state {
8321×
            return Err("attestation does not describe this update".into());
833178×
        }
834178×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8350×
            return Err("attestation is for a different repository".into());
836178×
        }
837178×
        if let Some(last) = last_serial {
83893×
            if *serial < last || (*serial == last && !allow_equal) {
8391×
                return Err(format!(
8401×
                    "attestation serial {serial} is not greater than the last seen {last}"
8411×
                ));
84292×
            }
84385×
        }
844177×
        Ok(*serial)
845179×
    }
846
847
    /// An attestation's first signature verifies with its signer's
848
    /// identity, which must be stored here.
849177×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
850177×
        let r = sa.attest.hash();
851177×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
852177×
        let id = self
853177×
            .store
854177×
            .get_identity(&sig.key)
855177×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
856171×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
857177×
    }
858
859
    /// Accept a push (spec §16.4). Without a trust policy every repository
860
    /// is unverified, so unsigned changes and unattested updates are accepted;
861
    /// attestations that are present must still be valid. With a policy,
862
    /// every change and update is checked against it. A newer policy in the
863
    /// push is applied first when it is signed by the current roots.
864316×
    pub fn receive_push(
865316×
        &self,
866316×
        bundle: Bundle,
867316×
        updates: Vec<RefUpdate>,
868316×
        policy: Option<SignedPolicy>,
869316×
        tags: Vec<crate::protocol::TagRef>,
870316×
    ) -> Result<Vec<RefResult>> {
871316×
        Ok(self
872316×
            .receive_push_report(bundle, updates, policy, tags)?
873
            .results)
874316×
    }
875
876
    /// `receive_push` with what a host wants to log: each accepted
877
    /// reference's old and new state and heads, and the changes this push
878
    /// stored (hub spec §6.12).
879365×
    pub fn receive_push_report(
880365×
        &self,
881365×
        bundle: Bundle,
882365×
        updates: Vec<RefUpdate>,
883365×
        policy: Option<SignedPolicy>,
884365×
        tags: Vec<crate::protocol::TagRef>,
885365×
    ) -> Result<PushReport> {
886
        // Updates are checked against the head as it is now, not as this
887
        // handle first read it (oxygenhub#249): another push may have
888
        // landed since.
889365×
        self.refresh()?;
890365×
        let mut report = PushReport::default();
891365×
        let results = &mut report.results;
892365×
        if let Some(sp) = policy {
89336×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
89434×
                Ok(()) => {
89534×
                    results.push(RefResult {
89634×
                        name: "policy".into(),
89734×
                        ok: true,
89834×
                        reason: format!("serial {}", sp.policy.serial),
89934×
                    });
90034×
                }
9012×
                Err(e) => {
9022×
                    results.push(RefResult {
9032×
                        name: "policy".into(),
9042×
                        ok: false,
9052×
                        reason: e,
9062×
                    });
9072×
                    for u in updates {
9080×
                        results.push(RefResult {
9090×
                            name: u.name,
9100×
                            ok: false,
9110×
                            reason: "policy update was rejected".into(),
9120×
                        });
9130×
                    }
9142×
                    return Ok(report);
915
                }
916
            }
917329×
        }
918363×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
919
        // A push of objects alone (one batch of a long history, oxygen#95)
920
        // names no reference: its outcome is reported as `objects`.
921363×
        let objects_only = updates.is_empty() && tags.is_empty();
922363×
        match self.import_bundle(&bundle, policy.is_some()) {
923357×
            Ok(imported) => {
924357×
                if objects_only {
9257×
                    results.push(RefResult {
9267×
                        name: OBJECTS_RESULT.into(),
9277×
                        ok: true,
9287×
                        reason: format!("{} changes stored", imported.len()),
9297×
                    });
930350×
                }
931357×
                report.imported = imported;
932
            }
9336×
            Err(e) => {
9346×
                if objects_only {
9350×
                    results.push(RefResult {
9360×
                        name: OBJECTS_RESULT.into(),
9370×
                        ok: false,
9380×
                        reason: e.to_string(),
9390×
                    });
9406×
                }
9416×
                for u in updates {
9426×
                    results.push(RefResult {
9436×
                        name: u.name,
9446×
                        ok: false,
9456×
                        reason: e.to_string(),
9466×
                    });
9476×
                }
9486×
                return Ok(report);
949
            }
950
        }
951357×
        let (op_ref, op) = self.head_op()?;
952357×
        let mut view = op.view.clone();
953357×
        let mut names = Vec::new();
954357×
        for u in updates {
955345×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
956345×
            let (ok, reason) = match outcome {
957312×
                Ok(()) => (true, String::new()),
95833×
                Err(e) => (false, e),
959
            };
960345×
            if ok {
961312×
                names.push(u.name.clone());
962312×
                let heads = self
963312×
                    .store
964312×
                    .get_state(&u.new_state)
965312×
                    .map(|s| s.heads)
966312×
                    .unwrap_or_default();
967312×
                report.updated.push(RefUpdated {
968312×
                    name: u.name.clone(),
969312×
                    old_state: u.old_state,
970312×
                    new_state: u.new_state,
971312×
                    heads,
972312×
                });
97333×
            }
974345×
            results.push(RefResult {
975345×
                name: u.name,
976345×
                ok,
977345×
                reason,
978345×
            });
979
        }
980357×
        for t in &tags {
98122×
            let name = format!("tags/{}", t.name);
98222×
            if t.is_withdrawal() {
9833×
                match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut TagCheck::Received)
984
                {
9852×
                    Ok(removed) => {
986
                        // A withdrawal is an update to nothing, as a
987
                        // bookmark's deletion is.
9882×
                        if removed {
9892×
                            report.updated.push(RefUpdated {
9902×
                                name: name.clone(),
9912×
                                old_state: t.state,
9922×
                                new_state: ObjectRef::ZERO,
9932×
                                heads: vec![],
9942×
                            });
9952×
                        }
9962×
                        names.push(name.clone());
9972×
                        results.push(RefResult {
9982×
                            name,
999
                            ok: true,
10002×
                            reason: if removed {
10012×
                                "withdrawn"
1002
                            } else {
10030×
                                "already withdrawn"
1004
                            }
10052×
                            .into(),
1006
                        });
1007
                    }
10081×
                    Err(e) => results.push(RefResult {
10091×
                        name,
10101×
                        ok: false,
10111×
                        reason: e.reason,
10121×
                    }),
1013
                }
10143×
                continue;
101519×
            }
101619×
            let new = !view.tags.contains_key(&t.name);
101719×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
1018
                Ok(()) => {
1019
                    // A tag new here is an update too, so a hub can start
1020
                    // its pipeline's tag jobs (oxygenflow#24); one it
1021
                    // already had, sent again, is not.
102214×
                    if new {
102313×
                        report.updated.push(RefUpdated {
102413×
                            name: name.clone(),
102513×
                            old_state: ObjectRef::ZERO,
102613×
                            new_state: t.state,
102713×
                            heads: t.heads.clone(),
102813×
                        });
102913×
                    }
103014×
                    names.push(name.clone());
103114×
                    results.push(RefResult {
103214×
                        name,
103314×
                        ok: true,
103414×
                        reason: String::new(),
103514×
                    });
1036
                }
10375×
                Err(e) => results.push(RefResult {
10385×
                    name,
10395×
                    ok: false,
10405×
                    reason: e.reason,
10415×
                }),
1042
            }
1043
        }
1044357×
        if !names.is_empty() {
1045314×
            self.record_op(
1046314×
                &[op_ref],
1047314×
                &format!("push received: {}", names.join(" ")),
1048314×
                view,
10493×
            )?;
105043×
        }
1051354×
        Ok(report)
1052365×
    }
1053
1054
    /// Check an update's attestation against the latest one for its
1055
    /// reference and store it as the new latest. Failures say what was
1056
    /// being done, for which reference, so a refused push can be diagnosed
1057
    /// from its reason alone.
1058106×
    fn record_update_attest(
1059106×
        &self,
1060106×
        u: &RefUpdate,
1061106×
        sa: &SignedAttest,
1062106×
    ) -> std::result::Result<(), String> {
1063106×
        let name = &u.name;
1064106×
        let last = self
1065106×
            .latest_ref_attest(name)
1066106×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1067106×
            .and_then(|(_, a)| match a.attest.body {
106865×
                AttestBody::Ref { serial, .. } => Some(serial),
10690×
                _ => None,
107065×
            });
1071106×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1072104×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1073104×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1074103×
        for sig in &sa.sigs {
1075103×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1076
        }
1077103×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1078
        // Signed by a short-lived key: a host records when it accepted it.
1079100×
        let certified = sa
1080100×
            .sigs
1081100×
            .first()
1082100×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
1083100×
        if certified {
10846×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
108594×
        }
1086100×
        Ok(())
1087106×
    }
1088
1089
    /// Record that this host accepted attestation `r` now, signed with its
1090
    /// acceptor key (spec §14.7); nothing without one.
109111×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
109211×
        let Some(acceptor) = &self.acceptor else {
10937×
            return Ok(());
1094
        };
10954×
        let (id, sk) = (&acceptor.0, &acceptor.1);
10964×
        let attest = Attest {
10974×
            repo: self.id()?,
10984×
            hlc: Hlc::now(),
10994×
            body: AttestBody::Accepted { attest: *r },
1100
        };
11014×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
11024×
        self.store.put_identity(id)?;
11034×
        let a = self.store.put_attest(&attest)?;
11044×
        self.store.put_signature(&a, &sig)?;
11054×
        self.store.index_add_pub("accepted", r, &a)?;
11064×
        Ok(())
110711×
    }
1108
1109
    /// The host's acceptance of attestation `r`, if one was recorded.
1110227×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1111227×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1112206×
            return Ok(None);
1113
        };
1114
        Ok(Some(SignedAttest {
111521×
            attest: self.store.get_attest(&a)?,
111621×
            sigs: self.store.signatures(&a)?,
1117
        }))
1118227×
    }
1119
1120
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1121
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1122
    /// signer's certificate and accepts `sa`; else the attestation's own
1123
    /// time, which the signer chose.
112431×
    pub(crate) fn certified_time(
112531×
        &self,
112631×
        signer: &KeyId,
112731×
        sa: &SignedAttest,
112831×
        accepted: Option<&SignedAttest>,
112931×
    ) -> u64 {
113031×
        self.issuer_acceptance(signer, sa, accepted)
113131×
            .unwrap_or(sa.attest.hlc.wall_ms)
113231×
    }
1133
1134
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1135
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
1136101×
    pub(crate) fn issuer_acceptance(
1137101×
        &self,
1138101×
        signer: &KeyId,
1139101×
        sa: &SignedAttest,
1140101×
        accepted: Option<&SignedAttest>,
1141101×
    ) -> Option<u64> {
1142101×
        let acc = accepted?;
114346×
        let c = self.store.certificate_of(signer).ok().flatten()?;
114446×
        let cert = self.store.get_certificate(&c).ok()?;
114546×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11460×
            return None;
1147
        };
114851×
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
114943×
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
115043×
        (*attest == sa.attest.hash()
115142×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
115243×
        .then_some(acc.attest.hlc.wall_ms)
1153101×
    }
1154
1155
    /// Keep an acceptance this repository was given for attestation `r`
1156
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1157
    /// what it accepts.
11589×
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
11599×
        let a = self.store.put_attest(&acc.attest)?;
116011×
        for sig in &acc.sigs {
116111×
            self.store.put_signature(&a, sig)?;
1162
        }
11639×
        self.store.index_add_pub("accepted", r, &a)?;
11649×
        Ok(())
11659×
    }
1166
1167
    /// A fetched bookmark's attestation by a signer the policy does not
1168
    /// list itself: a delegate or a short-lived key, whose authority
1169
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1170
    /// attestation's integrated time when the host's log gives one; else
1171
    /// as before, at the host's acceptance for a certified signer, when it
1172
    /// countersigned one, or at the attestation's own time, and said so
1173
    /// when the host keeps a log. Failing at the integrated time but not
1174
    /// as before is a note while logs are new; a large gap between the
1175
    /// claimed and the integrated time is a note.
1176
    #[allow(clippy::too_many_arguments)]
117727×
    pub(crate) fn authorize_in_time(
117827×
        &self,
117927×
        p: &crate::policy::Policy,
118027×
        remote_name: &str,
118127×
        r: &crate::protocol::RemoteRef,
118227×
        sa: &SignedAttest,
118327×
        signer: &KeyId,
118427×
        log: &super::transparency::LogCheck,
118527×
        notes: &mut Vec<String>,
118627×
    ) -> Result<()> {
1187
        use super::transparency::{gap_note, judge, Timed};
118827×
        let own = sa.attest.hlc.wall_ms;
118927×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
119027×
        let time = log.time_of(&r.name);
119129×
        let check = |t_delegate: u64, t_cert: u64| {
119229×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
119327×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
119429×
        };
119527×
        let before = if at != own {
11967×
            "the host's acceptance"
1197
        } else {
119820×
            "the time it claims"
1199
        };
120027×
        let what = format!("{remote_name}/{}", r.name);
120127×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1202
            Timed::Refused => {
12031×
                return fail(format!(
1204
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
12051×
                    signer.short(12)
1206
                ))
1207
            }
12083×
            Timed::Integrated => {}
12091×
            Timed::Disagrees => notes.push(format!(
1210
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
12111×
                signer.short(12),
12121×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1213
            )),
12141×
            Timed::Fallback if log.kept => notes.push(format!(
1215
                "{what}: {} checked at {before}, not at a witnessed time: {}",
12161×
                signer.short(12),
12171×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1218
            )),
121921×
            Timed::Fallback => {}
1220
        }
122126×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
12222×
            notes.push(format!("{what}'s attestation {n}"));
122324×
        }
122426×
        Ok(())
122527×
    }
1226
1227
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1228
    /// at `old_state`, is never the bookmark a non-bare repository has
1229
    /// checked out (a bare one's default is its host's to protect, see
1230
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1231
    /// an attestation by a key that may update it.
1232
    /// The deletion's attestation stays the bookmark's latest, so an older
1233
    /// one cannot be replayed to bring it back.
12343×
    fn apply_deletion(
12353×
        &self,
12363×
        view: &mut View,
12373×
        u: &RefUpdate,
12383×
        policy: Option<&crate::policy::Policy>,
12393×
    ) -> std::result::Result<(), String> {
12403×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
12410×
            return Err(format!("no bookmark {:?} to delete", u.name));
1242
        };
12433×
        if current != u.old_state {
12440×
            return Err("stale: the remote bookmark has moved; pull first".into());
12453×
        }
12463×
        if !self.is_bare() && u.name == self.config.bookmark {
12471×
            return Err(format!(
12481×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
12491×
                u.name
12501×
            ));
12512×
        }
12522×
        if let Some(p) = policy {
12530×
            let Some(sa) = &u.attestation else {
12540×
                return Err(format!(
12550×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12560×
                    u.name
12570×
                ));
1258
            };
12590×
            let signer = sa
12600×
                .sigs
12610×
                .first()
12620×
                .map(|s| s.key)
12630×
                .ok_or("attestation carries no signature")?;
1264
            // Received now: the receiver's own clock is the trusted time.
12650×
            let now = Hlc::now().wall_ms;
12660×
            if !p.authorizes(&signer, &u.name)
12670×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12680×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1269
            {
12700×
                return Err(format!(
12710×
                    "key {} may not delete {:?} under this repository's policy",
12720×
                    signer.short(12),
12730×
                    u.name
12740×
                ));
12750×
            }
12762×
        }
12772×
        if let Some(sa) = &u.attestation {
12781×
            self.record_update_attest(u, sa)?;
12791×
        }
12802×
        view.bookmarks.remove(&u.name);
12812×
        Ok(())
12823×
    }
1283
1284345×
    fn apply_update(
1285345×
        &self,
1286345×
        view: &mut View,
1287345×
        u: &RefUpdate,
1288345×
        policy: Option<&crate::policy::Policy>,
1289345×
    ) -> std::result::Result<(), String> {
1290345×
        if u.name == "policy" {
12910×
            return Err(
12920×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
12930×
            );
1294345×
        }
1295345×
        let empty = self
1296345×
            .store
1297345×
            .put_state(&StateObject::new(vec![]))
1298345×
            .map_err(|e| e.to_string())?;
1299345×
        if u.new_state.is_zero() {
13003×
            return self.apply_deletion(view, u, policy);
1301342×
        }
1302342×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1303342×
        if current != u.old_state {
130413×
            return Err("stale: the remote bookmark has moved; pull first".into());
1305329×
        }
1306329×
        let new_state = self
1307329×
            .store
1308329×
            .get_state(&u.new_state)
1309329×
            .map_err(|_| "new state object is missing".to_string())?;
1310610×
        for h in &new_state.heads {
1311610×
            if !self.store.has(h) {
13121×
                return Err(format!("head {} is missing", h.short(12)));
1313609×
            }
1314
        }
1315328×
        if !u.force {
1316327×
            let old_heads = self
1317327×
                .store
1318327×
                .get_state(&current)
1319327×
                .map_err(|e| e.to_string())?
1320
                .heads;
1321327×
            let closure = self
1322327×
                .closure_in_store(&new_state.heads)
1323327×
                .map_err(|e| e.to_string())?;
1324327×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
13251×
                return Err(format!(
13261×
                    "not a fast-forward: current head {} would be dropped (use --force)",
13271×
                    h.short(12)
13281×
                ));
1329326×
            }
13301×
        }
1331327×
        if let Some(p) = policy {
133259×
            let Some(sa) = &u.attestation else {
13331×
                return Err(format!(
13341×
                    "{:?} requires a signed reference attestation under this repository's policy",
13351×
                    u.name
13361×
                ));
1337
            };
133858×
            let signer = sa
133958×
                .sigs
134058×
                .first()
134158×
                .map(|s| s.key)
134258×
                .ok_or("attestation carries no signature")?;
1343
            // Received now: the receiver's own clock is the trusted time.
134458×
            let now = Hlc::now().wall_ms;
134558×
            if !p.authorizes(&signer, &u.name)
134619×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
134716×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1348
            {
134910×
                return Err(format!(
135010×
                    "key {} may not update {:?} under this repository's policy",
135110×
                    signer.short(12),
135210×
                    u.name
135310×
                ));
135448×
            }
135548×
            let old_heads = self
135648×
                .store
135748×
                .get_state(&current)
135848×
                .map_err(|e| e.to_string())?
1359
                .heads;
136048×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1361268×
        }
1362316×
        if let Some(sa) = &u.attestation {
1363105×
            self.record_update_attest(u, sa)?;
1364211×
        }
1365310×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1366310×
        Ok(())
1367345×
    }
1368
1369
    // ------------------------------------------------------------ client side
1370
13711530×
    fn remote_url(&self, name: &str) -> Result<String> {
13721530×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13733×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13743×
            RepoError::Msg(match names.as_slice() {
13753×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
13761×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1377
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
13781×
                    names.join(", "),
13791×
                    names[0],
13801×
                    names[0]
1381
                ),
13820×
                _ => format!(
1383
                    "no remote named {name:?}; this repository has {}",
13840×
                    names.join(", ")
1385
                ),
1386
            })
13873×
        })
13881530×
    }
1389
1390
    /// Refuse a remote that is another repository. An **unbound** remote
1391
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1392
    /// for pushes, which bind it to this repository's id (spec §16.1).
1393835×
    fn check_remote_id(
1394835×
        &self,
1395835×
        remote: &dyn crate::protocol::Remote,
1396835×
        remote_name: &str,
1397835×
        allow_unbound: bool,
1398835×
    ) -> Result<()> {
1399835×
        let theirs = remote.repo_id()?;
1400834×
        if theirs == self.id()? {
1401807×
            return Ok(());
140227×
        }
140327×
        if theirs == crate::protocol::UNBOUND_ID {
140424×
            if allow_unbound {
140523×
                return Ok(());
14061×
            }
14071×
            return fail(format!(
1408
                "remote {remote_name:?} is empty and unbound: push to it first"
1409
            ));
14103×
        }
14113×
        fail(format!(
1412
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1413
        ))
1414835×
    }
1415
1416
    /// Credentials and trust for a remote: `remote.<name>.token` and
1417
    /// `remote.<name>.ca`, else the defaults for its URL
1418
    /// ([`Repo::fill_credentials`]).
14191137×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
14201137×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
14211137×
        let mut options = RemoteOptions {
14221137×
            repo_id: self.id().ok(),
14231137×
            token: self.config.remote_tokens.get(name).cloned(),
14241137×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
14251137×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
14261137×
            ..RemoteOptions::default()
14271137×
        };
14281137×
        self.fill_credentials(&url, &mut options);
14291137×
        options
14301137×
    }
1431
1432
    /// The user's credential store (`credentials.toml` beside the user
1433
    /// configuration file).
14341158×
    pub fn credentials(&self) -> crate::credentials::Credentials {
14351158×
        crate::credentials::Credentials::at(
14361158×
            self.user_config
14371158×
                .parent()
14381158×
                .map(Path::to_path_buf)
14391158×
                .unwrap_or_else(default_home),
1440
        )
14411158×
    }
1442
1443
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1444
    /// then the user's credential store for its hub, then a remote on the
1445
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1446
    /// When the token is not this remote's own or the environment's, the
1447
    /// other tokens enclosing checkouts hold for the hub are kept to try
1448
    /// if it is refused: a stale stored login must not hide a parent's
1449
    /// good token (oxygen#112).
14501159×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14511159×
        if options.token.is_some() && options.ca.is_some() {
14521×
            return;
14531158×
        }
14541158×
        let explicit =
14551158×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14561158×
        let stored = self.credentials().options_for(url);
14571158×
        options.token = options.token.take().or(stored.token);
14581158×
        options.ca = options.ca.take().or(stored.ca);
14591158×
        let enclosing = self.enclosing_credentials(url);
14601158×
        if options.token.is_none() {
14611148×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
146210×
        }
14631158×
        if options.ca.is_none() {
14641142×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
146516×
        }
14661158×
        if !explicit {
14671151×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
14685×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
14692×
                    options.fallback_tokens.push(t);
14703×
                }
1471
            }
14727×
        }
14731159×
    }
1474
1475
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1476
    /// checkouts, nearest first.
14771158×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
14781158×
        let mut out = Vec::new();
14791158×
        let Some(hub) = crate::credentials::hub_of(url) else {
14801002×
            return out;
1481
        };
1482156×
        let mut at = self.root.parent();
1483632×
        while let Some(dir) = at {
1484476×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14850×
                break;
1486
            };
1487476×
            for (key, remote_url) in &cfg {
148815×
                let Some(name) = key
148915×
                    .strip_prefix("remote.")
149015×
                    .and_then(|k| k.strip_suffix(".url"))
1491
                else {
14927×
                    continue;
1493
                };
14948×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
14951×
                    continue;
14967×
                }
14977×
                out.push((
14987×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
14997×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
15007×
                ));
1501
            }
1502476×
            at = dir.parent();
1503
        }
1504156×
        out
15051158×
    }
1506
1507
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1508
    /// no changes and no reference updates, which the receiver stores.
15090×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
15100×
        let remote = self.open_named_remote(remote_name)?;
15110×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
15120×
        let mut bundle = Bundle::default();
15130×
        for r in seals {
15140×
            let attest = self.store.get_attest(r)?;
15150×
            let sigs = self.store.signatures(r)?;
15160×
            bundle
15170×
                .attests
15180×
                .push(crate::protocol::SignedAttest { attest, sigs });
1519
        }
15200×
        let results = remote.push(bundle, vec![], None, vec![])?;
15210×
        if let Some(r) = results.iter().find(|r| !r.ok) {
15220×
            return fail(format!("{}: {}", r.name, r.reason));
15230×
        }
15240×
        Ok(())
15250×
    }
1526
1527
    /// The remote whose URL starts with `base` (a hub), if configured.
15284×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
15294×
        let base = base.trim_end_matches('/');
15304×
        self.config
15314×
            .remotes
15324×
            .iter()
15334×
            .find(|(_, url)| url.trim_end_matches('/') == base)
15344×
            .map(|(name, _)| name.clone())
15354×
    }
1536
1537
    /// Open a remote by name or, failing that, by URL with the default
1538
    /// credentials (see [`Repo::credentials_for`]).
15390×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15400×
        if let Some(name) = self.remote_for_url(url) {
15410×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15420×
        }
15430×
        let options = RemoteOptions {
15440×
            repo_id: self.id().ok(),
15450×
            ..self.credentials_for(url)
15460×
        };
15470×
        Ok((url.to_string(), open_remote(url, &options)?))
15480×
    }
1549
1550
    /// Credentials for a URL: those of the configured remote with that
1551
    /// URL, else the environment's.
15524×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
15534×
        match self.remote_for_url(url) {
15544×
            Some(name) => self.remote_options(&name),
15550×
            None => RemoteOptions {
15560×
                repo_id: self.id().ok(),
15570×
                ..self.credentials_for(url)
15580×
            },
1559
        }
15604×
    }
1561
15621120×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15631120×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15641120×
    }
1565
1566220×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1567220×
        self.oxy
1568220×
            .join("remotes")
1569220×
            .join(remote)
1570220×
            .join(format!("{bookmark}.serial"))
1571220×
    }
1572
157373×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
157473×
        fs::read_to_string(self.serial_path(remote, bookmark))
157573×
            .ok()
157673×
            .and_then(|s| s.trim().parse().ok())
157773×
    }
1578
1579147×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1580147×
        let p = self.serial_path(remote, bookmark);
1581147×
        fs::create_dir_all(p.parent().unwrap())?;
1582147×
        write_atomic(&p, serial.to_string().as_bytes())
1583147×
    }
1584
1585482×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1586482×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1587482×
    }
1588
1589
    /// The highest policy serial `remote` has ever presented.
1590410×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1591410×
        fs::read_to_string(self.policy_serial_path(remote))
1592410×
            .ok()
1593410×
            .and_then(|s| s.trim().parse().ok())
1594410×
    }
1595
159672×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
159772×
        let p = self.policy_serial_path(remote);
159872×
        fs::create_dir_all(p.parent().unwrap())?;
159972×
        write_atomic(&p, serial.to_string().as_bytes())
160072×
    }
1601
160227×
    fn lazy_dir(&self) -> PathBuf {
160327×
        self.oxy.join("lazy")
160427×
    }
1605
1606
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
16074×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
16084×
        fs::create_dir_all(self.lazy_dir())?;
16094×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
16104×
    }
1611
1612
    /// Which remote promised an absent blob, if any.
161315×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
161415×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
161515×
            .ok()
161615×
            .map(|s| s.trim().to_string())
161715×
    }
1618
1619
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
16204×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
16214×
        let Some(remote_name) = self.lazy_remote(blob) else {
16220×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1623
        };
16244×
        let remote = self.open_named_remote(&remote_name)?;
16254×
        let objects = remote.objects(&[*blob])?;
16269×
        for (ty, body) in objects {
16279×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
16289×
                self.store.put(ty, &body)?;
16290×
            }
1630
        }
16314×
        if !self.store.has(blob) {
16320×
            return fail(format!(
1633
                "{remote_name} did not send blob {}",
16340×
                blob.short(12)
1635
            ));
16364×
        }
16374×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
16384×
        Ok(())
16394×
    }
1640
1641
    /// After importing from `remote`, record every blob the changes reference
1642
    /// that the store lacks as lazily available from that remote.
16434×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
16444×
        let mut n = 0;
16454×
        for h in changes {
16464×
            let c = self.store.get_change(h)?;
164713×
            for e in &c.edits {
164813×
                if let Edit::Replace { old, new, .. } = e {
16496×
                    for b in [old, new].into_iter().flatten() {
16506×
                        if !self.store.has(b) {
16514×
                            self.register_lazy(b, remote)?;
16524×
                            n += 1;
16532×
                        }
1654
                    }
16557×
                }
1656
            }
1657
        }
16584×
        Ok(n)
16594×
    }
1660
1661
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1662410×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1663410×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1664558×
        for st in view
1665410×
            .bookmarks
1666410×
            .values()
1667410×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1668
        {
1669558×
            if let Ok(s) = self.store.get_state(st) {
1670558×
                have.extend(s.heads);
1671558×
            }
1672
        }
1673410×
        have.extend(view.workspaces.values().copied());
1674410×
        Ok(have.into_iter().collect())
1675410×
    }
1676
1677
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1678416×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1679416×
        let remote = self.open_named_remote(remote_name)?;
1680413×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1681411×
        let resp = remote.refs()?;
1682
        // The host's transparency log (spec §14.8): a fork fails here.
1683410×
        let log = self.check_log(
1684410×
            &self.remote_url(remote_name)?,
1685410×
            self.config.remote_cas.get(remote_name).map(Path::new),
1686410×
            &resp,
16870×
        )?;
1688410×
        let mut log_notes = log.notes.clone();
1689
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1690
        // and signed by roots we trust, or on first contact. A remote that
1691
        // once presented a policy may never present none or an older one:
1692
        // that is a downgrade. A remote that never presented one is
1693
        // unverified, and this fetch is checked only as far as possible.
1694410×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1695410×
        let seen = self.remote_policy_serial(remote_name);
1696410×
        let mut unverified = false;
1697410×
        match &resp.policy {
169838×
            Some(sp) => {
169938×
                if seen.is_some_and(|s| sp.policy.serial < s) {
17000×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
170138×
                }
170214×
                match &local_policy {
170314×
                    Some(l) if sp.policy.serial < l.serial => {}
170414×
                    Some(l) if sp.policy.serial == l.serial => {
170510×
                        if sp.policy.hash() != l.hash() {
17060×
                            return fail(format!(
1707
                                "{remote_name} presents a different policy with the same serial {}",
1708
                                l.serial
1709
                            ));
171010×
                        }
1711
                    }
1712
                    _ => {
171328×
                        self.adopt_policy_chain(
171428×
                            &resp.history,
171528×
                            sp,
171628×
                            &format!("oxy fetch {remote_name}"),
1717
                        )
171828×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1719
                    }
1720
                }
172138×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1722
            }
1723
            None => {
1724372×
                if seen.is_some() {
17250×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1726372×
                }
1727372×
                unverified = true;
1728
            }
1729
        }
1730410×
        let policy = if unverified {
1731372×
            None
1732
        } else {
173338×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1734
        };
1735410×
        let (op_ref, op) = self.head_op()?;
1736410×
        let mut view = op.view.clone();
1737410×
        let have = self.known_heads(&view)?;
1738410×
        let mut report = Vec::new();
1739410×
        let mut skipped = Vec::new();
1740410×
        let max_blob = self.config.max_blob;
1741436×
        for r in resp.refs {
1742436×
            let needed = {
1743436×
                let _t = crate::timing::phase("fetch: negotiate");
1744436×
                remote.negotiate(&have, &r.heads)?
1745
            };
1746436×
            let bundle = {
1747436×
                let _t = crate::timing::phase("fetch: bundle");
1748436×
                remote.fetch(&needed, max_blob)?
1749
            };
1750
            // Changes are not individually re-verified here: the bookmark's
1751
            // attestation (checked below) binds its whole state, and the
1752
            // receiver of the push verified the added changes at that time.
1753436×
            let imported = {
1754436×
                let _t = crate::timing::phase("fetch: import");
1755436×
                self.import_bundle(&bundle, false)?
1756
            };
1757436×
            if max_blob.is_some() {
17584×
                self.register_missing_blobs(&imported, remote_name)?;
1759432×
            }
1760590×
            for h in &r.heads {
1761590×
                if !self.store.has(h) {
17620×
                    return fail(format!("remote did not send head {}", h.short(12)));
1763590×
                }
1764
            }
1765436×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1766436×
            if state != r.state {
17670×
                return fail(format!(
1768
                    "remote state {} does not match its heads",
17690×
                    r.state.short(12)
1770
                ));
1771436×
            }
1772436×
            if let Some(p) = &policy {
177341×
                let Some(sa) = &r.attestation else {
17740×
                    return fail(format!(
1775
                        "{remote_name}/{} has no attestation, which its policy requires",
1776
                        r.name
1777
                    ));
1778
                };
177941×
                let signer = sa
178041×
                    .sigs
178141×
                    .first()
178241×
                    .map(|s| s.key)
178341×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
178441×
                if !p.authorizes(&signer, &r.name) {
178520×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
178621×
                }
1787395×
            }
1788436×
            if let Some(sa) = &r.attestation {
1789
                let AttestBody::Ref {
179073×
                    old_state,
179173×
                    new_state,
1792
                    ..
179373×
                } = &sa.attest.body
1794
                else {
17950×
                    return fail("remote sent a non-ref attestation for a bookmark");
1796
                };
179773×
                let (old_state, new_state) = (*old_state, *new_state);
179873×
                let serial = self
179973×
                    .check_ref_attest_body(
180073×
                        sa,
180173×
                        &r.name,
180273×
                        &old_state,
180373×
                        &new_state,
180473×
                        self.last_seen_serial(remote_name, &r.name),
1805
                        true,
1806
                    )
180773×
                    .map_err(|e| {
18080×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
18090×
                    })?;
181073×
                if new_state != r.state {
18110×
                    return fail(format!(
1812
                        "attestation for {}/{} does not cover its current state",
1813
                        remote_name, r.name
1814
                    ));
181573×
                }
1816
                // A signature this client cannot verify (its signer unknown
1817
                // here, as from a host that did not send the identity, or
1818
                // bad) fails that bookmark alone: it stays as it was and
1819
                // the rest are fetched (oxygenhub#266). The current
1820
                // bookmark, which a pull would take, still fails the fetch.
1821
                // A policy's requirements were checked above and still fail.
182273×
                if let Err(e) = self.verify_attest_signature(sa) {
182312×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
182412×
                    if r.name == self.config.bookmark {
18253×
                        return fail(why);
18269×
                    }
18279×
                    skipped.push((r.name, why));
18289×
                    continue;
182961×
                }
183061×
                let ar = self.store.put_attest(&sa.attest)?;
183161×
                for sig in &sa.sigs {
183261×
                    self.store.put_signature(&ar, sig)?;
1833
                }
183461×
                self.record_serial(remote_name, &r.name, serial)?;
1835363×
            }
1836424×
            view.remotes
1837424×
                .entry(remote_name.to_string())
1838424×
                .or_default()
1839424×
                .insert(r.name.clone(), state);
1840424×
            report.push((r.name, r.heads, imported.len()));
1841
        }
1842407×
        let mut new_tags = 0;
1843407×
        for t in &resp.tags {
184431×
            if view.tags.contains_key(&t.name) {
18457×
                continue;
184624×
            }
1847
            // Withdrawn here: the name is not used again.
184824×
            if self.tag_withdrawal(&t.name)?.is_some() {
18490×
                continue;
185024×
            }
1851
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
185224×
            let missing: Vec<ChangeHash> = t
185324×
                .heads
185424×
                .iter()
185524×
                .filter(|h| !self.store.has(h))
185624×
                .copied()
185724×
                .collect();
185824×
            if !missing.is_empty() {
18590×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
18600×
                let bundle = remote.fetch(&needed, max_blob)?;
18610×
                self.import_bundle(&bundle, false)?;
186224×
            }
186324×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
186424×
            let mut check = TagCheck::Fetched {
186524×
                remote: remote_name,
186624×
                log: &log,
186724×
                notes: &mut log_notes,
186824×
            };
186924×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
187022×
                Ok(()) => new_tags += 1,
1871
                // Nothing says when a short-lived key signed it: the tag is
1872
                // left out, said so, and the rest is fetched (oxygen#129).
18732×
                Err(e) if e.untimed => {
18742×
                    skipped.push((format!("tags/{}", t.name), e.reason));
18752×
                }
18760×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1877
            }
1878
        }
1879
        // The remote withdrew a tag this repository has: so does this one,
1880
        // once the withdrawal is checked as a push's would be; one that is
1881
        // not is left as it is, said so (oxygenhub#301).
1882407×
        let mut withdrawn_tags = Vec::new();
1883407×
        for t in &resp.withdrawn {
18841×
            if !view.tags.contains_key(&t.name) {
18850×
                continue;
18861×
            }
18871×
            let mut check = TagCheck::Fetched {
18881×
                remote: remote_name,
18891×
                log: &log,
18901×
                notes: &mut log_notes,
18911×
            };
18921×
            match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut check) {
18931×
                Ok(true) => withdrawn_tags.push(t.name.clone()),
18940×
                Ok(false) => {}
18950×
                Err(e) => skipped.push((
18960×
                    format!("tags/{}", t.name),
18970×
                    format!("withdrawn on {remote_name}, kept here: {}", e.reason),
18980×
                )),
1899
            }
1900
        }
1901407×
        if view != op.view {
1902391×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
190316×
        }
1904407×
        let _ = self.run_hook(
1905407×
            "post-fetch",
1906407×
            &format!(
1907
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1908407×
                json_str(remote_name),
1909421×
                json_array(report.iter().map(|(n, heads, _)| format!(
1910
                    "{{\"name\":{},\"heads\":{}}}",
1911421×
                    json_str(n),
1912575×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1913
                )))
1914
            ),
1915
        );
1916407×
        Ok(FetchReport {
1917407×
            refs: report,
1918407×
            unverified,
1919407×
            new_tags,
1920407×
            withdrawn_tags,
1921407×
            log_notes,
1922407×
            skipped,
1923407×
        })
1924416×
    }
1925
1926
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1927
    /// the changes within `depth` steps of its heads, and the boundary below.
19281×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
19291×
        let remote = self.open_named_remote(remote_name)?;
19301×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
19311×
        let resp = remote.refs()?;
19321×
        let bookmark = self.config.bookmark.clone();
19331×
        if let Some(sp) = &resp.policy {
19340×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
19350×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
19360×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
19371×
        }
19381×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
19390×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1940
        };
19411×
        if r.heads.is_empty() {
19420×
            return Ok(0);
19431×
        }
1944
        // Base: the remote's checkpoint of exactly these heads.
19451×
        let cp_bundle = remote.checkpoint(&r.heads)?;
19461×
        let mut cp_ref = None;
19473×
        for (ty, body) in &cp_bundle.objects {
19483×
            let put = self.store.put(*ty, body)?;
19493×
            if *ty == ObjectType::Checkpoint {
19501×
                cp_ref = Some(put);
19512×
            }
1952
        }
19531×
        let Some(cp_ref) = cp_ref else {
19540×
            return fail(format!("{remote_name} sent no checkpoint"));
1955
        };
19561×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1957
        // History window.
19581×
        let wanted = remote.shallow(&r.heads, depth)?;
19591×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
19601×
        let imported = self.import_bundle_shallow(&bundle, false)?;
19611×
        if self.config.max_blob.is_some() {
19620×
            self.register_missing_blobs(&imported, remote_name)?;
19631×
        }
19641×
        self.refresh_boundary(&imported)?;
19651×
        if let Some(sa) = &r.attestation {
19660×
            let ar = self.store.put_attest(&sa.attest)?;
19670×
            for sig in &sa.sigs {
19680×
                self.store.put_signature(&ar, sig)?;
1969
            }
19700×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
19710×
                self.record_serial(remote_name, &r.name, serial)?;
19720×
            }
19731×
        }
19741×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
19751×
        let (op_ref, op) = self.head_op()?;
19761×
        let mut view = op.view.clone();
19771×
        view.remotes
19781×
            .entry(remote_name.to_string())
19791×
            .or_default()
19801×
            .insert(r.name.clone(), state);
19811×
        self.record_op(
19821×
            &[op_ref],
19831×
            &format!("oxy fetch {remote_name} --depth {depth}"),
19841×
            view,
19850×
        )?;
19861×
        Ok(imported.len())
19871×
    }
1988
1989
    /// Fetch, then take the union of the local bookmark's state with the
1990
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1991118×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1992118×
        let _wc = self.lock_working_copy()?;
1993118×
        let skipped = self.fetch(remote_name)?.skipped;
1994114×
        let (op_ref, op) = self.head_op()?;
1995114×
        let current = self.config.bookmark.clone();
1996114×
        let mut local_current = self.heads_of(&op.view, &current)?;
1997114×
        local_current.sort();
1998114×
        let mut view = op.view.clone();
1999114×
        let mut current_heads = local_current.clone();
2000114×
        let mut changed = false;
2001114×
        let mut others = Vec::new();
2002114×
        let tracked = op
2003114×
            .view
2004114×
            .remotes
2005114×
            .get(remote_name)
2006114×
            .cloned()
2007114×
            .unwrap_or_default();
2008119×
        for (name, remote_state) in tracked {
2009
            // Every local bookmark tracks the remote's of the same name;
2010
            // the current one may be new here.
2011119×
            let local_state = op.view.bookmarks.get(&name).copied();
2012119×
            if local_state.is_none() && name != current {
20131×
                continue;
2014118×
            }
2015118×
            if local_state == Some(remote_state) {
201610×
                continue;
2017108×
            }
2018108×
            let local = self.heads_of(&op.view, &name)?;
2019108×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2020132×
            if remote_heads.iter().all(|h| local.contains(h)) {
20210×
                continue;
2022108×
            }
2023108×
            let mut all = local.clone();
2024108×
            all.extend(remote_heads);
2025108×
            let st = self.load_state_history(&all)?;
2026108×
            let mut heads = st.maximal(&all);
2027108×
            heads.sort();
2028108×
            let mut sorted_local = local;
2029108×
            sorted_local.sort();
2030108×
            if heads == sorted_local {
20311×
                continue;
2032107×
            }
2033107×
            view.bookmarks.insert(
2034107×
                name.clone(),
2035107×
                self.store.put_state(&StateObject::new(heads.clone()))?,
2036
            );
2037107×
            if name == current {
2038105×
                changed = true;
2039105×
                current_heads = heads;
2040105×
            } else {
20412×
                others.push(name);
20422×
            }
2043
        }
2044114×
        if changed || !others.is_empty() {
2045106×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
20468×
        }
2047
        // The working copy follows its bookmark whenever nothing would be
2048
        // lost, also when this pull brought nothing new but it had been
2049
        // left behind (oxygen#89).
2050114×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2051
        Ok(PullReport {
2052114×
            heads: if changed {
2053105×
                current_heads
2054
            } else {
20559×
                local_current
2056
            },
2057114×
            changed,
2058114×
            checked_out,
2059114×
            others,
2060114×
            skipped,
2061
        })
2062118×
    }
2063
2064
    /// How many changes the working copy's bookmark has that its base
2065
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2066
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2067
    /// the bookmark or holds changes the bookmark lacks. History is read
2068
    /// only when the base and the bookmark's heads differ (oxygen#89).
20697×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
20707×
        let (_, wc) = self.working_copy()?;
20717×
        let mut base = wc.deps.clone();
20727×
        base.sort();
20737×
        let mut heads = self.bookmark_heads()?;
20747×
        heads.sort();
20757×
        if base == heads || heads.is_empty() {
20766×
            return Ok(None);
20771×
        }
20781×
        let state = self.load_state_history(&heads)?;
20791×
        if !base.iter().all(|h| state.contains(h)) {
20800×
            return Ok(None);
20811×
        }
20821×
        let had = if base.is_empty() {
20830×
            0
2084
        } else {
20851×
            self.load_state_history(&base)?.len()
2086
        };
20871×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
20887×
    }
2089
2090
    /// Bring the working copy to `heads`, the state of its bookmark
2091
    /// `bookmark`, when nothing would be lost: its base is part of that
2092
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2093
    /// with uncommitted work, the work comes along when the new changes
2094
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2095
    /// it followed only from exactly the bookmark's old heads, so a working
2096
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2097
    /// or a pull from another workspace) never caught up, and nothing said
2098
    /// so (oxygen#74, #89). Returns whether it moved.
2099114×
    pub fn follow_bookmark(
2100114×
        &self,
2101114×
        heads: &[ChangeHash],
2102114×
        bookmark: &str,
2103114×
        command: &str,
2104114×
    ) -> Result<bool> {
2105114×
        let snap = self.snapshot(command)?;
2106114×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2107114×
        let mut base = snap.base.maximal(&snap.wc.deps);
2108114×
        base.sort();
2109114×
        let mut target = heads.to_vec();
2110114×
        target.sort();
2111114×
        if base == target {
21128×
            return Ok(false);
2113106×
        }
2114106×
        let state = self.load_state_history(heads)?;
2115201×
        if !base.iter().all(|h| state.contains(h)) {
2116
            // The working copy holds changes the bookmark lacks: not ours to move.
21170×
            return Ok(false);
2118106×
        }
2119106×
        if clean {
2120106×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
2121106×
            Ok(true)
2122
        } else {
21230×
            Ok(self
21240×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
21250×
                .is_ok())
2126
        }
2127114×
    }
2128
2129
    /// Withdraw tag `tag` on `remote_name` (`oxy push --delete tags/NAME`,
2130
    /// oxygenhub#301): withdrawn here first when it still is a tag here
2131
    /// (`oxy tag delete`), then the withdrawal alone is sent, with its
2132
    /// signer's identity and certificate.
21333×
    pub fn push_tag_withdrawal(&self, remote_name: &str, tag: &str) -> Result<Vec<RefResult>> {
21343×
        let remote = self.open_named_remote(remote_name)?;
21353×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
21363×
        let resp = remote.refs()?;
21373×
        let name = format!("tags/{tag}");
21383×
        if resp.withdrawn.iter().any(|t| t.name == tag) {
21391×
            return Ok(vec![RefResult {
21401×
                name,
21411×
                ok: true,
21421×
                reason: "already withdrawn".into(),
21431×
            }]);
21442×
        }
21452×
        let Some(there) = resp.tags.iter().find(|t| t.name == tag) else {
21460×
            return fail(format!("{remote_name} has no tag {tag}"));
2147
        };
21482×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
21490×
            return fail(format!("{remote_name} enforces a trust policy; withdrawing a tag needs an identity (`oxy identity create`)"));
21502×
        }
21512×
        if self.tag_withdrawal(tag)?.is_none() {
21522×
            match self.view()?.tags.get(tag) {
21532×
                Some(st) if *st == there.state => {
21542×
                    self.tag_delete(tag, "")?;
2155
                }
2156
                Some(_) => {
21570×
                    return fail(format!(
2158
                        "tag {tag} names another state here than on {remote_name}"
2159
                    ))
2160
                }
2161
                None => {
21620×
                    return fail(format!(
2163
                        "there is no tag {tag} here to withdraw: `oxy fetch {remote_name}` first"
2164
                    ))
2165
                }
2166
            }
21670×
        }
21682×
        let Some(w) = self
21692×
            .withdrawn_refs()?
21702×
            .into_iter()
21712×
            .find(|w| w.name == tag && w.state == there.state)
2172
        else {
21730×
            return fail(format!(
2174
                "tag {tag} was withdrawn here at another state than {remote_name}'s"
2175
            ));
2176
        };
21772×
        let mut bundle = Bundle::default();
21782×
        let signers: Vec<KeyId> = w
21792×
            .attestation
21802×
            .iter()
21812×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
21822×
            .collect();
21832×
        for k in &signers {
21842×
            if let Ok(id) = self.identity(k) {
21852×
                bundle.objects.push((ObjectType::Identity, id.encode()));
21862×
            }
2187
        }
21882×
        self.attach_certificates_for(&mut bundle, &signers)?;
21892×
        remote.push(bundle, vec![], None, vec![w])
21903×
    }
2191
2192
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2193
    /// changes and attesting the reference when a key is available.
2194
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2195
    /// state, attested when we have an identity. The local bookmark, if
2196
    /// any, is kept; only the remote-tracking entry goes.
21978×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
21988×
        if let Some(tag) = bookmark.strip_prefix("tags/") {
21993×
            return self.push_tag_withdrawal(remote_name, tag);
22005×
        }
22015×
        let remote = self.open_named_remote(remote_name)?;
22025×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
22035×
        let resp = remote.refs()?;
22047×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
22051×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2206
        };
22074×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
22080×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
22094×
        }
22104×
        let attestation = match self.secret_key()? {
22112×
            Some(_) => Some(self.sign_attest(&Attest {
22122×
                repo: self.id()?,
22132×
                hlc: Hlc::now(),
22142×
                body: AttestBody::Ref {
22152×
                    name: bookmark.to_string(),
22162×
                    old_state: r.state,
22172×
                    new_state: ObjectRef::ZERO,
22182×
                    serial: r.last_serial.unwrap_or(0) + 1,
22192×
                },
22200×
            })?),
22212×
            None => None,
2222
        };
22234×
        let results = remote.push(
22244×
            Bundle::default(),
22254×
            vec![RefUpdate {
22264×
                name: bookmark.to_string(),
22274×
                old_state: r.state,
22284×
                new_state: ObjectRef::ZERO,
22294×
                force: true,
22304×
                attestation,
22314×
            }],
22324×
            None,
22334×
            vec![],
22340×
        )?;
22354×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
22362×
            let (op_ref, op) = self.head_op()?;
22372×
            let mut view = op.view.clone();
22382×
            if let Some(m) = view.remotes.get_mut(remote_name) {
22392×
                m.remove(bookmark);
22402×
            }
22412×
            self.record_op(
22422×
                &[op_ref],
22432×
                &format!("oxy push {remote_name} --delete {bookmark}"),
22442×
                view,
22450×
            )?;
22462×
        }
22474×
        Ok(results)
22488×
    }
2249
2250
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2251
    /// repository's config (its URL, token, CA and store settings), its
2252
    /// tracking bookmarks in the view, and a store remote's mirror under
2253
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
22543×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
22553×
        if !self.config.remotes.contains_key(name) {
22561×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
22572×
        }
22582×
        let prefix = format!("remote.{name}.");
22592×
        let keys: Vec<String> = self
22602×
            .config
22612×
            .repo_layer()
22622×
            .keys()
22634×
            .filter(|k| k.starts_with(&prefix))
22642×
            .cloned()
22652×
            .collect();
22663×
        for k in keys {
22673×
            self.config.set(&k, "")?;
2268
        }
22692×
        self.config.remotes.remove(name);
22702×
        self.save_config()?;
22712×
        let (op_ref, op) = self.head_op()?;
22722×
        if op.view.remotes.contains_key(name) {
22731×
            let mut view = op.view.clone();
22741×
            view.remotes.remove(name);
22751×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
22761×
        }
22772×
        let mirror = self.oxy.join("remotes").join(name);
22782×
        if mirror.is_dir() {
22790×
            fs::remove_dir_all(&mirror)?;
22802×
        }
22812×
        Ok(())
22823×
    }
2283
2284
    /// `changes`, in dependency order, cut into batches of about
2285
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2286
    /// There is always one, perhaps empty.
2287326×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2288326×
        let blob_len = |r: &ObjectRef| -> u64 {
228929×
            self.store
229029×
                .get_typed(r, ObjectType::Blob)
229129×
                .ok()
229229×
                .and_then(|b| Blob::decode(&b).ok())
229329×
                .map_or(0, |b| b.length)
229429×
        };
2295326×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2296431×
        for h in changes {
2297431×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2298431×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2299431×
            let mut weight = raw.len() as u64;
2300545×
            for t in &texts {
2301545×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
230226×
                    weight += blob_len(r);
2303519×
                }
2304
            }
2305711×
            for e in &c.edits {
23063×
                if let Edit::Replace { new: Some(b), .. } = e {
23073×
                    weight += blob_len(b);
2308708×
                }
2309
            }
2310431×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
23115×
                out.push(std::mem::take(&mut batch));
23125×
                bytes = 0;
2313426×
            }
2314431×
            batch.push(*h);
2315431×
            bytes += weight;
2316
        }
2317326×
        out.push(batch);
2318326×
        Ok(out)
2319326×
    }
2320
2321393×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2322393×
        let bookmark = self.config.bookmark.clone();
2323393×
        self.push_bookmark(remote_name, &bookmark, force)
2324393×
    }
2325
2326
    /// `push` for a named bookmark (`oxy push -b NAME`).
2327406×
    pub fn push_bookmark(
2328406×
        &self,
2329406×
        remote_name: &str,
2330406×
        bookmark: &str,
2331406×
        force: bool,
2332406×
    ) -> Result<Vec<RefResult>> {
2333406×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2334406×
    }
2335
2336
    /// `push_bookmark`, saying how a long push is going: one line per
2337
    /// batch sent (oxygen#95).
2338414×
    pub fn push_bookmark_with(
2339414×
        &self,
2340414×
        remote_name: &str,
2341414×
        bookmark: &str,
2342414×
        force: bool,
2343414×
        progress: crate::store::Progress,
2344414×
    ) -> Result<Vec<RefResult>> {
2345414×
        let (op_ref, op) = self.head_op()?;
2346414×
        if !op.view.bookmarks.contains_key(bookmark) {
23470×
            return fail(format!("no bookmark {bookmark}"));
2348414×
        }
2349414×
        let bookmark = bookmark.to_string();
2350414×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2351
        // pre-push hook: may veto before the remote is contacted.
2352414×
        self.run_hook(
2353414×
            "pre-push",
2354414×
            &format!(
2355
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2356414×
                json_str(remote_name),
2357414×
                json_str(&bookmark),
2358828×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2359
            ),
23601×
        )?;
2361413×
        let remote = self.open_named_remote(remote_name)?;
2362413×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2363410×
        let resp = remote.refs()?;
2364410×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2365410×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2366410×
        let policy_to_send = match (&local_policy, &resp.policy) {
236744×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
236816×
            (Some(l), None) => Some(l.clone()),
236926×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
23701×
                return fail(format!(
2371
                    "{remote_name} has a newer policy (serial {}); fetch first",
2372
                    r.policy.serial
2373
                ));
2374
            }
2375375×
            _ => None,
2376
        };
2377409×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2378409×
        if remote_has_policy && self.secret_key()?.is_none() {
23791×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2380408×
        }
2381408×
        let remote_tags: BTreeSet<String> = resp
2382408×
            .tags
2383408×
            .iter()
2384408×
            .chain(&resp.withdrawn)
2385408×
            .map(|t| t.name.clone())
2386408×
            .collect();
2387408×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2388408×
            .tag_refs()?
2389408×
            .into_iter()
2390408×
            .filter(|t| !remote_tags.contains(&t.name))
2391408×
            .collect();
2392
        // Tags withdrawn here that the remote still has, at the same state
2393
        // (oxygenhub#301).
2394408×
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2395408×
            .withdrawn_refs()?
2396408×
            .into_iter()
2397408×
            .filter(|w| {
23982×
                resp.tags
23992×
                    .iter()
24002×
                    .any(|t| t.name == w.name && t.state == w.state)
24012×
            })
2402408×
            .collect();
2403408×
        let refs = resp.refs;
2404408×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2405408×
        let (remote_state, remote_heads, last_serial) =
2406409×
            match refs.iter().find(|r| r.name == bookmark) {
2407386×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
240822×
                None => (empty, vec![], None),
2409
            };
2410408×
        let new_state = self
2411408×
            .store
2412408×
            .put_state(&StateObject::new(local_heads.clone()))?;
2413
        // A push that carries a policy re-attests the bookmark even when its
2414
        // state is unchanged, so the current attestation is always by a key
2415
        // the current policy authorizes (a revoked key's attestation would
2416
        // otherwise be refused by every later fetch).
2417408×
        if new_state == remote_state
241835×
            && policy_to_send.is_none()
241918×
            && tags_to_send.is_empty()
24209×
            && withdrawals_to_send.is_empty()
2421
        {
24228×
            return Ok(vec![RefResult {
24238×
                name: bookmark,
24248×
                ok: true,
24258×
                reason: "already up to date".into(),
24268×
            }]);
2427400×
        }
2428417×
        for h in &remote_heads {
2429417×
            if !self.store.has(h) {
243073×
                return fail(format!(
2431
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
243273×
                    h.short(12)
2433
                ));
2434344×
            }
2435
        }
2436327×
        if !force {
2437327×
            let closure = self.closure_in_store(&local_heads)?;
2438335×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
24390×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2440327×
            }
24410×
        }
2442327×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2443327×
        let key = self.secret_key()?.map(|(k, _)| k);
2444327×
        if let Some(key) = key {
2445
            // Seal this author's changes that carry no valid authenticator,
2446
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2447
            // are stored, so each batch's bundle carries those it needs.
2448112×
            let mut unsigned = Vec::new();
2449112×
            for h in &to_send {
245092×
                let c = self.store.get_change_meta(h)?;
245192×
                if self.seals_for_author(&c.author, &key)
245287×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
245353×
                {
245453×
                    unsigned.push(*h);
245553×
                }
2456
            }
2457112×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
245850×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2459
            }
2460215×
        }
2461
        // A long history goes in batches, in dependency order, so neither
2462
        // side holds it whole and no request passes the remote's limit:
2463
        // all but the last carry objects alone; the last moves the bookmark
2464
        // (oxygen#95).
2465326×
        let batches = self.push_batches(&to_send)?;
2466326×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2467326×
        for (i, batch) in earlier.iter().enumerate() {
24685×
            progress(&format!(
24695×
                "part {} of {}: {} changes",
24705×
                i + 1,
24715×
                batches.len(),
24725×
                batch.len()
24735×
            ));
24745×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
24755×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
24765×
                Some(r) if r.ok => {}
24770×
                Some(r) => {
24780×
                    return fail(format!(
2479
                        "{remote_name} refused part {} of the push: {}",
24800×
                        i + 1,
2481
                        r.reason
2482
                    ))
2483
                }
2484
                None => {
24850×
                    return fail(format!(
2486
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2487
                    ))
2488
                }
2489
            }
2490
        }
2491326×
        if batches.len() > 1 {
24921×
            progress(&format!(
24931×
                "part {} of {}: {} changes",
24941×
                batches.len(),
24951×
                batches.len(),
24961×
                last.len()
24971×
            ));
2498325×
        }
2499326×
        let mut bundle = self.bundle_for(last)?;
2500326×
        bundle.objects.push((
2501326×
            ObjectType::State,
2502326×
            StateObject::new(local_heads.clone()).encode(),
2503326×
        ));
2504326×
        let attestation = match key {
2505111×
            Some(_) => Some(self.sign_attest(&Attest {
2506111×
                repo: self.id()?,
2507111×
                hlc: Hlc::now(),
2508111×
                body: AttestBody::Ref {
2509111×
                    name: bookmark.clone(),
2510111×
                    old_state: remote_state,
2511111×
                    new_state,
2512111×
                    serial: next_serial(last_serial),
2513111×
                },
25141×
            })?),
2515215×
            None => None,
2516
        };
2517
        // Whoever signed the move, and whom a delegate acts for, travel with
2518
        // it: a receiver that has never seen a change by this delegate could
2519
        // not otherwise check its signature (oxygenhub#129).
2520325×
        if attestation.is_some() {
2521220×
            for k in [self.signing_key(), self.config.author_key]
2522110×
                .into_iter()
2523110×
                .flatten()
2524
            {
2525220×
                if let Ok(id) = self.identity(&k) {
2526220×
                    let body = id.encode();
2527220×
                    if !bundle
2528220×
                        .objects
2529220×
                        .iter()
2530269×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
253132×
                    {
253232×
                        bundle.objects.push((ObjectType::Identity, body));
2533188×
                    }
25340×
                }
2535
            }
2536
            // A short-lived signing key's certificate goes with it (§14.7).
2537110×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2538110×
            self.attach_certificates_for(&mut bundle, &signers)?;
2539215×
        }
2540325×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2541110×
            AttestBody::Ref { serial, .. } => Some(serial),
25420×
            _ => None,
2543110×
        });
2544325×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2545
        // Tag states must be present on the remote: bundle their changes too.
2546325×
        for t in &tags_to_send {
254716×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
254816×
            let extra: Vec<ChangeHash> =
254916×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
255016×
            if !extra.is_empty() {
25510×
                let more = self.bundle_for(&extra)?;
25520×
                bundle.changes.extend(more.changes);
25530×
                bundle.hashes.extend(more.hashes);
25540×
                bundle.attests.extend(more.attests);
25550×
                bundle.objects.extend(more.objects);
255616×
            }
255716×
            bundle.objects.push((
255816×
                ObjectType::State,
255916×
                StateObject::new(t.heads.clone()).encode(),
256016×
            ));
2561
        }
2562
        // A tag's signer travels with it, as the bookmark's does: a tag made
2563
        // by `oxy tag create` under a short-lived key was signed by a key the
2564
        // receiver has never seen, so its identity and certificate go too.
2565325×
        let tag_signers: Vec<KeyId> = tags_to_send
2566325×
            .iter()
2567325×
            .chain(&withdrawals_to_send)
2568325×
            .filter_map(|t| t.attestation.as_ref())
2569325×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2570325×
            .collect();
2571325×
        for k in &tag_signers {
257216×
            if let Ok(id) = self.identity(k) {
257316×
                let body = id.encode();
257416×
                if !bundle
257516×
                    .objects
257616×
                    .iter()
257732×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
25782×
                {
25792×
                    bundle.objects.push((ObjectType::Identity, body));
258014×
                }
25810×
            }
2582
        }
2583325×
        if !tag_signers.is_empty() {
258415×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2585310×
        }
2586325×
        if let Some(l) = &policy_to_send {
258734×
            let remote_serial = resp_policy_serial;
258834×
            bundle.policies = self
258934×
                .policy_history()?
259034×
                .into_iter()
259166×
                .filter(|sp| {
259266×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
259336×
                        && sp.policy.serial < l.policy.serial
259466×
                })
259534×
                .collect();
2596291×
        }
2597325×
        let results = remote.push(
2598325×
            bundle,
2599325×
            vec![RefUpdate {
2600325×
                name: bookmark.clone(),
2601325×
                old_state: remote_state,
2602325×
                new_state,
2603325×
                force,
2604325×
                attestation,
2605325×
            }],
2606325×
            policy_to_send,
2607325×
            tags_to_send
2608325×
                .into_iter()
2609325×
                .chain(withdrawals_to_send)
2610325×
                .collect(),
26118×
        )?;
261234×
        if let (Some(serial), true) = (
2613317×
            sent_serial,
2614331×
            results.iter().any(|r| r.ok && r.name == "policy"),
2615
        ) {
261634×
            self.record_policy_serial(remote_name, serial)?;
2617283×
        }
2618354×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2619287×
            let mut view = op.view.clone();
2620287×
            view.remotes
2621287×
                .entry(remote_name.to_string())
2622287×
                .or_default()
2623287×
                .insert(bookmark.clone(), new_state);
2624287×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2625284×
            if let Some(s) = serial {
262686×
                self.record_serial(remote_name, &bookmark, s)?;
2627198×
            }
262830×
        }
2629312×
        Ok(results)
2630414×
    }
2631
2632
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2633
    /// bookmark set to the remote's, working copy checked out.
2634264×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2635264×
        Self::clone_with(url, dest, None, &[])
2636264×
    }
2637
2638
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2639
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2640
    /// unless a size is given, so out-of-scope binaries are never fetched).
2641267×
    pub fn clone_with(
2642267×
        url: &str,
2643267×
        dest: &Path,
2644267×
        max_blob: Option<u64>,
2645267×
        sparse: &[String],
2646267×
    ) -> Result<Repo> {
2647267×
        Self::clone_full(url, dest, max_blob, sparse, None)
2648267×
    }
2649
2650
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2651
    /// changes within `depth` steps of them; the rest is the boundary.
26521×
    pub fn clone_shallow(
26531×
        url: &str,
26541×
        dest: &Path,
26551×
        depth: u32,
26561×
        max_blob: Option<u64>,
26571×
        sparse: &[String],
26581×
    ) -> Result<Repo> {
26591×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
26601×
    }
2661
2662268×
    fn clone_full(
2663268×
        url: &str,
2664268×
        dest: &Path,
2665268×
        max_blob: Option<u64>,
2666268×
        sparse: &[String],
2667268×
        depth: Option<u32>,
2668268×
    ) -> Result<Repo> {
2669268×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2670268×
    }
2671
2672
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2673
    /// `depth`), also returning the bookmarks the fetch left out because
2674
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2675
    /// for the caller to warn about. The bookmark checked out is never one
2676
    /// of them: that fails the clone.
2677274×
    pub fn clone_reporting(
2678274×
        url: &str,
2679274×
        dest: &Path,
2680274×
        max_blob: Option<u64>,
2681274×
        sparse: &[String],
2682274×
        depth: Option<u32>,
2683274×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2684274×
        let options = crate::credentials::Credentials::user().options_for(url);
2685274×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2686274×
    }
2687
2688
    /// Clone a subrepo with the credentials the parent would use for its
2689
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2690
    /// subrepo: it finds the same ones again through its parent.
269110×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
269210×
        let options = self.credentials_for(url);
269310×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
269410×
    }
2695
2696
    /// The name of a remote of this repository on the same hub (scheme,
2697
    /// host and port) as `url`.
269823×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
269927×
        let origin = |u: &str| -> Option<String> {
270027×
            let (scheme, rest) = u.split_once("://")?;
27018×
            if !matches!(scheme, "http" | "https") {
27020×
                return None;
27038×
            }
27048×
            let host = rest.split('/').next()?;
27058×
            Some(format!(
27068×
                "{}://{}",
27078×
                scheme.to_ascii_lowercase(),
27088×
                host.to_ascii_lowercase()
27098×
            ))
271027×
        };
271123×
        let want = origin(url)?;
27124×
        self.config
27134×
            .remotes
27144×
            .iter()
27154×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
27164×
            .map(|(name, _)| name.clone())
271723×
    }
2718
2719
    /// The token and CA to reach `url` with: those of a remote of this
2720
    /// repository on the same hub (scheme, host and port), else the
2721
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2722
    /// and enclosing checkouts', as a clone would use them.
272323×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
272423×
        match self.remote_on_same_hub(url) {
27251×
            Some(name) => RemoteOptions {
27261×
                repo_id: None,
27271×
                cache_dir: None,
27281×
                ..self.remote_options(&name)
27291×
            },
2730
            None => {
273122×
                let mut options = RemoteOptions::default();
273222×
                self.fill_credentials(url, &mut options);
273322×
                options
2734
            }
2735
        }
273623×
    }
2737
2738284×
    fn clone_using(
2739284×
        url: &str,
2740284×
        dest: &Path,
2741284×
        max_blob: Option<u64>,
2742284×
        sparse: &[String],
2743284×
        depth: Option<u32>,
2744284×
        options: &RemoteOptions,
2745284×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2746284×
        let remote = open_remote(url, options)?;
2747284×
        let id = remote.repo_id()?;
2748280×
        if id == crate::protocol::UNBOUND_ID {
27492×
            return fail(format!(
2750
                "{url} is empty and unbound: push a repository to it first"
2751
            ));
2752278×
        }
2753278×
        let mut repo = Repo::init_with_id(dest, id)?;
2754278×
        repo.config
2755278×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2756278×
        if let Some(m) = max_blob {
27572×
            repo.config.set("filter.max-blob", &m.to_string())?;
2758276×
        } else if !sparse.is_empty() {
27591×
            repo.config.set("filter.max-blob", "0")?;
2760275×
        }
2761278×
        if !sparse.is_empty() {
27621×
            repo.config.set("filter.paths", &sparse.join(","))?;
2763277×
        }
2764278×
        repo.save_config()?;
2765278×
        let skipped = if let Some(depth) = depth {
27661×
            repo.fetch_shallow("origin", depth)?;
27671×
            Vec::new()
2768
        } else {
2769277×
            repo.fetch("origin")?.skipped
2770
        };
2771276×
        let (op_ref, op) = repo.head_op()?;
2772
        // The remote's default bookmark, else ours (main), else its only
2773
        // one; a bookmark the fetch skipped counts, so the clone fails
2774
        // rather than check out another (oxygenhub#266).
2775276×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2776276×
        for (name, _) in &skipped {
27773×
            theirs.insert(name.clone(), ObjectRef::ZERO);
27783×
        }
2779
        // Asked of the remote as now configured, so a store-backed one
2780
        // answers from the mirror the fetch just filled.
2781276×
        let advertised = repo
2782276×
            .open_named_remote("origin")
2783276×
            .ok()
2784276×
            .and_then(|r| r.refs().ok())
2785276×
            .and_then(|r| r.default_bookmark);
2786276×
        let bookmark = advertised
2787276×
            .filter(|b| theirs.contains_key(b))
2788276×
            .or_else(|| {
27897×
                theirs
27907×
                    .contains_key(&repo.config.bookmark)
27917×
                    .then(|| repo.config.bookmark.clone())
27927×
            })
2793276×
            .or_else(|| {
27940×
                (theirs.len() == 1)
27950×
                    .then(|| theirs.keys().next().cloned())
27960×
                    .flatten()
27970×
            })
2798276×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2799276×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
28000×
            return fail(format!("cannot check out {bookmark}: {why}"));
2801276×
        }
2802276×
        let initial = repo.config.bookmark.clone();
2803276×
        if bookmark != repo.config.bookmark {
28041×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
28051×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
28061×
            repo.config.bookmark = bookmark.clone();
2807275×
        }
2808276×
        if let Some(state) = theirs.get(&bookmark).copied() {
2809276×
            let heads = repo.store.get_state(&state)?.heads;
2810276×
            let mut view = op.view.clone();
2811
            // The empty bookmark `init` made goes when another is checked out.
2812276×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
28131×
                view.bookmarks.remove(&initial);
2814275×
            }
2815276×
            view.bookmarks.insert(bookmark, state);
2816276×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2817276×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
28180×
        }
2819276×
        Ok((repo, skipped))
2820284×
    }
2821
}
2822
2823
/// The serial of a reference's next attestation: one more than the last the
2824
/// remote reports, or, for a bookmark the remote does not have, the clock in
2825
/// milliseconds, so a bookmark created again after a deletion goes past the
2826
/// deletion's serial the remote keeps.
2827111×
fn next_serial(last: Option<u64>) -> u64 {
2828111×
    match last {
282969×
        Some(l) => l + 1,
283042×
        None => Hlc::now().wall_ms.max(1),
2831
    }
2832111×
}