OXYGENHUB

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

2006 of 2227 lines run, 318 of 420 functions · run #367 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
681798×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
691798×
        self.oxy.join("attest").join(name_file(bookmark))
701798×
    }
71
72
    /// The latest reference attestation stored for a bookmark.
731388×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
741388×
        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
            }
861043×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
870×
            Err(e) => Err(e.into()),
88
        }
891388×
    }
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
961099×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
971099×
        let view = self.view()?;
981099×
        let mut out = Vec::new();
991152×
        for (name, state) in &view.bookmarks {
1001152×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
1011152×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
102230×
                AttestBody::Ref { serial, .. } => Some(serial),
1030×
                _ => None,
104230×
            });
1051152×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1061152×
            let accepted = match &attestation {
107219×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
108933×
                None => None,
109
            };
1101152×
            out.push(RemoteRef {
1111152×
                name: name.clone(),
1121152×
                state: *state,
1131152×
                heads: self.store.get_state(state)?.heads,
1141152×
                attestation,
1151152×
                last_serial,
1161152×
                accepted,
1171152×
                logged: None,
1181152×
                integration: vec![],
119
            });
120
        }
1211099×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1221099×
        let history = self
1231099×
            .policy_history()?
1241099×
            .into_iter()
1251099×
            .filter(|sp| {
126221×
                policy
127221×
                    .as_ref()
128221×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
129221×
            })
1301099×
            .collect();
131
        Ok(RefsResponse {
1321099×
            refs: out,
1331099×
            policy,
1341099×
            tags: self.tag_refs()?,
1351099×
            history,
1361099×
            default_bookmark: Some(self.config.bookmark.clone()),
1371099×
            log: None,
1381099×
            witnesses: vec![],
1391099×
            withdrawn: self.withdrawn_refs()?,
140
        })
1411099×
    }
142
143
    /// Every change reachable from `heads` that is in the store.
1441515×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1451515×
        let mut seen = BTreeSet::new();
1461515×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1474983×
        while let Some(h) = stack.pop() {
1483468×
            if seen.contains(&h) || !self.store.has(&h) {
149990×
                continue;
1502478×
            }
1512478×
            seen.insert(h);
1522478×
            stack.extend(self.store.get_change_meta(&h)?.deps);
153
        }
1541515×
        Ok(seen)
1551515×
    }
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
1822139×
    fn shallow_path(&self) -> PathBuf {
1832139×
        self.oxy.join("shallow")
1842139×
    }
185
186
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1872136×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1882136×
        fs::read_to_string(self.shallow_path())
1892136×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1902136×
            .unwrap_or_default()
1912136×
    }
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).
242878×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
243878×
        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.
246878×
        let boundary = self.boundary();
247878×
        let mut out = Vec::new();
248878×
        let mut done: BTreeSet<ChangeHash> = have.clone();
249878×
        done.extend(boundary.iter().copied());
250
        // Iterative post-order DFS.
2511343×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2523478×
        while let Some((h, expanded)) = stack.pop() {
2532600×
            if done.contains(&h) {
254464×
                continue;
2552136×
            }
2562136×
            if !self.store.has(&h) {
2570×
                return fail(format!("change {} is not in this repository", h.short(12)));
2582136×
            }
2592136×
            if expanded {
2601068×
                done.insert(h);
2611068×
                out.push(h);
2621068×
                continue;
2631068×
            }
2641068×
            stack.push((h, true));
2651068×
            for d in self.store.get_change_meta(&h)?.deps {
266685×
                if !done.contains(&d) {
267189×
                    stack.push((d, false));
268496×
                }
269
            }
270
        }
271878×
        Ok(out)
272878×
    }
273
274
    /// Bundle changes (in the given dependency order) with their signatures,
275
    /// seals, identities, blobs, chunks.
276336×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
277336×
        self.bundle_of(changes, None, false, false)
278336×
    }
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.
30752×
    pub fn bundle_for_filtered(
30852×
        &self,
30952×
        changes: &[ChangeHash],
31052×
        max_blob: Option<u64>,
31152×
    ) -> Result<Bundle> {
31252×
        self.bundle_of(changes, max_blob, false, true)
31352×
    }
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.
319370×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
320370×
        self.bundle_of(changes, max_blob, true, true)
321370×
    }
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.
334422×
    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);
337422×
        let key = (self.oxy.clone(), self.head_op()?.0);
338422×
        if let Some(keys) = SERVED
339422×
            .lock()
340422×
            .unwrap_or_else(|p| p.into_inner())
341422×
            .as_ref()
342422×
            .and_then(|m| m.get(&key))
343
        {
344131×
            return Ok(keys.clone());
345291×
        }
346291×
        let keys = self.attest_signers_now()?;
347291×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
348291×
        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.
3516007×
        map.retain(|(oxy, _), _| *oxy != key.0);
352291×
        if map.len() >= 1024 {
3530×
            map.clear();
354291×
        }
355291×
        map.insert(key, keys.clone());
356291×
        Ok(keys)
357422×
    }
358
359291×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
360291×
        let view = self.view()?;
361291×
        let pointers = view
362291×
            .bookmarks
363291×
            .keys()
364301×
            .map(|b| self.ref_attest_path(b))
365291×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
366291×
        let mut keys = BTreeSet::new();
367323×
        for p in pointers {
368323×
            let Ok(text) = fs::read_to_string(&p) else {
369260×
                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
        }
376291×
        Ok(keys)
377291×
    }
378
379
    /// `serving`: a fetch's answer, which carries the identities and
380
    /// certificates of [`Repo::served_attest_signers`] too.
381758×
    fn bundle_of(
382758×
        &self,
383758×
        changes: &[ChangeHash],
384758×
        max_blob: Option<u64>,
385758×
        raw: bool,
386758×
        serving: bool,
387758×
    ) -> Result<Bundle> {
388758×
        let mut bundle = Bundle::default();
389758×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
390758×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3911240×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3921240×
            if !r.is_zero() && self.store.has(r) {
393384×
                objects.insert(*r);
394856×
            }
3951240×
        };
396982×
        for h in changes {
397
            // Raw: the stored bytes, and a skeleton for the rest.
398982×
            let (c, encoded) = if raw {
399517×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
400517×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
4014982×
                for t in texts {
4024982×
                    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);
4064979×
                    }
407
                }
408517×
                (skel, Some(bytes))
409
            } else {
410465×
                (self.store.get_change(h)?, None)
411
            };
412982×
            let sigs = self.store.signatures(h)?;
413982×
            add_object(&c.author, &mut objects);
414982×
            for s in &sigs {
41537×
                add_object(&s.key, &mut objects);
41637×
            }
4175963×
            for e in &c.edits {
4185963×
                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
                    }
4325951×
                }
433
            }
434982×
            for s in self.store.seals_for(h)? {
435110×
                seals.insert(s);
436110×
            }
437982×
            match encoded {
438517×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
439465×
                None => {
440465×
                    bundle.changes.push((c, sigs));
441465×
                    bundle.hashes.push(*h);
442465×
                }
443
            }
444
        }
445758×
        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
        }
453758×
        let signers: Vec<KeyId> = if serving {
454422×
            let signers = self.served_attest_signers()?;
455422×
            for k in &signers {
456116×
                add_object(k, &mut objects);
457116×
            }
458422×
            signers.into_iter().collect()
459
        } else {
460336×
            Vec::new()
461
        };
462758×
        for r in objects {
463225×
            let (ty, body) = self.store.get(&r)?;
464225×
            bundle.objects.push((ty, body));
465
        }
466758×
        self.attach_certificates_for(&mut bundle, &signers)?;
467758×
        Ok(bundle)
468758×
    }
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).
474885×
    pub(crate) fn attach_certificates_for(
475885×
        &self,
476885×
        bundle: &mut Bundle,
477885×
        also: &[KeyId],
478885×
    ) -> Result<()> {
479885×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
480885×
        keys.extend(
481885×
            bundle
482885×
                .changes
483885×
                .iter()
484885×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
485
        );
486885×
        keys.extend(
487885×
            bundle
488885×
                .raw_changes
489885×
                .iter()
490885×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
491
        );
492885×
        keys.extend(
493885×
            bundle
494885×
                .attests
495885×
                .iter()
496885×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
497
        );
498885×
        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
        }
526885×
        Ok(())
527885×
    }
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.
531802×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
532802×
        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
        }
544802×
        Ok(())
545802×
    }
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).
580799×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
581799×
        self.import_bundle_inner(bundle, strict, false)
582799×
    }
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
590802×
    fn import_bundle_inner(
591802×
        &self,
592802×
        bundle: &Bundle,
593802×
        strict: bool,
594802×
        shallow: bool,
595802×
    ) -> Result<Vec<ChangeHash>> {
596802×
        let batch = self.store.begin_batch()?;
597802×
        let result = self.import_bundle_batched(bundle, strict, shallow);
598802×
        batch.finish()?;
599800×
        result
600802×
    }
601
602802×
    fn import_bundle_batched(
603802×
        &self,
604802×
        bundle: &Bundle,
605802×
        strict: bool,
606802×
        shallow: bool,
607802×
    ) -> Result<Vec<ChangeHash>> {
608802×
        for (ty, _) in &bundle.objects {
6090×
            if !matches!(
610691×
                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()));
618691×
            }
619
        }
620
        // All at once: in a large batch they are compressed on every core.
621802×
        let objects: Vec<(ObjectType, &[u8])> = bundle
622802×
            .objects
623802×
            .iter()
624802×
            .map(|(ty, body)| (*ty, body.as_slice()))
625802×
            .collect();
626802×
        self.store.put_many(&objects)?;
627802×
        self.adopt_certificates(&bundle.certificates)?;
628802×
        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).
642802×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
643793×
            bundle.hashes.clone()
644
        } else {
6459×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
646
        };
647802×
        let raw_hashes: Vec<ChangeHash> = bundle
648802×
            .raw_changes
649802×
            .iter()
650802×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
651802×
            .collect();
652802×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
653802×
        let boundary = self.boundary();
654802×
        let mut imported = Vec::new();
655
        // Changes as stored: checked, then stored as they are, their text
656
        // blobs having come with the objects.
657802×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
658518×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
659518×
            for d in &skel.deps {
660358×
                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
                    ));
667358×
                }
668
            }
6694983×
            for t in texts {
6704983×
                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×
                    }
6784979×
                }
679
            }
680517×
            self.store.put(ObjectType::Change, bytes)?;
681517×
            for sig in sigs {
68213×
                self.store.put_signature(&h, sig)?;
683
            }
684517×
            imported.push(h);
685
        }
686801×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
687492×
            for d in &c.deps {
688281×
                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
                    ));
695278×
                }
696
            }
697489×
            let stored = self.store.put_change(c)?;
698489×
            if stored != h {
6990×
                return fail(format!(
700
                    "change {} is not the change the bundle names",
7010×
                    h.short(12)
702
                ));
703489×
            }
704489×
            for sig in sigs {
70533×
                self.store.put_signature(&h, sig)?;
706
            }
707489×
            imported.push(h);
708
        }
709798×
        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
            }
718731×
        }
719794×
        Ok(imported)
720802×
    }
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.
864308×
    pub fn receive_push(
865308×
        &self,
866308×
        bundle: Bundle,
867308×
        updates: Vec<RefUpdate>,
868308×
        policy: Option<SignedPolicy>,
869308×
        tags: Vec<crate::protocol::TagRef>,
870308×
    ) -> Result<Vec<RefResult>> {
871308×
        Ok(self
872308×
            .receive_push_report(bundle, updates, policy, tags)?
873
            .results)
874308×
    }
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).
879356×
    pub fn receive_push_report(
880356×
        &self,
881356×
        bundle: Bundle,
882356×
        updates: Vec<RefUpdate>,
883356×
        policy: Option<SignedPolicy>,
884356×
        tags: Vec<crate::protocol::TagRef>,
885356×
    ) -> 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.
889356×
        self.refresh()?;
890356×
        let mut report = PushReport::default();
891356×
        let results = &mut report.results;
892356×
        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
            }
917320×
        }
918354×
        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`.
921354×
        let objects_only = updates.is_empty() && tags.is_empty();
922354×
        match self.import_bundle(&bundle, policy.is_some()) {
923348×
            Ok(imported) => {
924348×
                if objects_only {
9257×
                    results.push(RefResult {
9267×
                        name: OBJECTS_RESULT.into(),
9277×
                        ok: true,
9287×
                        reason: format!("{} changes stored", imported.len()),
9297×
                    });
930341×
                }
931348×
                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
        }
951348×
        let (op_ref, op) = self.head_op()?;
952348×
        let mut view = op.view.clone();
953348×
        let mut names = Vec::new();
954348×
        for u in updates {
955336×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
956336×
            let (ok, reason) = match outcome {
957304×
                Ok(()) => (true, String::new()),
95832×
                Err(e) => (false, e),
959
            };
960336×
            if ok {
961304×
                names.push(u.name.clone());
962304×
                let heads = self
963304×
                    .store
964304×
                    .get_state(&u.new_state)
965304×
                    .map(|s| s.heads)
966304×
                    .unwrap_or_default();
967304×
                report.updated.push(RefUpdated {
968304×
                    name: u.name.clone(),
969304×
                    old_state: u.old_state,
970304×
                    new_state: u.new_state,
971304×
                    heads,
972304×
                });
97332×
            }
974336×
            results.push(RefResult {
975336×
                name: u.name,
976336×
                ok,
977336×
                reason,
978336×
            });
979
        }
980348×
        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
        }
1044348×
        if !names.is_empty() {
1045306×
            self.record_op(
1046306×
                &[op_ref],
1047306×
                &format!("push received: {}", names.join(" ")),
1048306×
                view,
10493×
            )?;
105042×
        }
1051345×
        Ok(report)
1052356×
    }
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
        };
114846×
        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
1284336×
    fn apply_update(
1285336×
        &self,
1286336×
        view: &mut View,
1287336×
        u: &RefUpdate,
1288336×
        policy: Option<&crate::policy::Policy>,
1289336×
    ) -> std::result::Result<(), String> {
1290336×
        if u.name == "policy" {
12910×
            return Err(
12920×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
12930×
            );
1294336×
        }
1295336×
        let empty = self
1296336×
            .store
1297336×
            .put_state(&StateObject::new(vec![]))
1298336×
            .map_err(|e| e.to_string())?;
1299336×
        if u.new_state.is_zero() {
13003×
            return self.apply_deletion(view, u, policy);
1301333×
        }
1302333×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1303333×
        if current != u.old_state {
130412×
            return Err("stale: the remote bookmark has moved; pull first".into());
1305321×
        }
1306321×
        let new_state = self
1307321×
            .store
1308321×
            .get_state(&u.new_state)
1309321×
            .map_err(|_| "new state object is missing".to_string())?;
1310606×
        for h in &new_state.heads {
1311606×
            if !self.store.has(h) {
13121×
                return Err(format!("head {} is missing", h.short(12)));
1313605×
            }
1314
        }
1315320×
        if !u.force {
1316319×
            let old_heads = self
1317319×
                .store
1318319×
                .get_state(&current)
1319319×
                .map_err(|e| e.to_string())?
1320
                .heads;
1321319×
            let closure = self
1322319×
                .closure_in_store(&new_state.heads)
1323319×
                .map_err(|e| e.to_string())?;
1324326×
            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×
                ));
1329318×
            }
13301×
        }
1331319×
        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)?;
1361260×
        }
1362308×
        if let Some(sa) = &u.attestation {
1363105×
            self.record_update_attest(u, sa)?;
1364203×
        }
1365302×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1366302×
        Ok(())
1367336×
    }
1368
1369
    // ------------------------------------------------------------ client side
1370
13711459×
    fn remote_url(&self, name: &str) -> Result<String> {
13721459×
        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×
        })
13881459×
    }
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).
1393793×
    fn check_remote_id(
1394793×
        &self,
1395793×
        remote: &dyn crate::protocol::Remote,
1396793×
        remote_name: &str,
1397793×
        allow_unbound: bool,
1398793×
    ) -> Result<()> {
1399793×
        let theirs = remote.repo_id()?;
1400792×
        if theirs == self.id()? {
1401765×
            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
        ))
1414793×
    }
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`]).
14191087×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
14201087×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
14211087×
        let mut options = RemoteOptions {
14221087×
            repo_id: self.id().ok(),
14231087×
            token: self.config.remote_tokens.get(name).cloned(),
14241087×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
14251087×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
14261087×
            ..RemoteOptions::default()
14271087×
        };
14281087×
        self.fill_credentials(&url, &mut options);
14291087×
        options
14301087×
    }
1431
1432
    /// The user's credential store (`credentials.toml` beside the user
1433
    /// configuration file).
14341108×
    pub fn credentials(&self) -> crate::credentials::Credentials {
14351108×
        crate::credentials::Credentials::at(
14361108×
            self.user_config
14371108×
                .parent()
14381108×
                .map(Path::to_path_buf)
14391108×
                .unwrap_or_else(default_home),
1440
        )
14411108×
    }
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).
14501109×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14511109×
        if options.token.is_some() && options.ca.is_some() {
14521×
            return;
14531108×
        }
14541108×
        let explicit =
14551108×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14561108×
        let stored = self.credentials().options_for(url);
14571108×
        options.token = options.token.take().or(stored.token);
14581108×
        options.ca = options.ca.take().or(stored.ca);
14591108×
        let enclosing = self.enclosing_credentials(url);
14601108×
        if options.token.is_none() {
14611098×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
146210×
        }
14631108×
        if options.ca.is_none() {
14641093×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
146515×
        }
14661108×
        if !explicit {
14671101×
            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×
        }
14731109×
    }
1474
1475
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1476
    /// checkouts, nearest first.
14771108×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
14781108×
        let mut out = Vec::new();
14791108×
        let Some(hub) = crate::credentials::hub_of(url) else {
1480960×
            return out;
1481
        };
1482148×
        let mut at = self.root.parent();
1483600×
        while let Some(dir) = at {
1484452×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14850×
                break;
1486
            };
1487452×
            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
            }
1502452×
            at = dir.parent();
1503
        }
1504148×
        out
15051108×
    }
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
15621070×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15631070×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15641070×
    }
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
1585461×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1586461×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1587461×
    }
1588
1589
    /// The highest policy serial `remote` has ever presented.
1590389×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1591389×
        fs::read_to_string(self.policy_serial_path(remote))
1592389×
            .ok()
1593389×
            .and_then(|s| s.trim().parse().ok())
1594389×
    }
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.
1662389×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1663389×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1664524×
        for st in view
1665389×
            .bookmarks
1666389×
            .values()
1667389×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1668
        {
1669524×
            if let Ok(s) = self.store.get_state(st) {
1670524×
                have.extend(s.heads);
1671524×
            }
1672
        }
1673389×
        have.extend(view.workspaces.values().copied());
1674389×
        Ok(have.into_iter().collect())
1675389×
    }
1676
1677
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1678395×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1679395×
        let remote = self.open_named_remote(remote_name)?;
1680392×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1681390×
        let resp = remote.refs()?;
1682
        // The host's transparency log (spec §14.8): a fork fails here.
1683389×
        let log = self.check_log(
1684389×
            &self.remote_url(remote_name)?,
1685389×
            self.config.remote_cas.get(remote_name).map(Path::new),
1686389×
            &resp,
16870×
        )?;
1688389×
        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.
1694389×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1695389×
        let seen = self.remote_policy_serial(remote_name);
1696389×
        let mut unverified = false;
1697389×
        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 => {
1724351×
                if seen.is_some() {
17250×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1726351×
                }
1727351×
                unverified = true;
1728
            }
1729
        }
1730389×
        let policy = if unverified {
1731351×
            None
1732
        } else {
173338×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1734
        };
1735389×
        let (op_ref, op) = self.head_op()?;
1736389×
        let mut view = op.view.clone();
1737389×
        let have = self.known_heads(&view)?;
1738389×
        let mut report = Vec::new();
1739389×
        let mut skipped = Vec::new();
1740389×
        let max_blob = self.config.max_blob;
1741415×
        for r in resp.refs {
1742415×
            let needed = {
1743415×
                let _t = crate::timing::phase("fetch: negotiate");
1744415×
                remote.negotiate(&have, &r.heads)?
1745
            };
1746415×
            let bundle = {
1747415×
                let _t = crate::timing::phase("fetch: bundle");
1748415×
                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.
1753415×
            let imported = {
1754415×
                let _t = crate::timing::phase("fetch: import");
1755415×
                self.import_bundle(&bundle, false)?
1756
            };
1757415×
            if max_blob.is_some() {
17584×
                self.register_missing_blobs(&imported, remote_name)?;
1759411×
            }
1760546×
            for h in &r.heads {
1761546×
                if !self.store.has(h) {
17620×
                    return fail(format!("remote did not send head {}", h.short(12)));
1763546×
                }
1764
            }
1765415×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1766415×
            if state != r.state {
17670×
                return fail(format!(
1768
                    "remote state {} does not match its heads",
17690×
                    r.state.short(12)
1770
                ));
1771415×
            }
1772415×
            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×
                }
1787374×
            }
1788415×
            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)?;
1835342×
            }
1836403×
            view.remotes
1837403×
                .entry(remote_name.to_string())
1838403×
                .or_default()
1839403×
                .insert(r.name.clone(), state);
1840403×
            report.push((r.name, r.heads, imported.len()));
1841
        }
1842386×
        let mut new_tags = 0;
1843386×
        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).
1882386×
        let mut withdrawn_tags = Vec::new();
1883386×
        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
        }
1901386×
        if view != op.view {
1902370×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
190316×
        }
1904386×
        let _ = self.run_hook(
1905386×
            "post-fetch",
1906386×
            &format!(
1907
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1908386×
                json_str(remote_name),
1909400×
                json_array(report.iter().map(|(n, heads, _)| format!(
1910
                    "{{\"name\":{},\"heads\":{}}}",
1911400×
                    json_str(n),
1912531×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1913
                )))
1914
            ),
1915
        );
1916386×
        Ok(FetchReport {
1917386×
            refs: report,
1918386×
            unverified,
1919386×
            new_tags,
1920386×
            withdrawn_tags,
1921386×
            log_notes,
1922386×
            skipped,
1923386×
        })
1924395×
    }
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).
1991105×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1992105×
        let _wc = self.lock_working_copy()?;
1993105×
        let skipped = self.fetch(remote_name)?.skipped;
1994101×
        let (op_ref, op) = self.head_op()?;
1995101×
        let current = self.config.bookmark.clone();
1996101×
        let mut local_current = self.heads_of(&op.view, &current)?;
1997101×
        local_current.sort();
1998101×
        let mut view = op.view.clone();
1999101×
        let mut current_heads = local_current.clone();
2000101×
        let mut changed = false;
2001101×
        let mut others = Vec::new();
2002101×
        let tracked = op
2003101×
            .view
2004101×
            .remotes
2005101×
            .get(remote_name)
2006101×
            .cloned()
2007101×
            .unwrap_or_default();
2008106×
        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.
2011106×
            let local_state = op.view.bookmarks.get(&name).copied();
2012106×
            if local_state.is_none() && name != current {
20131×
                continue;
2014105×
            }
2015105×
            if local_state == Some(remote_state) {
201610×
                continue;
201795×
            }
201895×
            let local = self.heads_of(&op.view, &name)?;
201995×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2020123×
            if remote_heads.iter().all(|h| local.contains(h)) {
20210×
                continue;
202295×
            }
202395×
            let mut all = local.clone();
202495×
            all.extend(remote_heads);
202595×
            let st = self.load_state_history(&all)?;
202695×
            let mut heads = st.maximal(&all);
202795×
            heads.sort();
202895×
            let mut sorted_local = local;
202995×
            sorted_local.sort();
203095×
            if heads == sorted_local {
20311×
                continue;
203294×
            }
203394×
            view.bookmarks.insert(
203494×
                name.clone(),
203594×
                self.store.put_state(&StateObject::new(heads.clone()))?,
2036
            );
203794×
            if name == current {
203892×
                changed = true;
203992×
                current_heads = heads;
204092×
            } else {
20412×
                others.push(name);
20422×
            }
2043
        }
2044101×
        if changed || !others.is_empty() {
204593×
            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).
2050101×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2051
        Ok(PullReport {
2052101×
            heads: if changed {
205392×
                current_heads
2054
            } else {
20559×
                local_current
2056
            },
2057101×
            changed,
2058101×
            checked_out,
2059101×
            others,
2060101×
            skipped,
2061
        })
2062105×
    }
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.
2099101×
    pub fn follow_bookmark(
2100101×
        &self,
2101101×
        heads: &[ChangeHash],
2102101×
        bookmark: &str,
2103101×
        command: &str,
2104101×
    ) -> Result<bool> {
2105101×
        let snap = self.snapshot(command)?;
2106101×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2107101×
        let mut base = snap.base.maximal(&snap.wc.deps);
2108101×
        base.sort();
2109101×
        let mut target = heads.to_vec();
2110101×
        target.sort();
2111101×
        if base == target {
21128×
            return Ok(false);
211393×
        }
211493×
        let state = self.load_state_history(heads)?;
2115168×
        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);
211893×
        }
211993×
        if clean {
212093×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
212193×
            Ok(true)
2122
        } else {
21230×
            Ok(self
21240×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
21250×
                .is_ok())
2126
        }
2127101×
    }
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.
2287317×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2288317×
        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×
        };
2295317×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2296410×
        for h in changes {
2297410×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2298410×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2299410×
            let mut weight = raw.len() as u64;
2300529×
            for t in &texts {
2301529×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
230226×
                    weight += blob_len(r);
2303503×
                }
2304
            }
2305673×
            for e in &c.edits {
23063×
                if let Edit::Replace { new: Some(b), .. } = e {
23073×
                    weight += blob_len(b);
2308670×
                }
2309
            }
2310410×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
23115×
                out.push(std::mem::take(&mut batch));
23125×
                bytes = 0;
2313405×
            }
2314410×
            batch.push(*h);
2315410×
            bytes += weight;
2316
        }
2317317×
        out.push(batch);
2318317×
        Ok(out)
2319317×
    }
2320
2321372×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2322372×
        let bookmark = self.config.bookmark.clone();
2323372×
        self.push_bookmark(remote_name, &bookmark, force)
2324372×
    }
2325
2326
    /// `push` for a named bookmark (`oxy push -b NAME`).
2327385×
    pub fn push_bookmark(
2328385×
        &self,
2329385×
        remote_name: &str,
2330385×
        bookmark: &str,
2331385×
        force: bool,
2332385×
    ) -> Result<Vec<RefResult>> {
2333385×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2334385×
    }
2335
2336
    /// `push_bookmark`, saying how a long push is going: one line per
2337
    /// batch sent (oxygen#95).
2338393×
    pub fn push_bookmark_with(
2339393×
        &self,
2340393×
        remote_name: &str,
2341393×
        bookmark: &str,
2342393×
        force: bool,
2343393×
        progress: crate::store::Progress,
2344393×
    ) -> Result<Vec<RefResult>> {
2345393×
        let (op_ref, op) = self.head_op()?;
2346393×
        if !op.view.bookmarks.contains_key(bookmark) {
23470×
            return fail(format!("no bookmark {bookmark}"));
2348393×
        }
2349393×
        let bookmark = bookmark.to_string();
2350393×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2351
        // pre-push hook: may veto before the remote is contacted.
2352393×
        self.run_hook(
2353393×
            "pre-push",
2354393×
            &format!(
2355
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2356393×
                json_str(remote_name),
2357393×
                json_str(&bookmark),
2358761×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2359
            ),
23601×
        )?;
2361392×
        let remote = self.open_named_remote(remote_name)?;
2362392×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2363389×
        let resp = remote.refs()?;
2364389×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2365389×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2366389×
        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
            }
2375354×
            _ => None,
2376
        };
2377388×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2378388×
        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`)"));
2380387×
        }
2381387×
        let remote_tags: BTreeSet<String> = resp
2382387×
            .tags
2383387×
            .iter()
2384387×
            .chain(&resp.withdrawn)
2385387×
            .map(|t| t.name.clone())
2386387×
            .collect();
2387387×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2388387×
            .tag_refs()?
2389387×
            .into_iter()
2390387×
            .filter(|t| !remote_tags.contains(&t.name))
2391387×
            .collect();
2392
        // Tags withdrawn here that the remote still has, at the same state
2393
        // (oxygenhub#301).
2394387×
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2395387×
            .withdrawn_refs()?
2396387×
            .into_iter()
2397387×
            .filter(|w| {
23982×
                resp.tags
23992×
                    .iter()
24002×
                    .any(|t| t.name == w.name && t.state == w.state)
24012×
            })
2402387×
            .collect();
2403387×
        let refs = resp.refs;
2404387×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2405387×
        let (remote_state, remote_heads, last_serial) =
2406388×
            match refs.iter().find(|r| r.name == bookmark) {
2407365×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
240822×
                None => (empty, vec![], None),
2409
            };
2410387×
        let new_state = self
2411387×
            .store
2412387×
            .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).
2417387×
        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×
            }]);
2427379×
        }
2428412×
        for h in &remote_heads {
2429412×
            if !self.store.has(h) {
243061×
                return fail(format!(
2431
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
243261×
                    h.short(12)
2433
                ));
2434351×
            }
2435
        }
2436318×
        if !force {
2437318×
            let closure = self.closure_in_store(&local_heads)?;
2438333×
            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)));
2440318×
            }
24410×
        }
2442318×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2443318×
        let key = self.secret_key()?.map(|(k, _)| k);
2444318×
        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
            }
2460206×
        }
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).
2465317×
        let batches = self.push_batches(&to_send)?;
2466317×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2467317×
        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
        }
2491317×
        if batches.len() > 1 {
24921×
            progress(&format!(
24931×
                "part {} of {}: {} changes",
24941×
                batches.len(),
24951×
                batches.len(),
24961×
                last.len()
24971×
            ));
2498316×
        }
2499317×
        let mut bundle = self.bundle_for(last)?;
2500317×
        bundle.objects.push((
2501317×
            ObjectType::State,
2502317×
            StateObject::new(local_heads.clone()).encode(),
2503317×
        ));
2504317×
        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×
            })?),
2515206×
            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).
2520316×
        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()
2530265×
                        .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)?;
2539206×
        }
2540316×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2541110×
            AttestBody::Ref { serial, .. } => Some(serial),
25420×
            _ => None,
2543110×
        });
2544316×
        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.
2546316×
        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.
2565316×
        let tag_signers: Vec<KeyId> = tags_to_send
2566316×
            .iter()
2567316×
            .chain(&withdrawals_to_send)
2568316×
            .filter_map(|t| t.attestation.as_ref())
2569316×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2570316×
            .collect();
2571316×
        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()
257730×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
25782×
                {
25792×
                    bundle.objects.push((ObjectType::Identity, body));
258014×
                }
25810×
            }
2582
        }
2583316×
        if !tag_signers.is_empty() {
258415×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2585301×
        }
2586316×
        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();
2596282×
        }
2597316×
        let results = remote.push(
2598316×
            bundle,
2599316×
            vec![RefUpdate {
2600316×
                name: bookmark.clone(),
2601316×
                old_state: remote_state,
2602316×
                new_state,
2603316×
                force,
2604316×
                attestation,
2605316×
            }],
2606316×
            policy_to_send,
2607316×
            tags_to_send
2608316×
                .into_iter()
2609316×
                .chain(withdrawals_to_send)
2610316×
                .collect(),
26118×
        )?;
261234×
        if let (Some(serial), true) = (
2613308×
            sent_serial,
2614322×
            results.iter().any(|r| r.ok && r.name == "policy"),
2615
        ) {
261634×
            self.record_policy_serial(remote_name, serial)?;
2617274×
        }
2618345×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2619279×
            let mut view = op.view.clone();
2620279×
            view.remotes
2621279×
                .entry(remote_name.to_string())
2622279×
                .or_default()
2623279×
                .insert(bookmark.clone(), new_state);
2624279×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2625276×
            if let Some(s) = serial {
262686×
                self.record_serial(remote_name, &bookmark, s)?;
2627190×
            }
262829×
        }
2629303×
        Ok(results)
2630393×
    }
2631
2632
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2633
    /// bookmark set to the remote's, working copy checked out.
2634256×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2635256×
        Self::clone_with(url, dest, None, &[])
2636256×
    }
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).
2641259×
    pub fn clone_with(
2642259×
        url: &str,
2643259×
        dest: &Path,
2644259×
        max_blob: Option<u64>,
2645259×
        sparse: &[String],
2646259×
    ) -> Result<Repo> {
2647259×
        Self::clone_full(url, dest, max_blob, sparse, None)
2648259×
    }
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
2662260×
    fn clone_full(
2663260×
        url: &str,
2664260×
        dest: &Path,
2665260×
        max_blob: Option<u64>,
2666260×
        sparse: &[String],
2667260×
        depth: Option<u32>,
2668260×
    ) -> Result<Repo> {
2669260×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2670260×
    }
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.
2677266×
    pub fn clone_reporting(
2678266×
        url: &str,
2679266×
        dest: &Path,
2680266×
        max_blob: Option<u64>,
2681266×
        sparse: &[String],
2682266×
        depth: Option<u32>,
2683266×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2684266×
        let options = crate::credentials::Credentials::user().options_for(url);
2685266×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2686266×
    }
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
2738276×
    fn clone_using(
2739276×
        url: &str,
2740276×
        dest: &Path,
2741276×
        max_blob: Option<u64>,
2742276×
        sparse: &[String],
2743276×
        depth: Option<u32>,
2744276×
        options: &RemoteOptions,
2745276×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2746276×
        let remote = open_remote(url, options)?;
2747276×
        let id = remote.repo_id()?;
2748272×
        if id == crate::protocol::UNBOUND_ID {
27492×
            return fail(format!(
2750
                "{url} is empty and unbound: push a repository to it first"
2751
            ));
2752270×
        }
2753270×
        let mut repo = Repo::init_with_id(dest, id)?;
2754270×
        repo.config
2755270×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2756270×
        if let Some(m) = max_blob {
27572×
            repo.config.set("filter.max-blob", &m.to_string())?;
2758268×
        } else if !sparse.is_empty() {
27591×
            repo.config.set("filter.max-blob", "0")?;
2760267×
        }
2761270×
        if !sparse.is_empty() {
27621×
            repo.config.set("filter.paths", &sparse.join(","))?;
2763269×
        }
2764270×
        repo.save_config()?;
2765270×
        let skipped = if let Some(depth) = depth {
27661×
            repo.fetch_shallow("origin", depth)?;
27671×
            Vec::new()
2768
        } else {
2769269×
            repo.fetch("origin")?.skipped
2770
        };
2771268×
        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).
2775268×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2776268×
        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.
2781268×
        let advertised = repo
2782268×
            .open_named_remote("origin")
2783268×
            .ok()
2784268×
            .and_then(|r| r.refs().ok())
2785268×
            .and_then(|r| r.default_bookmark);
2786268×
        let bookmark = advertised
2787268×
            .filter(|b| theirs.contains_key(b))
2788268×
            .or_else(|| {
27897×
                theirs
27907×
                    .contains_key(&repo.config.bookmark)
27917×
                    .then(|| repo.config.bookmark.clone())
27927×
            })
2793268×
            .or_else(|| {
27940×
                (theirs.len() == 1)
27950×
                    .then(|| theirs.keys().next().cloned())
27960×
                    .flatten()
27970×
            })
2798268×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2799268×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
28000×
            return fail(format!("cannot check out {bookmark}: {why}"));
2801268×
        }
2802268×
        let initial = repo.config.bookmark.clone();
2803268×
        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();
2807267×
        }
2808268×
        if let Some(state) = theirs.get(&bookmark).copied() {
2809268×
            let heads = repo.store.get_state(&state)?.heads;
2810268×
            let mut view = op.view.clone();
2811
            // The empty bookmark `init` made goes when another is checked out.
2812268×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
28131×
                view.bookmarks.remove(&initial);
2814267×
            }
2815268×
            view.bookmarks.insert(bookmark, state);
2816268×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2817268×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
28180×
        }
2819268×
        Ok((repo, skipped))
2820276×
    }
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×
}