OXYGENHUB

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

2137 of 2369 lines run, 333 of 444 functions · run #372 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
681828×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
691828×
        self.oxy.join("attest").join(name_file(bookmark))
701828×
    }
71
72
    /// The latest reference attestation stored for a bookmark.
731413×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
741413×
        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
            }
861068×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
870×
            Err(e) => Err(e.into()),
88
        }
891413×
    }
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
961124×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
971124×
        let view = self.view()?;
981124×
        let mut out = Vec::new();
991177×
        for (name, state) in &view.bookmarks {
1001177×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
1011177×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
102230×
                AttestBody::Ref { serial, .. } => Some(serial),
1030×
                _ => None,
104230×
            });
1051177×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1061177×
            let accepted = match &attestation {
107219×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
108958×
                None => None,
109
            };
1101177×
            out.push(RemoteRef {
1111177×
                name: name.clone(),
1121177×
                state: *state,
1131177×
                heads: self.store.get_state(state)?.heads,
1141177×
                attestation,
1151177×
                last_serial,
1161177×
                accepted,
1171177×
                logged: None,
1181177×
                integration: vec![],
119
            });
120
        }
1211124×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1221124×
        let history = self
1231124×
            .policy_history()?
1241124×
            .into_iter()
1251124×
            .filter(|sp| {
126221×
                policy
127221×
                    .as_ref()
128221×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
129221×
            })
1301124×
            .collect();
131
        Ok(RefsResponse {
1321124×
            refs: out,
1331124×
            policy,
1341124×
            tags: self.tag_refs()?,
1351124×
            history,
1361124×
            default_bookmark: Some(self.config.bookmark.clone()),
1371124×
            log: None,
1381124×
            witnesses: vec![],
1391124×
            withdrawn: self.withdrawn_refs()?,
140
        })
1411124×
    }
142
143
    /// Every change reachable from `heads` that is in the store.
1441531×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1451531×
        let mut seen = BTreeSet::new();
1461531×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1475168×
        while let Some(h) = stack.pop() {
1483637×
            if seen.contains(&h) || !self.store.has(&h) {
1491084×
                continue;
1502553×
            }
1512553×
            seen.insert(h);
1522553×
            stack.extend(self.store.get_change_meta(&h)?.deps);
153
        }
1541531×
        Ok(seen)
1551531×
    }
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
1823880×
    fn shallow_path(&self) -> PathBuf {
1833880×
        self.oxy.join("shallow")
1843880×
    }
185
186
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1873871×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1883871×
        fs::read_to_string(self.shallow_path())
1893871×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1903871×
            .unwrap_or_default()
1913871×
    }
192
1931503×
    pub fn is_shallow(&self) -> bool {
1941503×
        !self.boundary().is_empty()
1951503×
    }
196
1979×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1989×
        if boundary.is_empty() {
1991×
            let _ = fs::remove_file(self.shallow_path());
2001×
            return Ok(());
2018×
        }
2028×
        let text: String = boundary
2038×
            .iter()
2049×
            .map(|h| format!("{}\n", h.to_hex()))
2058×
            .collect();
2068×
        write_atomic(&self.shallow_path(), text.as_bytes())
2079×
    }
208
209
    /// Recompute the boundary from what is stored: every dependency of a
210
    /// stored change that is not itself stored.
2117×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2127×
        let mut boundary = self.boundary();
2137×
        boundary.retain(|h| !self.store.has(h));
21412×
        for h in imported {
21515×
            for d in self.store.get_change_meta(h)?.deps {
21615×
                if !self.store.has(&d) {
2173×
                    boundary.insert(d);
21812×
                }
219
            }
220
        }
2217×
        self.write_boundary(&boundary)
2227×
    }
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).
242888×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
243888×
        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.
246888×
        let boundary = self.boundary();
247888×
        let mut out = Vec::new();
248888×
        let mut done: BTreeSet<ChangeHash> = have.clone();
249888×
        done.extend(boundary.iter().copied());
250
        // Iterative post-order DFS.
251888×
        let shallow = self.is_shallow();
2521391×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2533601×
        while let Some((h, expanded)) = stack.pop() {
2542713×
            if done.contains(&h) {
255470×
                continue;
2562243×
            }
2572243×
            if !self.store.has(&h) {
258
                // A shallow repository holds only part of its history; a
259
                // change it lacks is below what it cloned (in a depth-0
260
                // clone, any change of the checkpoint), which the remote
261
                // is assumed to hold, as it is for the boundary (#137).
2621×
                if shallow {
2631×
                    done.insert(h);
2641×
                    continue;
2650×
                }
2660×
                return fail(format!("change {} is not in this repository", h.short(12)));
2672242×
            }
2682242×
            if expanded {
2691121×
                done.insert(h);
2701121×
                out.push(h);
2711121×
                continue;
2721121×
            }
2731121×
            stack.push((h, true));
2741121×
            for d in self.store.get_change_meta(&h)?.deps {
275738×
                if !done.contains(&d) {
276201×
                    stack.push((d, false));
277537×
                }
278
            }
279
        }
280888×
        Ok(out)
281888×
    }
282
283
    /// Bundle changes (in the given dependency order) with their signatures,
284
    /// seals, identities, blobs, chunks.
285337×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
286337×
        self.bundle_of(changes, None, false, false)
287337×
    }
288
289
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2906×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2916×
        let mut out = Vec::new();
2926×
        for r in refs {
2936×
            let (ty, body) = match self.store.get(r) {
2946×
                Ok(x) => x,
2950×
                Err(StoreError::NotFound(_)) => continue,
2960×
                Err(e) => return Err(e.into()),
297
            };
2986×
            if ty == ObjectType::Blob {
2997×
                for c in Blob::decode(&body)?.chunks {
3007×
                    if let Ok((cty, cb)) = self.store.get(&c) {
3017×
                        out.push((cty, cb));
3027×
                    }
303
                }
3040×
            }
3056×
            out.push((ty, body));
306
        }
3076×
        Ok(out)
3086×
    }
309
310
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
311
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
312
    ///
313
    /// This is what a server answers a fetch with, so it also carries what
314
    /// verifies the attestations it serves beside it (see
315
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
31654×
    pub fn bundle_for_filtered(
31754×
        &self,
31854×
        changes: &[ChangeHash],
31954×
        max_blob: Option<u64>,
32054×
    ) -> Result<Bundle> {
32154×
        self.bundle_of(changes, max_blob, false, true)
32254×
    }
323
324
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
325
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
326
    /// with their text blobs and chunks among the objects, so neither side
327
    /// decodes or encodes their text.
328377×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
329377×
        self.bundle_of(changes, max_blob, true, true)
330377×
    }
331
332
    /// The keys that signed the attestations this repository serves with
333
    /// its references: each bookmark's latest and each tag's. A fetch
334
    /// bundle carries their identities and certificates (spec §16.2), so a
335
    /// client can check an attestation whose signer signed none of the
336
    /// changes it receives, a delegate or a short-lived key that only
337
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
338
    /// list per reference, computed once per operation head and kept
339
    /// (every bookmark move and tag is an operation): a client sends one
340
    /// fetch per bookmark, and on a bucket store each signature list is a
341
    /// LIST request, so recomputing per fetch cost metalgear2 (145
342
    /// bookmarks) 14 s a fetch.
343431×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
344
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
345
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
346431×
        let key = (self.oxy.clone(), self.head_op()?.0);
347431×
        if let Some(keys) = SERVED
348431×
            .lock()
349431×
            .unwrap_or_else(|p| p.into_inner())
350431×
            .as_ref()
351431×
            .and_then(|m| m.get(&key))
352
        {
353135×
            return Ok(keys.clone());
354296×
        }
355296×
        let keys = self.attest_signers_now()?;
356296×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
357296×
        let map = served.get_or_insert_with(Default::default);
358
        // One entry per repository: an older operation head is never asked
359
        // for again once a newer one is current.
3606286×
        map.retain(|(oxy, _), _| *oxy != key.0);
361296×
        if map.len() >= 1024 {
3620×
            map.clear();
363296×
        }
364296×
        map.insert(key, keys.clone());
365296×
        Ok(keys)
366431×
    }
367
368296×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
369296×
        let view = self.view()?;
370296×
        let pointers = view
371296×
            .bookmarks
372296×
            .keys()
373306×
            .map(|b| self.ref_attest_path(b))
374296×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
375296×
        let mut keys = BTreeSet::new();
376328×
        for p in pointers {
377328×
            let Ok(text) = fs::read_to_string(&p) else {
378265×
                continue;
379
            };
38063×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3810×
                continue;
382
            };
38363×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
384
        }
385296×
        Ok(keys)
386296×
    }
387
388
    /// `serving`: a fetch's answer, which carries the identities and
389
    /// certificates of [`Repo::served_attest_signers`] too.
390768×
    fn bundle_of(
391768×
        &self,
392768×
        changes: &[ChangeHash],
393768×
        max_blob: Option<u64>,
394768×
        raw: bool,
395768×
        serving: bool,
396768×
    ) -> Result<Bundle> {
397768×
        let mut bundle = Bundle::default();
398768×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
399768×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
4001293×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
4011293×
            if !r.is_zero() && self.store.has(r) {
402384×
                objects.insert(*r);
403909×
            }
4041293×
        };
4051035×
        for h in changes {
406
            // Raw: the stored bytes, and a skeleton for the rest.
4071035×
            let (c, encoded) = if raw {
408558×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
409558×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
4105014×
                for t in texts {
4115014×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
4123×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4133×
                        objects.insert(r);
4143×
                        objects.extend(blob.chunks);
4155011×
                    }
416
                }
417558×
                (skel, Some(bytes))
418
            } else {
419477×
                (self.store.get_change(h)?, None)
420
            };
4211035×
            let sigs = self.store.signatures(h)?;
4221035×
            add_object(&c.author, &mut objects);
4231035×
            for s in &sigs {
42437×
                add_object(&s.key, &mut objects);
42537×
            }
4266006×
            for e in &c.edits {
4276006×
                if let Edit::Replace { old, new, .. } = e {
42822×
                    for b in [old, new].into_iter().flatten() {
42922×
                        if self.store.has(b) {
43022×
                            if let Ok(blob) =
43122×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
432
                            {
43322×
                                if max_blob.is_some_and(|m| blob.length > m) {
4344×
                                    continue;
43518×
                                }
43618×
                                objects.insert(*b);
43718×
                                objects.extend(blob.chunks.iter().copied());
4380×
                            }
4390×
                        }
440
                    }
4415986×
                }
442
            }
4431035×
            for s in self.store.seals_for(h)? {
444110×
                seals.insert(s);
445110×
            }
4461035×
            match encoded {
447558×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
448477×
                None => {
449477×
                    bundle.changes.push((c, sigs));
450477×
                    bundle.hashes.push(*h);
451477×
                }
452
            }
453
        }
454768×
        for r in seals {
455105×
            let attest = self.store.get_attest(&r)?;
456105×
            let sigs = self.store.signatures(&r)?;
457105×
            for s in &sigs {
458105×
                add_object(&s.key, &mut objects);
459105×
            }
460105×
            bundle.attests.push(SignedAttest { attest, sigs });
461
        }
462768×
        let signers: Vec<KeyId> = if serving {
463431×
            let signers = self.served_attest_signers()?;
464431×
            for k in &signers {
465116×
                add_object(k, &mut objects);
466116×
            }
467431×
            signers.into_iter().collect()
468
        } else {
469337×
            Vec::new()
470
        };
471768×
        for r in objects {
472243×
            let (ty, body) = self.store.get(&r)?;
473243×
            bundle.objects.push((ty, body));
474
        }
475768×
        self.attach_certificates_for(&mut bundle, &signers)?;
476768×
        Ok(bundle)
477768×
    }
478
479
    /// Add the certificates of short-lived keys that signed what `bundle`
480
    /// carries, and their issuers' identities, so a receiver can tell who
481
    /// they stand for (spec §14.7). `also` names more signers (a reference
482
    /// attestation sent beside the bundle).
483895×
    pub(crate) fn attach_certificates_for(
484895×
        &self,
485895×
        bundle: &mut Bundle,
486895×
        also: &[KeyId],
487895×
    ) -> Result<()> {
488895×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
489895×
        keys.extend(
490895×
            bundle
491895×
                .changes
492895×
                .iter()
493895×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
494
        );
495895×
        keys.extend(
496895×
            bundle
497895×
                .raw_changes
498895×
                .iter()
499895×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
500
        );
501895×
        keys.extend(
502895×
            bundle
503895×
                .attests
504895×
                .iter()
505895×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
506
        );
507895×
        for k in keys {
508350×
            let Some(r) = self.store.certificate_of(&k)? else {
509301×
                continue;
510
            };
51149×
            let cert = self.store.get_certificate(&r)?;
51249×
            if bundle
51349×
                .certificates
51449×
                .iter()
51549×
                .any(|c| c.cert.hash() == cert.cert.hash())
516
            {
51712×
                continue;
51837×
            }
519
            // An agent's certificate brings its grant's signer too, so the
520
            // receiver can check the grant (oxygen#134).
52137×
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
52281×
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
52381×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
52480×
                    if !bundle
52580×
                        .objects
52680×
                        .iter()
527147×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
52835×
                    {
52935×
                        bundle.objects.push((ObjectType::Identity, body));
53045×
                    }
5311×
                }
532
            }
53337×
            bundle.certificates.push(cert);
534
        }
535895×
        Ok(())
536895×
    }
537
538
    /// Keep the certificates a bundle brings once each verifies with the
539
    /// identity of the issuer it names; one that does not refuses the bundle.
540816×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
541816×
        for c in certs {
54236×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5430×
                RepoError::Msg(format!(
5440×
                    "a certificate names issuer {}, whose identity did not come with it",
5450×
                    c.cert.issuer.short(12)
5460×
                ))
5470×
            })?;
54836×
            c.verify(&issuer)
54936×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
55036×
            self.store.put_identity(&c.cert.key)?;
55136×
            self.store.put_certificate(c)?;
552
        }
553816×
        Ok(())
554816×
    }
555
556
    /// A signer authorized for `reference` by what an issuer certified it
557
    /// as (spec §14.7): a short-lived key with a kept certificate that
558
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
559
    /// signer did not choose) and names a subject the policy grants.
56057×
    pub(crate) fn certified_authorized(
56157×
        &self,
56257×
        p: &crate::policy::Policy,
56357×
        signer: &KeyId,
56457×
        reference: &str,
56557×
        scope: Scope,
56657×
        at_ms: u64,
56757×
    ) -> bool {
56857×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5695×
            return false;
570
        };
57152×
        let Ok(c) = self.store.get_certificate(&r) else {
5720×
            return false;
573
        };
57452×
        let Some(issuer) = p
57552×
            .identity(&c.cert.issuer)
57652×
            .cloned()
57752×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
578
        else {
5790×
            return false;
580
        };
58152×
        c.verify(&issuer).is_ok()
58252×
            && c.cert.key_id() == *signer
58352×
            && c.cert.covers(scope, at_ms)
58442×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
58557×
    }
586
587
    /// Store a bundle's contents. With `strict`, every change must
588
    /// authenticate (signature or seal by its author or a delegate).
589811×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
590811×
        self.import_bundle_inner(bundle, strict, false)
591811×
    }
592
593
    /// Like `import_bundle`, accepting changes whose dependencies are absent
594
    /// (they join the shallow boundary).
5955×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5965×
        self.import_bundle_inner(bundle, strict, true)
5975×
    }
598
599816×
    fn import_bundle_inner(
600816×
        &self,
601816×
        bundle: &Bundle,
602816×
        strict: bool,
603816×
        shallow: bool,
604816×
    ) -> Result<Vec<ChangeHash>> {
605816×
        let batch = self.store.begin_batch()?;
606816×
        let result = self.import_bundle_batched(bundle, strict, shallow);
607816×
        batch.finish()?;
608814×
        result
609816×
    }
610
611816×
    fn import_bundle_batched(
612816×
        &self,
613816×
        bundle: &Bundle,
614816×
        strict: bool,
615816×
        shallow: bool,
616816×
    ) -> Result<Vec<ChangeHash>> {
617816×
        for (ty, _) in &bundle.objects {
6180×
            if !matches!(
619710×
                ty,
620
                ObjectType::Chunk
621
                    | ObjectType::Blob
622
                    | ObjectType::Identity
623
                    | ObjectType::State
624
                    | ObjectType::Checkpoint
625
            ) {
6260×
                return fail(format!("bundle may not carry {} objects", ty.name()));
627710×
            }
628
        }
629
        // All at once: in a large batch they are compressed on every core.
630816×
        let objects: Vec<(ObjectType, &[u8])> = bundle
631816×
            .objects
632816×
            .iter()
633816×
            .map(|(ty, body)| (*ty, body.as_slice()))
634816×
            .collect();
635816×
        self.store.put_many(&objects)?;
636816×
        self.adopt_certificates(&bundle.certificates)?;
637816×
        for sa in &bundle.attests {
638108×
            let r = self.store.put_attest(&sa.attest)?;
639108×
            for sig in &sa.sigs {
640108×
                self.store.put_signature(&r, sig)?;
641
            }
642108×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
643113×
                for h in hashes {
644113×
                    self.store.index_seal(h, &r)?;
645
                }
6460×
            }
647
        }
648
        // Each change's hash: from the bundle when its maker knew it, else
649
        // worked out once (for a change adding a whole tree, hashing is
650
        // chunking all its text).
651816×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
652807×
            bundle.hashes.clone()
653
        } else {
6549×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
655
        };
656816×
        let raw_hashes: Vec<ChangeHash> = bundle
657816×
            .raw_changes
658816×
            .iter()
659816×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
660816×
            .collect();
661816×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
662816×
        let boundary = self.boundary();
663816×
        let mut imported = Vec::new();
664
        // Changes as stored: checked, then stored as they are, their text
665
        // blobs having come with the objects.
666816×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
667559×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
668559×
            for d in &skel.deps {
669395×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
670
                {
6710×
                    return fail(format!(
672
                        "change {} depends on {}, which is neither stored nor in the bundle",
6730×
                        h.short(12),
6740×
                        d.short(12)
675
                    ));
676395×
                }
677
            }
6785015×
            for t in texts {
6795015×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6804×
                    if !self.store.has(&r) {
6811×
                        return fail(format!(
682
                            "change {} came without its text blob {}",
6831×
                            h.short(12),
6841×
                            r.short(12)
685
                        ));
6863×
                    }
6875011×
                }
688
            }
689558×
            self.store.put(ObjectType::Change, bytes)?;
690558×
            for sig in sigs {
69113×
                self.store.put_signature(&h, sig)?;
692
            }
693558×
            imported.push(h);
694
        }
695815×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
696504×
            for d in &c.deps {
697297×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
698
                {
6993×
                    return fail(format!(
700
                        "change {} depends on {}, which is neither stored nor in the bundle",
7013×
                        h.short(12),
7023×
                        d.short(12)
703
                    ));
704294×
                }
705
            }
706501×
            let stored = self.store.put_change(c)?;
707501×
            if stored != h {
7080×
                return fail(format!(
709
                    "change {} is not the change the bundle names",
7100×
                    h.short(12)
711
                ));
712501×
            }
713501×
            for sig in sigs {
71433×
                self.store.put_signature(&h, sig)?;
715
            }
716501×
            imported.push(h);
717
        }
718812×
        if strict {
71967×
            for h in &imported {
72039×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7214×
                    return fail(format!(
722
                        "change {} is not authenticated by its author",
7234×
                        h.short(12)
724
                    ));
72535×
                }
726
            }
727745×
        }
728808×
        Ok(imported)
729816×
    }
730
731
    /// Verify a reference attestation against an update it claims to describe.
732
    /// `allow_equal` lets a client re-read the attestation it already has; a
733
    /// server receiving a push requires a strictly greater serial.
734
    /// A reference attestation signed by a delegate of an identity the
735
    /// rule lists is authorized as that identity (spec §14.5): the identity
736
    /// named the delegate with the `refs` scope, still in force at `at_ms`
737
    /// (the attestation's wall time), and the policy names the identity.
738
    /// Revoked keys authorize nothing either way.
73972×
    pub(crate) fn delegate_authorized(
74072×
        &self,
74172×
        p: &crate::policy::Policy,
74272×
        signer: &KeyId,
74372×
        reference: &str,
74472×
        at_ms: u64,
74572×
    ) -> bool {
74672×
        if p.is_revoked(signer) {
7471×
            return false;
74871×
        }
74971×
        let Some(rule) = p.rule_for(reference) else {
7500×
            return false;
751
        };
75272×
        rule.keys.iter().any(|k| {
75372×
            !p.is_revoked(k)
75472×
                && p.identity(k)
75572×
                    .cloned()
75672×
                    .or_else(|| self.store.get_identity(k).ok())
75772×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
75872×
        })
75972×
    }
760
761
    /// A lasting attestation (a tag) signed by a key the policy has since
762
    /// rotated away from (spec §14.2) is authorized as the key that
763
    /// succeeded it: a key the rule lists reaches the signer through
764
    /// `previous` links, and the attestation is dated (`at_ms`) before the
765
    /// signer's successor was made, so a superseded key makes nothing new.
766
    /// Revoked keys authorize nothing.
76727×
    pub(crate) fn predecessor_authorized(
76827×
        &self,
76927×
        p: &crate::policy::Policy,
77027×
        signer: &KeyId,
77127×
        reference: &str,
77227×
        at_ms: u64,
77327×
    ) -> bool {
77427×
        if p.is_revoked(signer) {
7750×
            return false;
77627×
        }
77727×
        let Some(rule) = p.rule_for(reference) else {
7780×
            return false;
779
        };
78028×
        let identity = |k: &KeyId| {
78128×
            p.identity(k)
78228×
                .cloned()
78328×
                .or_else(|| self.store.get_identity(k).ok())
78428×
        };
78527×
        rule.keys.iter().any(|k| {
78627×
            if p.is_revoked(k) {
7870×
                return false;
78827×
            }
78927×
            let mut cur = identity(k);
79027×
            for _ in 0..32 {
79128×
                let Some(id) = cur else {
7920×
                    return false;
793
                };
7941×
                match id.previous {
7956×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7961×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
79722×
                    _ => return false,
798
                }
799
            }
8000×
            false
80127×
        })
80227×
    }
803
804106×
    fn check_ref_attest(
805106×
        &self,
806106×
        sa: &SignedAttest,
807106×
        name: &str,
808106×
        old_state: &ObjectRef,
809106×
        new_state: &ObjectRef,
810106×
        last_serial: Option<u64>,
811106×
        allow_equal: bool,
812106×
    ) -> std::result::Result<u64, String> {
813104×
        let serial =
814106×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
815104×
        self.verify_attest_signature(sa)?;
816104×
        Ok(serial)
817106×
    }
818
819
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
820
    /// attestation describes this update of this repository with a serial
821
    /// past the last seen.
822179×
    fn check_ref_attest_body(
823179×
        &self,
824179×
        sa: &SignedAttest,
825179×
        name: &str,
826179×
        old_state: &ObjectRef,
827179×
        new_state: &ObjectRef,
828179×
        last_serial: Option<u64>,
829179×
        allow_equal: bool,
830179×
    ) -> std::result::Result<u64, String> {
831
        let AttestBody::Ref {
832179×
            name: n,
833179×
            old_state: o,
834179×
            new_state: nw,
835179×
            serial,
836179×
        } = &sa.attest.body
837
        else {
8380×
            return Err("attestation is not a ref attestation".into());
839
        };
840179×
        if n != name || o != old_state || nw != new_state {
8411×
            return Err("attestation does not describe this update".into());
842178×
        }
843178×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8440×
            return Err("attestation is for a different repository".into());
845178×
        }
846178×
        if let Some(last) = last_serial {
84793×
            if *serial < last || (*serial == last && !allow_equal) {
8481×
                return Err(format!(
8491×
                    "attestation serial {serial} is not greater than the last seen {last}"
8501×
                ));
85192×
            }
85285×
        }
853177×
        Ok(*serial)
854179×
    }
855
856
    /// An attestation's first signature verifies with its signer's
857
    /// identity, which must be stored here.
858177×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
859177×
        let r = sa.attest.hash();
860177×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
861177×
        let id = self
862177×
            .store
863177×
            .get_identity(&sig.key)
864177×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
865171×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
866177×
    }
867
868
    /// Accept a push (spec §16.4). Without a trust policy every repository
869
    /// is unverified, so unsigned changes and unattested updates are accepted;
870
    /// attestations that are present must still be valid. With a policy,
871
    /// every change and update is checked against it. A newer policy in the
872
    /// push is applied first when it is signed by the current roots.
873317×
    pub fn receive_push(
874317×
        &self,
875317×
        bundle: Bundle,
876317×
        updates: Vec<RefUpdate>,
877317×
        policy: Option<SignedPolicy>,
878317×
        tags: Vec<crate::protocol::TagRef>,
879317×
    ) -> Result<Vec<RefResult>> {
880317×
        Ok(self
881317×
            .receive_push_report(bundle, updates, policy, tags)?
882
            .results)
883317×
    }
884
885
    /// `receive_push` with what a host wants to log: each accepted
886
    /// reference's old and new state and heads, and the changes this push
887
    /// stored (hub spec §6.12).
888361×
    pub fn receive_push_report(
889361×
        &self,
890361×
        bundle: Bundle,
891361×
        updates: Vec<RefUpdate>,
892361×
        policy: Option<SignedPolicy>,
893361×
        tags: Vec<crate::protocol::TagRef>,
894361×
    ) -> Result<PushReport> {
895
        // Updates are checked against the head as it is now, not as this
896
        // handle first read it (oxygenhub#249): another push may have
897
        // landed since.
898361×
        self.refresh()?;
899361×
        let mut report = PushReport::default();
900361×
        let results = &mut report.results;
901361×
        if let Some(sp) = policy {
90236×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
90334×
                Ok(()) => {
90434×
                    results.push(RefResult {
90534×
                        name: "policy".into(),
90634×
                        ok: true,
90734×
                        reason: format!("serial {}", sp.policy.serial),
90834×
                    });
90934×
                }
9102×
                Err(e) => {
9112×
                    results.push(RefResult {
9122×
                        name: "policy".into(),
9132×
                        ok: false,
9142×
                        reason: e,
9152×
                    });
9162×
                    for u in updates {
9170×
                        results.push(RefResult {
9180×
                            name: u.name,
9190×
                            ok: false,
9200×
                            reason: "policy update was rejected".into(),
9210×
                        });
9220×
                    }
9232×
                    return Ok(report);
924
                }
925
            }
926325×
        }
927359×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
928
        // A push of objects alone (one batch of a long history, oxygen#95)
929
        // names no reference: its outcome is reported as `objects`.
930359×
        let objects_only = updates.is_empty() && tags.is_empty();
931359×
        match self.import_bundle(&bundle, policy.is_some()) {
932353×
            Ok(imported) => {
933353×
                if objects_only {
93411×
                    results.push(RefResult {
93511×
                        name: OBJECTS_RESULT.into(),
93611×
                        ok: true,
93711×
                        reason: format!("{} changes stored", imported.len()),
93811×
                    });
939342×
                }
940353×
                report.imported = imported;
941
            }
9426×
            Err(e) => {
9436×
                if objects_only {
9440×
                    results.push(RefResult {
9450×
                        name: OBJECTS_RESULT.into(),
9460×
                        ok: false,
9470×
                        reason: e.to_string(),
9480×
                    });
9496×
                }
9506×
                for u in updates {
9516×
                    results.push(RefResult {
9526×
                        name: u.name,
9536×
                        ok: false,
9546×
                        reason: e.to_string(),
9556×
                    });
9566×
                }
9576×
                return Ok(report);
958
            }
959
        }
960353×
        let (op_ref, op) = self.head_op()?;
961353×
        let mut view = op.view.clone();
962353×
        let mut names = Vec::new();
963353×
        for u in updates {
964337×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
965337×
            let (ok, reason) = match outcome {
966309×
                Ok(()) => (true, String::new()),
96728×
                Err(e) => (false, e),
968
            };
969337×
            if ok {
970309×
                names.push(u.name.clone());
971309×
                let heads = self
972309×
                    .store
973309×
                    .get_state(&u.new_state)
974309×
                    .map(|s| s.heads)
975309×
                    .unwrap_or_default();
976309×
                report.updated.push(RefUpdated {
977309×
                    name: u.name.clone(),
978309×
                    old_state: u.old_state,
979309×
                    new_state: u.new_state,
980309×
                    heads,
981309×
                });
98228×
            }
983337×
            results.push(RefResult {
984337×
                name: u.name,
985337×
                ok,
986337×
                reason,
987337×
            });
988
        }
989353×
        for t in &tags {
99022×
            let name = format!("tags/{}", t.name);
99122×
            if t.is_withdrawal() {
9923×
                match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut TagCheck::Received)
993
                {
9942×
                    Ok(removed) => {
995
                        // A withdrawal is an update to nothing, as a
996
                        // bookmark's deletion is.
9972×
                        if removed {
9982×
                            report.updated.push(RefUpdated {
9992×
                                name: name.clone(),
10002×
                                old_state: t.state,
10012×
                                new_state: ObjectRef::ZERO,
10022×
                                heads: vec![],
10032×
                            });
10042×
                        }
10052×
                        names.push(name.clone());
10062×
                        results.push(RefResult {
10072×
                            name,
1008
                            ok: true,
10092×
                            reason: if removed {
10102×
                                "withdrawn"
1011
                            } else {
10120×
                                "already withdrawn"
1013
                            }
10142×
                            .into(),
1015
                        });
1016
                    }
10171×
                    Err(e) => results.push(RefResult {
10181×
                        name,
10191×
                        ok: false,
10201×
                        reason: e.reason,
10211×
                    }),
1022
                }
10233×
                continue;
102419×
            }
102519×
            let new = !view.tags.contains_key(&t.name);
102619×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
1027
                Ok(()) => {
1028
                    // A tag new here is an update too, so a hub can start
1029
                    // its pipeline's tag jobs (oxygenflow#24); one it
1030
                    // already had, sent again, is not.
103114×
                    if new {
103213×
                        report.updated.push(RefUpdated {
103313×
                            name: name.clone(),
103413×
                            old_state: ObjectRef::ZERO,
103513×
                            new_state: t.state,
103613×
                            heads: t.heads.clone(),
103713×
                        });
103813×
                    }
103914×
                    names.push(name.clone());
104014×
                    results.push(RefResult {
104114×
                        name,
104214×
                        ok: true,
104314×
                        reason: String::new(),
104414×
                    });
1045
                }
10465×
                Err(e) => results.push(RefResult {
10475×
                    name,
10485×
                    ok: false,
10495×
                    reason: e.reason,
10505×
                }),
1051
            }
1052
        }
1053353×
        if !names.is_empty() {
1054311×
            self.record_op(
1055311×
                &[op_ref],
1056311×
                &format!("push received: {}", names.join(" ")),
1057311×
                view,
10583×
            )?;
105942×
        }
1060350×
        Ok(report)
1061361×
    }
1062
1063
    /// Check an update's attestation against the latest one for its
1064
    /// reference and store it as the new latest. Failures say what was
1065
    /// being done, for which reference, so a refused push can be diagnosed
1066
    /// from its reason alone.
1067106×
    fn record_update_attest(
1068106×
        &self,
1069106×
        u: &RefUpdate,
1070106×
        sa: &SignedAttest,
1071106×
    ) -> std::result::Result<(), String> {
1072106×
        let name = &u.name;
1073106×
        let last = self
1074106×
            .latest_ref_attest(name)
1075106×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1076106×
            .and_then(|(_, a)| match a.attest.body {
107765×
                AttestBody::Ref { serial, .. } => Some(serial),
10780×
                _ => None,
107965×
            });
1080106×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1081104×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1082104×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1083103×
        for sig in &sa.sigs {
1084103×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1085
        }
1086103×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1087
        // Signed by a short-lived key: a host records when it accepted it.
1088100×
        let certified = sa
1089100×
            .sigs
1090100×
            .first()
1091100×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
1092100×
        if certified {
10936×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
109494×
        }
1095100×
        Ok(())
1096106×
    }
1097
1098
    /// Record that this host accepted attestation `r` now, signed with its
1099
    /// acceptor key (spec §14.7); nothing without one.
110011×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
110111×
        let Some(acceptor) = &self.acceptor else {
11027×
            return Ok(());
1103
        };
11044×
        let (id, sk) = (&acceptor.0, &acceptor.1);
11054×
        let attest = Attest {
11064×
            repo: self.id()?,
11074×
            hlc: Hlc::now(),
11084×
            body: AttestBody::Accepted { attest: *r },
1109
        };
11104×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
11114×
        self.store.put_identity(id)?;
11124×
        let a = self.store.put_attest(&attest)?;
11134×
        self.store.put_signature(&a, &sig)?;
11144×
        self.store.index_add_pub("accepted", r, &a)?;
11154×
        Ok(())
111611×
    }
1117
1118
    /// The host's acceptance of attestation `r`, if one was recorded.
1119227×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1120227×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1121206×
            return Ok(None);
1122
        };
1123
        Ok(Some(SignedAttest {
112421×
            attest: self.store.get_attest(&a)?,
112521×
            sigs: self.store.signatures(&a)?,
1126
        }))
1127227×
    }
1128
1129
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1130
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1131
    /// signer's certificate and accepts `sa`; else the attestation's own
1132
    /// time, which the signer chose.
113331×
    pub(crate) fn certified_time(
113431×
        &self,
113531×
        signer: &KeyId,
113631×
        sa: &SignedAttest,
113731×
        accepted: Option<&SignedAttest>,
113831×
    ) -> u64 {
113931×
        self.issuer_acceptance(signer, sa, accepted)
114031×
            .unwrap_or(sa.attest.hlc.wall_ms)
114131×
    }
1142
1143
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1144
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
1145101×
    pub(crate) fn issuer_acceptance(
1146101×
        &self,
1147101×
        signer: &KeyId,
1148101×
        sa: &SignedAttest,
1149101×
        accepted: Option<&SignedAttest>,
1150101×
    ) -> Option<u64> {
1151101×
        let acc = accepted?;
115246×
        let c = self.store.certificate_of(signer).ok().flatten()?;
115346×
        let cert = self.store.get_certificate(&c).ok()?;
115446×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11550×
            return None;
1156
        };
115751×
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
115843×
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
115943×
        (*attest == sa.attest.hash()
116042×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
116143×
        .then_some(acc.attest.hlc.wall_ms)
1162101×
    }
1163
1164
    /// Keep an acceptance this repository was given for attestation `r`
1165
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1166
    /// what it accepts.
11679×
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
11689×
        let a = self.store.put_attest(&acc.attest)?;
116911×
        for sig in &acc.sigs {
117011×
            self.store.put_signature(&a, sig)?;
1171
        }
11729×
        self.store.index_add_pub("accepted", r, &a)?;
11739×
        Ok(())
11749×
    }
1175
1176
    /// A fetched bookmark's attestation by a signer the policy does not
1177
    /// list itself: a delegate or a short-lived key, whose authority
1178
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1179
    /// attestation's integrated time when the host's log gives one; else
1180
    /// as before, at the host's acceptance for a certified signer, when it
1181
    /// countersigned one, or at the attestation's own time, and said so
1182
    /// when the host keeps a log. Failing at the integrated time but not
1183
    /// as before is a note while logs are new; a large gap between the
1184
    /// claimed and the integrated time is a note.
1185
    #[allow(clippy::too_many_arguments)]
118627×
    pub(crate) fn authorize_in_time(
118727×
        &self,
118827×
        p: &crate::policy::Policy,
118927×
        remote_name: &str,
119027×
        r: &crate::protocol::RemoteRef,
119127×
        sa: &SignedAttest,
119227×
        signer: &KeyId,
119327×
        log: &super::transparency::LogCheck,
119427×
        notes: &mut Vec<String>,
119527×
    ) -> Result<()> {
1196
        use super::transparency::{gap_note, judge, Timed};
119727×
        let own = sa.attest.hlc.wall_ms;
119827×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
119927×
        let time = log.time_of(&r.name);
120029×
        let check = |t_delegate: u64, t_cert: u64| {
120129×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
120227×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
120329×
        };
120427×
        let before = if at != own {
12057×
            "the host's acceptance"
1206
        } else {
120720×
            "the time it claims"
1208
        };
120927×
        let what = format!("{remote_name}/{}", r.name);
121027×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1211
            Timed::Refused => {
12121×
                return fail(format!(
1213
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
12141×
                    signer.short(12)
1215
                ))
1216
            }
12173×
            Timed::Integrated => {}
12181×
            Timed::Disagrees => notes.push(format!(
1219
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
12201×
                signer.short(12),
12211×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1222
            )),
12231×
            Timed::Fallback if log.kept => notes.push(format!(
1224
                "{what}: {} checked at {before}, not at a witnessed time: {}",
12251×
                signer.short(12),
12261×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1227
            )),
122821×
            Timed::Fallback => {}
1229
        }
123026×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
12312×
            notes.push(format!("{what}'s attestation {n}"));
123224×
        }
123326×
        Ok(())
123427×
    }
1235
1236
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1237
    /// at `old_state`, is never the bookmark a non-bare repository has
1238
    /// checked out (a bare one's default is its host's to protect, see
1239
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1240
    /// an attestation by a key that may update it.
1241
    /// The deletion's attestation stays the bookmark's latest, so an older
1242
    /// one cannot be replayed to bring it back.
12433×
    fn apply_deletion(
12443×
        &self,
12453×
        view: &mut View,
12463×
        u: &RefUpdate,
12473×
        policy: Option<&crate::policy::Policy>,
12483×
    ) -> std::result::Result<(), String> {
12493×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
12500×
            return Err(format!("no bookmark {:?} to delete", u.name));
1251
        };
12523×
        if current != u.old_state {
12530×
            return Err("stale: the remote bookmark has moved; pull first".into());
12543×
        }
12553×
        if !self.is_bare() && u.name == self.config.bookmark {
12561×
            return Err(format!(
12571×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
12581×
                u.name
12591×
            ));
12602×
        }
12612×
        if let Some(p) = policy {
12620×
            let Some(sa) = &u.attestation else {
12630×
                return Err(format!(
12640×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12650×
                    u.name
12660×
                ));
1267
            };
12680×
            let signer = sa
12690×
                .sigs
12700×
                .first()
12710×
                .map(|s| s.key)
12720×
                .ok_or("attestation carries no signature")?;
1273
            // Received now: the receiver's own clock is the trusted time.
12740×
            let now = Hlc::now().wall_ms;
12750×
            if !p.authorizes(&signer, &u.name)
12760×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12770×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1278
            {
12790×
                return Err(format!(
12800×
                    "key {} may not delete {:?} under this repository's policy",
12810×
                    signer.short(12),
12820×
                    u.name
12830×
                ));
12840×
            }
12852×
        }
12862×
        if let Some(sa) = &u.attestation {
12871×
            self.record_update_attest(u, sa)?;
12881×
        }
12892×
        view.bookmarks.remove(&u.name);
12902×
        Ok(())
12913×
    }
1292
1293337×
    fn apply_update(
1294337×
        &self,
1295337×
        view: &mut View,
1296337×
        u: &RefUpdate,
1297337×
        policy: Option<&crate::policy::Policy>,
1298337×
    ) -> std::result::Result<(), String> {
1299337×
        if u.name == "policy" {
13000×
            return Err(
13010×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
13020×
            );
1303337×
        }
1304337×
        let empty = self
1305337×
            .store
1306337×
            .put_state(&StateObject::new(vec![]))
1307337×
            .map_err(|e| e.to_string())?;
1308337×
        if u.new_state.is_zero() {
13093×
            return self.apply_deletion(view, u, policy);
1310334×
        }
1311334×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1312334×
        if current != u.old_state {
13138×
            return Err("stale: the remote bookmark has moved; pull first".into());
1314326×
        }
1315326×
        let new_state = self
1316326×
            .store
1317326×
            .get_state(&u.new_state)
1318326×
            .map_err(|_| "new state object is missing".to_string())?;
1319631×
        for h in &new_state.heads {
1320631×
            if !self.store.has(h) {
13211×
                return Err(format!("head {} is missing", h.short(12)));
1322630×
            }
1323
        }
1324325×
        if !u.force {
1325324×
            let old_heads = self
1326324×
                .store
1327324×
                .get_state(&current)
1328324×
                .map_err(|e| e.to_string())?
1329
                .heads;
1330324×
            let closure = self
1331324×
                .closure_in_store(&new_state.heads)
1332324×
                .map_err(|e| e.to_string())?;
1333341×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
13341×
                return Err(format!(
13351×
                    "not a fast-forward: current head {} would be dropped (use --force)",
13361×
                    h.short(12)
13371×
                ));
1338323×
            }
13391×
        }
1340324×
        if let Some(p) = policy {
134159×
            let Some(sa) = &u.attestation else {
13421×
                return Err(format!(
13431×
                    "{:?} requires a signed reference attestation under this repository's policy",
13441×
                    u.name
13451×
                ));
1346
            };
134758×
            let signer = sa
134858×
                .sigs
134958×
                .first()
135058×
                .map(|s| s.key)
135158×
                .ok_or("attestation carries no signature")?;
1352
            // Received now: the receiver's own clock is the trusted time.
135358×
            let now = Hlc::now().wall_ms;
135458×
            if !p.authorizes(&signer, &u.name)
135519×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
135616×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1357
            {
135810×
                return Err(format!(
135910×
                    "key {} may not update {:?} under this repository's policy",
136010×
                    signer.short(12),
136110×
                    u.name
136210×
                ));
136348×
            }
136448×
            let old_heads = self
136548×
                .store
136648×
                .get_state(&current)
136748×
                .map_err(|e| e.to_string())?
1368
                .heads;
136948×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1370265×
        }
1371313×
        if let Some(sa) = &u.attestation {
1372105×
            self.record_update_attest(u, sa)?;
1373208×
        }
1374307×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1375307×
        Ok(())
1376337×
    }
1377
1378
    // ------------------------------------------------------------ client side
1379
13801494×
    fn remote_url(&self, name: &str) -> Result<String> {
13811494×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13823×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13833×
            RepoError::Msg(match names.as_slice() {
13843×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
13851×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1386
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
13871×
                    names.join(", "),
13881×
                    names[0],
13891×
                    names[0]
1390
                ),
13910×
                _ => format!(
1392
                    "no remote named {name:?}; this repository has {}",
13930×
                    names.join(", ")
1394
                ),
1395
            })
13963×
        })
13971494×
    }
1398
1399
    /// Refuse a remote that is another repository. An **unbound** remote
1400
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1401
    /// for pushes, which bind it to this repository's id (spec §16.1).
1402813×
    fn check_remote_id(
1403813×
        &self,
1404813×
        remote: &dyn crate::protocol::Remote,
1405813×
        remote_name: &str,
1406813×
        allow_unbound: bool,
1407813×
    ) -> Result<()> {
1408813×
        let theirs = remote.repo_id()?;
1409812×
        if theirs == self.id()? {
1410784×
            return Ok(());
141128×
        }
141228×
        if theirs == crate::protocol::UNBOUND_ID {
141325×
            if allow_unbound {
141424×
                return Ok(());
14151×
            }
14161×
            return fail(format!(
1417
                "remote {remote_name:?} is empty and unbound: push to it first"
1418
            ));
14193×
        }
14203×
        fail(format!(
1421
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1422
        ))
1423813×
    }
1424
1425
    /// Credentials and trust for a remote: `remote.<name>.token` and
1426
    /// `remote.<name>.ca`, else the defaults for its URL
1427
    /// ([`Repo::fill_credentials`]).
14281113×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
14291113×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
14301113×
        let mut options = RemoteOptions {
14311113×
            repo_id: self.id().ok(),
14321113×
            token: self.config.remote_tokens.get(name).cloned(),
14331113×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
14341113×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
14351113×
            ..RemoteOptions::default()
14361113×
        };
14371113×
        self.fill_credentials(&url, &mut options);
14381113×
        options
14391113×
    }
1440
1441
    /// The user's credential store (`credentials.toml` beside the user
1442
    /// configuration file).
14431134×
    pub fn credentials(&self) -> crate::credentials::Credentials {
14441134×
        crate::credentials::Credentials::at(
14451134×
            self.user_config
14461134×
                .parent()
14471134×
                .map(Path::to_path_buf)
14481134×
                .unwrap_or_else(default_home),
1449
        )
14501134×
    }
1451
1452
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1453
    /// then the user's credential store for its hub, then a remote on the
1454
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1455
    /// When the token is not this remote's own or the environment's, the
1456
    /// other tokens enclosing checkouts hold for the hub are kept to try
1457
    /// if it is refused: a stale stored login must not hide a parent's
1458
    /// good token (oxygen#112).
14591135×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14601135×
        if options.token.is_some() && options.ca.is_some() {
14611×
            return;
14621134×
        }
14631134×
        let explicit =
14641134×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14651134×
        let stored = self.credentials().options_for(url);
14661134×
        options.token = options.token.take().or(stored.token);
14671134×
        options.ca = options.ca.take().or(stored.ca);
14681134×
        let enclosing = self.enclosing_credentials(url);
14691134×
        if options.token.is_none() {
14701124×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
147110×
        }
14721134×
        if options.ca.is_none() {
14731118×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
147416×
        }
14751134×
        if !explicit {
14761127×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
14775×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
14782×
                    options.fallback_tokens.push(t);
14793×
                }
1480
            }
14817×
        }
14821135×
    }
1483
1484
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1485
    /// checkouts, nearest first.
14861134×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
14871134×
        let mut out = Vec::new();
14881134×
        let Some(hub) = crate::credentials::hub_of(url) else {
1489982×
            return out;
1490
        };
1491152×
        let mut at = self.root.parent();
1492616×
        while let Some(dir) = at {
1493464×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14940×
                break;
1495
            };
1496464×
            for (key, remote_url) in &cfg {
149715×
                let Some(name) = key
149815×
                    .strip_prefix("remote.")
149915×
                    .and_then(|k| k.strip_suffix(".url"))
1500
                else {
15017×
                    continue;
1502
                };
15038×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
15041×
                    continue;
15057×
                }
15067×
                out.push((
15077×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
15087×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
15097×
                ));
1510
            }
1511464×
            at = dir.parent();
1512
        }
1513152×
        out
15141134×
    }
1515
1516
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1517
    /// no changes and no reference updates, which the receiver stores.
15180×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
15190×
        let remote = self.open_named_remote(remote_name)?;
15200×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
15210×
        let mut bundle = Bundle::default();
15220×
        for r in seals {
15230×
            let attest = self.store.get_attest(r)?;
15240×
            let sigs = self.store.signatures(r)?;
15250×
            bundle
15260×
                .attests
15270×
                .push(crate::protocol::SignedAttest { attest, sigs });
1528
        }
15290×
        let results = remote.push(bundle, vec![], None, vec![])?;
15300×
        if let Some(r) = results.iter().find(|r| !r.ok) {
15310×
            return fail(format!("{}: {}", r.name, r.reason));
15320×
        }
15330×
        Ok(())
15340×
    }
1535
1536
    /// The remote whose URL starts with `base` (a hub), if configured.
15374×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
15384×
        let base = base.trim_end_matches('/');
15394×
        self.config
15404×
            .remotes
15414×
            .iter()
15424×
            .find(|(_, url)| url.trim_end_matches('/') == base)
15434×
            .map(|(name, _)| name.clone())
15444×
    }
1545
1546
    /// Open a remote by name or, failing that, by URL with the default
1547
    /// credentials (see [`Repo::credentials_for`]).
15480×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15490×
        if let Some(name) = self.remote_for_url(url) {
15500×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15510×
        }
15520×
        let options = RemoteOptions {
15530×
            repo_id: self.id().ok(),
15540×
            ..self.credentials_for(url)
15550×
        };
15560×
        Ok((url.to_string(), open_remote(url, &options)?))
15570×
    }
1558
1559
    /// Credentials for a URL: those of the configured remote with that
1560
    /// URL, else the environment's.
15614×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
15624×
        match self.remote_for_url(url) {
15634×
            Some(name) => self.remote_options(&name),
15640×
            None => RemoteOptions {
15650×
                repo_id: self.id().ok(),
15660×
                ..self.credentials_for(url)
15670×
            },
1568
        }
15694×
    }
1570
15711096×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15721096×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15731096×
    }
1574
1575220×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1576220×
        self.oxy
1577220×
            .join("remotes")
1578220×
            .join(remote)
1579220×
            .join(format!("{bookmark}.serial"))
1580220×
    }
1581
158273×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
158373×
        fs::read_to_string(self.serial_path(remote, bookmark))
158473×
            .ok()
158573×
            .and_then(|s| s.trim().parse().ok())
158673×
    }
1587
1588147×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1589147×
        let p = self.serial_path(remote, bookmark);
1590147×
        fs::create_dir_all(p.parent().unwrap())?;
1591147×
        write_atomic(&p, serial.to_string().as_bytes())
1592147×
    }
1593
1594470×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1595470×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1596470×
    }
1597
1598
    /// The highest policy serial `remote` has ever presented.
1599398×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1600398×
        fs::read_to_string(self.policy_serial_path(remote))
1601398×
            .ok()
1602398×
            .and_then(|s| s.trim().parse().ok())
1603398×
    }
1604
160572×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
160672×
        let p = self.policy_serial_path(remote);
160772×
        fs::create_dir_all(p.parent().unwrap())?;
160872×
        write_atomic(&p, serial.to_string().as_bytes())
160972×
    }
1610
161132×
    fn lazy_dir(&self) -> PathBuf {
161232×
        self.oxy.join("lazy")
161332×
    }
1614
1615
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
16165×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
16175×
        fs::create_dir_all(self.lazy_dir())?;
16185×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
16195×
    }
1620
1621
    /// Which remote promised an absent blob, if any.
162217×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
162317×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
162417×
            .ok()
162517×
            .map(|s| s.trim().to_string())
162617×
    }
1627
1628
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
16295×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
16305×
        let Some(remote_name) = self.lazy_remote(blob) else {
16310×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1632
        };
16335×
        let remote = self.open_named_remote(&remote_name)?;
16345×
        let objects = remote.objects(&[*blob])?;
163511×
        for (ty, body) in objects {
163611×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
163711×
                self.store.put(ty, &body)?;
16380×
            }
1639
        }
16405×
        if !self.store.has(blob) {
16410×
            return fail(format!(
1642
                "{remote_name} did not send blob {}",
16430×
                blob.short(12)
1644
            ));
16455×
        }
16465×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
16475×
        Ok(())
16485×
    }
1649
1650
    /// After importing from `remote`, record every blob the changes reference
1651
    /// that the store lacks as lazily available from that remote.
16525×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
16535×
        let mut n = 0;
16545×
        for h in changes {
16554×
            let c = self.store.get_change(h)?;
165613×
            for e in &c.edits {
165713×
                if let Edit::Replace { old, new, .. } = e {
16586×
                    for b in [old, new].into_iter().flatten() {
16596×
                        if !self.store.has(b) {
16604×
                            self.register_lazy(b, remote)?;
16614×
                            n += 1;
16622×
                        }
1663
                    }
16647×
                }
1665
            }
1666
        }
16675×
        Ok(n)
16685×
    }
1669
1670
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1671398×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1672398×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1673539×
        for st in view
1674398×
            .bookmarks
1675398×
            .values()
1676398×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1677
        {
1678539×
            if let Ok(s) = self.store.get_state(st) {
1679539×
                have.extend(s.heads);
1680539×
            }
1681
        }
1682398×
        have.extend(view.workspaces.values().copied());
1683398×
        Ok(have.into_iter().collect())
1684398×
    }
1685
1686
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1687404×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1688404×
        let remote = self.open_named_remote(remote_name)?;
1689401×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1690399×
        let resp = remote.refs()?;
1691
        // The host's transparency log (spec §14.8): a fork fails here.
1692398×
        let log = self.check_log(
1693398×
            &self.remote_url(remote_name)?,
1694398×
            self.config.remote_cas.get(remote_name).map(Path::new),
1695398×
            &resp,
16960×
        )?;
1697398×
        let mut log_notes = log.notes.clone();
1698
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1699
        // and signed by roots we trust, or on first contact. A remote that
1700
        // once presented a policy may never present none or an older one:
1701
        // that is a downgrade. A remote that never presented one is
1702
        // unverified, and this fetch is checked only as far as possible.
1703398×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1704398×
        let seen = self.remote_policy_serial(remote_name);
1705398×
        let mut unverified = false;
1706398×
        match &resp.policy {
170738×
            Some(sp) => {
170838×
                if seen.is_some_and(|s| sp.policy.serial < s) {
17090×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
171038×
                }
171114×
                match &local_policy {
171214×
                    Some(l) if sp.policy.serial < l.serial => {}
171314×
                    Some(l) if sp.policy.serial == l.serial => {
171410×
                        if sp.policy.hash() != l.hash() {
17150×
                            return fail(format!(
1716
                                "{remote_name} presents a different policy with the same serial {}",
1717
                                l.serial
1718
                            ));
171910×
                        }
1720
                    }
1721
                    _ => {
172228×
                        self.adopt_policy_chain(
172328×
                            &resp.history,
172428×
                            sp,
172528×
                            &format!("oxy fetch {remote_name}"),
1726
                        )
172728×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1728
                    }
1729
                }
173038×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1731
            }
1732
            None => {
1733360×
                if seen.is_some() {
17340×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1735360×
                }
1736360×
                unverified = true;
1737
            }
1738
        }
1739398×
        let policy = if unverified {
1740360×
            None
1741
        } else {
174238×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1743
        };
1744398×
        let (op_ref, op) = self.head_op()?;
1745398×
        let mut view = op.view.clone();
1746398×
        let have = self.known_heads(&view)?;
1747398×
        let mut report = Vec::new();
1748398×
        let mut skipped = Vec::new();
1749398×
        let max_blob = self.config.max_blob;
1750424×
        for r in resp.refs {
1751424×
            let needed = {
1752424×
                let _t = crate::timing::phase("fetch: negotiate");
1753424×
                remote.negotiate(&have, &r.heads)?
1754
            };
1755424×
            let bundle = {
1756424×
                let _t = crate::timing::phase("fetch: bundle");
1757424×
                remote.fetch(&needed, max_blob)?
1758
            };
1759
            // Changes are not individually re-verified here: the bookmark's
1760
            // attestation (checked below) binds its whole state, and the
1761
            // receiver of the push verified the added changes at that time.
1762
            // A shallow repository takes changes whose dependencies it never
1763
            // held (below what it cloned), as its clone did (#137).
1764424×
            let shallow = self.is_shallow();
1765424×
            let imported = {
1766424×
                let _t = crate::timing::phase("fetch: import");
1767424×
                if shallow {
17682×
                    self.import_bundle_shallow(&bundle, false)?
1769
                } else {
1770422×
                    self.import_bundle(&bundle, false)?
1771
                }
1772
            };
1773424×
            if shallow {
17742×
                self.refresh_boundary(&imported)?;
1775422×
            }
1776424×
            if max_blob.is_some() {
17774×
                self.register_missing_blobs(&imported, remote_name)?;
1778420×
            }
1779424×
            let boundary = if shallow {
17802×
                self.boundary()
1781
            } else {
1782422×
                BTreeSet::new()
1783
            };
1784581×
            for h in &r.heads {
1785581×
                if !self.store.has(h) && !boundary.contains(h) {
17860×
                    return fail(format!("remote did not send head {}", h.short(12)));
1787581×
                }
1788
            }
1789424×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1790424×
            if state != r.state {
17910×
                return fail(format!(
1792
                    "remote state {} does not match its heads",
17930×
                    r.state.short(12)
1794
                ));
1795424×
            }
1796424×
            if let Some(p) = &policy {
179741×
                let Some(sa) = &r.attestation else {
17980×
                    return fail(format!(
1799
                        "{remote_name}/{} has no attestation, which its policy requires",
1800
                        r.name
1801
                    ));
1802
                };
180341×
                let signer = sa
180441×
                    .sigs
180541×
                    .first()
180641×
                    .map(|s| s.key)
180741×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
180841×
                if !p.authorizes(&signer, &r.name) {
180920×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
181021×
                }
1811383×
            }
1812424×
            if let Some(sa) = &r.attestation {
1813
                let AttestBody::Ref {
181473×
                    old_state,
181573×
                    new_state,
1816
                    ..
181773×
                } = &sa.attest.body
1818
                else {
18190×
                    return fail("remote sent a non-ref attestation for a bookmark");
1820
                };
182173×
                let (old_state, new_state) = (*old_state, *new_state);
182273×
                let serial = self
182373×
                    .check_ref_attest_body(
182473×
                        sa,
182573×
                        &r.name,
182673×
                        &old_state,
182773×
                        &new_state,
182873×
                        self.last_seen_serial(remote_name, &r.name),
1829
                        true,
1830
                    )
183173×
                    .map_err(|e| {
18320×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
18330×
                    })?;
183473×
                if new_state != r.state {
18350×
                    return fail(format!(
1836
                        "attestation for {}/{} does not cover its current state",
1837
                        remote_name, r.name
1838
                    ));
183973×
                }
1840
                // A signature this client cannot verify (its signer unknown
1841
                // here, as from a host that did not send the identity, or
1842
                // bad) fails that bookmark alone: it stays as it was and
1843
                // the rest are fetched (oxygenhub#266). The current
1844
                // bookmark, which a pull would take, still fails the fetch.
1845
                // A policy's requirements were checked above and still fail.
184673×
                if let Err(e) = self.verify_attest_signature(sa) {
184712×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
184812×
                    if r.name == self.config.bookmark {
18493×
                        return fail(why);
18509×
                    }
18519×
                    skipped.push((r.name, why));
18529×
                    continue;
185361×
                }
185461×
                let ar = self.store.put_attest(&sa.attest)?;
185561×
                for sig in &sa.sigs {
185661×
                    self.store.put_signature(&ar, sig)?;
1857
                }
185861×
                self.record_serial(remote_name, &r.name, serial)?;
1859351×
            }
1860412×
            view.remotes
1861412×
                .entry(remote_name.to_string())
1862412×
                .or_default()
1863412×
                .insert(r.name.clone(), state);
1864412×
            report.push((r.name, r.heads, imported.len()));
1865
        }
1866395×
        let mut new_tags = 0;
1867395×
        for t in &resp.tags {
186831×
            if view.tags.contains_key(&t.name) {
18697×
                continue;
187024×
            }
1871
            // Withdrawn here: the name is not used again.
187224×
            if self.tag_withdrawal(&t.name)?.is_some() {
18730×
                continue;
187424×
            }
1875
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
187624×
            let missing: Vec<ChangeHash> = t
187724×
                .heads
187824×
                .iter()
187924×
                .filter(|h| !self.store.has(h))
188024×
                .copied()
188124×
                .collect();
188224×
            if !missing.is_empty() {
18830×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
18840×
                let bundle = remote.fetch(&needed, max_blob)?;
18850×
                self.import_bundle(&bundle, false)?;
188624×
            }
188724×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
188824×
            let mut check = TagCheck::Fetched {
188924×
                remote: remote_name,
189024×
                log: &log,
189124×
                notes: &mut log_notes,
189224×
            };
189324×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
189422×
                Ok(()) => new_tags += 1,
1895
                // Nothing says when a short-lived key signed it: the tag is
1896
                // left out, said so, and the rest is fetched (oxygen#129).
18972×
                Err(e) if e.untimed => {
18982×
                    skipped.push((format!("tags/{}", t.name), e.reason));
18992×
                }
19000×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1901
            }
1902
        }
1903
        // The remote withdrew a tag this repository has: so does this one,
1904
        // once the withdrawal is checked as a push's would be; one that is
1905
        // not is left as it is, said so (oxygenhub#301).
1906395×
        let mut withdrawn_tags = Vec::new();
1907395×
        for t in &resp.withdrawn {
19081×
            if !view.tags.contains_key(&t.name) {
19090×
                continue;
19101×
            }
19111×
            let mut check = TagCheck::Fetched {
19121×
                remote: remote_name,
19131×
                log: &log,
19141×
                notes: &mut log_notes,
19151×
            };
19161×
            match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut check) {
19171×
                Ok(true) => withdrawn_tags.push(t.name.clone()),
19180×
                Ok(false) => {}
19190×
                Err(e) => skipped.push((
19200×
                    format!("tags/{}", t.name),
19210×
                    format!("withdrawn on {remote_name}, kept here: {}", e.reason),
19220×
                )),
1923
            }
1924
        }
1925395×
        if view != op.view {
1926379×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
192716×
        }
1928395×
        let _ = self.run_hook(
1929395×
            "post-fetch",
1930395×
            &format!(
1931
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1932395×
                json_str(remote_name),
1933409×
                json_array(report.iter().map(|(n, heads, _)| format!(
1934
                    "{{\"name\":{},\"heads\":{}}}",
1935409×
                    json_str(n),
1936566×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1937
                )))
1938
            ),
1939
        );
1940395×
        Ok(FetchReport {
1941395×
            refs: report,
1942395×
            unverified,
1943395×
            new_tags,
1944395×
            withdrawn_tags,
1945395×
            log_notes,
1946395×
            skipped,
1947395×
        })
1948404×
    }
1949
1950
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1951
    /// the changes within `depth` steps of its heads, and the boundary below.
19523×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
19533×
        let remote = self.open_named_remote(remote_name)?;
19543×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
19553×
        let resp = remote.refs()?;
19563×
        let bookmark = self.config.bookmark.clone();
19573×
        if let Some(sp) = &resp.policy {
19580×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
19590×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
19600×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
19613×
        }
19623×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
19630×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1964
        };
19653×
        if r.heads.is_empty() {
19660×
            return Ok(0);
19673×
        }
1968
        // Base: the remote's checkpoint of exactly these heads.
19693×
        let cp_bundle = {
19703×
            let _t = crate::timing::phase("shallow: checkpoint request");
19713×
            remote.checkpoint(&r.heads)?
1972
        };
1973
        // In one batch: a big state's checkpoint is tens of thousands of
1974
        // graph blobs and chunks, which stored one by one were each written
1975
        // loose and flushed (a VS Code clone ran at 27 objects a second).
19763×
        let objects: Vec<(ObjectType, &[u8])> = cp_bundle
19773×
            .objects
19783×
            .iter()
19799×
            .map(|(ty, body)| (*ty, body.as_slice()))
19803×
            .collect();
19813×
        let t_store = crate::timing::phase("shallow: store the checkpoint");
19823×
        let batch = self.store.begin_batch()?;
19833×
        let stored = self.store.put_many(&objects);
19843×
        batch.finish()?;
19853×
        drop(t_store);
19863×
        let cp_ref = objects
19873×
            .iter()
19883×
            .zip(stored?)
19899×
            .find(|((ty, _), _)| *ty == ObjectType::Checkpoint)
19903×
            .map(|(_, r)| r);
19913×
        let Some(cp_ref) = cp_ref else {
19920×
            return fail(format!("{remote_name} sent no checkpoint"));
1993
        };
19943×
        self.install_checkpoint(&bookmark, &cp_ref)?;
19953×
        let _t_blobs = crate::timing::phase("shallow: the binary files' blobs");
1996
        // The blobs of the state's opaque files come with no change when the
1997
        // window holds none of the changes that set them (#137): fetch them
1998
        // now, or under `filter.max-blob` leave them to be fetched on read.
19993×
        let cp = crate::objects::Checkpoint::decode(
20003×
            &self.store.get_typed(&cp_ref, ObjectType::Checkpoint)?,
20010×
        )?;
20023×
        let base = State::from_checkpoint_history(&self.read_blob(&cp.payload)?)?;
20033×
        let mut missing: Vec<ObjectRef> = base
20043×
            .opaque_nodes()
20053×
            .iter()
20063×
            .flat_map(|n| base.live_blobs(n))
20073×
            .filter(|b| !self.store.has(b))
20083×
            .collect();
20093×
        missing.sort();
20103×
        missing.dedup();
20113×
        if self.config.max_blob.is_some() {
20121×
            for b in &missing {
20131×
                self.register_lazy(b, remote_name)?;
2014
            }
2015
        } else {
20162×
            for part in missing.chunks(512) {
20171×
                let objects = remote.objects(part)?;
20181×
                let objects: Vec<(ObjectType, &[u8])> = objects
20191×
                    .iter()
20202×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
20212×
                    .map(|(ty, body)| (*ty, body.as_slice()))
20221×
                    .collect();
20231×
                let batch = self.store.begin_batch()?;
20241×
                let stored = self.store.put_many(&objects);
20251×
                batch.finish()?;
20261×
                stored?;
2027
            }
20282×
            if let Some(b) = missing.iter().find(|b| !self.store.has(b)) {
20290×
                return fail(format!("{remote_name} did not send blob {}", b.short(12)));
20302×
            }
2031
        }
2032
        // History window. Depth 0 takes none (#137): the checkpoint holds
2033
        // every change's metadata, and its heads become the boundary, so a
2034
        // state of many heads (33,835 in the VS Code import) costs nothing
2035
        // to fetch.
20363×
        let imported = if depth == 0 {
20372×
            let mut boundary = self.boundary();
20382×
            boundary.extend(r.heads.iter().filter(|h| !self.store.has(h)).copied());
20392×
            self.write_boundary(&boundary)?;
20402×
            Vec::new()
2041
        } else {
20421×
            let wanted = remote.shallow(&r.heads, depth)?;
20431×
            let bundle = remote.fetch(&wanted, self.config.max_blob)?;
20441×
            self.import_bundle_shallow(&bundle, false)?
2045
        };
20463×
        if self.config.max_blob.is_some() {
20471×
            self.register_missing_blobs(&imported, remote_name)?;
20482×
        }
20493×
        self.refresh_boundary(&imported)?;
20503×
        if let Some(sa) = &r.attestation {
20510×
            let ar = self.store.put_attest(&sa.attest)?;
20520×
            for sig in &sa.sigs {
20530×
                self.store.put_signature(&ar, sig)?;
2054
            }
20550×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
20560×
                self.record_serial(remote_name, &r.name, serial)?;
20570×
            }
20583×
        }
20593×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
20603×
        let (op_ref, op) = self.head_op()?;
20613×
        let mut view = op.view.clone();
20623×
        view.remotes
20633×
            .entry(remote_name.to_string())
20643×
            .or_default()
20653×
            .insert(r.name.clone(), state);
20663×
        self.record_op(
20673×
            &[op_ref],
20683×
            &format!("oxy fetch {remote_name} --depth {depth}"),
20693×
            view,
20700×
        )?;
20713×
        Ok(imported.len())
20723×
    }
2073
2074
    /// Fetch, then take the union of the local bookmark's state with the
2075
    /// remote's: no merge change, conflicts become reified (spec §9.4).
2076111×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
2077111×
        let _wc = self.lock_working_copy()?;
2078111×
        let skipped = self.fetch(remote_name)?.skipped;
2079107×
        let (op_ref, op) = self.head_op()?;
2080107×
        let current = self.config.bookmark.clone();
2081107×
        let mut local_current = self.heads_of(&op.view, &current)?;
2082107×
        local_current.sort();
2083107×
        let mut view = op.view.clone();
2084107×
        let mut current_heads = local_current.clone();
2085107×
        let mut changed = false;
2086107×
        let mut others = Vec::new();
2087107×
        let tracked = op
2088107×
            .view
2089107×
            .remotes
2090107×
            .get(remote_name)
2091107×
            .cloned()
2092107×
            .unwrap_or_default();
2093112×
        for (name, remote_state) in tracked {
2094
            // Every local bookmark tracks the remote's of the same name;
2095
            // the current one may be new here.
2096112×
            let local_state = op.view.bookmarks.get(&name).copied();
2097112×
            if local_state.is_none() && name != current {
20981×
                continue;
2099111×
            }
2100111×
            if local_state == Some(remote_state) {
210110×
                continue;
2102101×
            }
2103101×
            let local = self.heads_of(&op.view, &name)?;
2104101×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2105135×
            if remote_heads.iter().all(|h| local.contains(h)) {
21060×
                continue;
2107101×
            }
2108101×
            let mut all = local.clone();
2109101×
            all.extend(remote_heads);
2110101×
            let st = self.load_state_history(&all)?;
2111101×
            let mut heads = st.maximal(&all);
2112101×
            heads.sort();
2113101×
            let mut sorted_local = local;
2114101×
            sorted_local.sort();
2115101×
            if heads == sorted_local {
21161×
                continue;
2117100×
            }
2118100×
            view.bookmarks.insert(
2119100×
                name.clone(),
2120100×
                self.store.put_state(&StateObject::new(heads.clone()))?,
2121
            );
2122100×
            if name == current {
212398×
                changed = true;
212498×
                current_heads = heads;
212598×
            } else {
21262×
                others.push(name);
21272×
            }
2128
        }
2129107×
        if changed || !others.is_empty() {
213099×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
21318×
        }
2132
        // The working copy follows its bookmark whenever nothing would be
2133
        // lost, also when this pull brought nothing new but it had been
2134
        // left behind (oxygen#89).
2135107×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2136
        Ok(PullReport {
2137107×
            heads: if changed {
213898×
                current_heads
2139
            } else {
21409×
                local_current
2141
            },
2142107×
            changed,
2143107×
            checked_out,
2144107×
            others,
2145107×
            skipped,
2146
        })
2147111×
    }
2148
2149
    /// How many changes the working copy's bookmark has that its base
2150
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2151
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2152
    /// the bookmark or holds changes the bookmark lacks. History is read
2153
    /// only when the base and the bookmark's heads differ (oxygen#89).
21547×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
21557×
        let (_, wc) = self.working_copy()?;
21567×
        let mut base = wc.deps.clone();
21577×
        base.sort();
21587×
        let mut heads = self.bookmark_heads()?;
21597×
        heads.sort();
21607×
        if base == heads || heads.is_empty() {
21616×
            return Ok(None);
21621×
        }
21631×
        let state = self.load_state_history(&heads)?;
21641×
        if !base.iter().all(|h| state.contains(h)) {
21650×
            return Ok(None);
21661×
        }
21671×
        let had = if base.is_empty() {
21680×
            0
2169
        } else {
21701×
            self.load_state_history(&base)?.len()
2171
        };
21721×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
21737×
    }
2174
2175
    /// Bring the working copy to `heads`, the state of its bookmark
2176
    /// `bookmark`, when nothing would be lost: its base is part of that
2177
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2178
    /// with uncommitted work, the work comes along when the new changes
2179
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2180
    /// it followed only from exactly the bookmark's old heads, so a working
2181
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2182
    /// or a pull from another workspace) never caught up, and nothing said
2183
    /// so (oxygen#74, #89). Returns whether it moved.
2184107×
    pub fn follow_bookmark(
2185107×
        &self,
2186107×
        heads: &[ChangeHash],
2187107×
        bookmark: &str,
2188107×
        command: &str,
2189107×
    ) -> Result<bool> {
2190107×
        let snap = self.snapshot(command)?;
2191107×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2192107×
        let mut base = snap.base.maximal(&snap.wc.deps);
2193107×
        base.sort();
2194107×
        let mut target = heads.to_vec();
2195107×
        target.sort();
2196107×
        if base == target {
21978×
            return Ok(false);
219899×
        }
219999×
        let state = self.load_state_history(heads)?;
2200183×
        if !base.iter().all(|h| state.contains(h)) {
2201
            // The working copy holds changes the bookmark lacks: not ours to move.
22020×
            return Ok(false);
220399×
        }
220499×
        if clean {
220599×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
220699×
            Ok(true)
2207
        } else {
22080×
            Ok(self
22090×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
22100×
                .is_ok())
2211
        }
2212107×
    }
2213
2214
    /// Withdraw tag `tag` on `remote_name` (`oxy push --delete tags/NAME`,
2215
    /// oxygenhub#301): withdrawn here first when it still is a tag here
2216
    /// (`oxy tag delete`), then the withdrawal alone is sent, with its
2217
    /// signer's identity and certificate.
22183×
    pub fn push_tag_withdrawal(&self, remote_name: &str, tag: &str) -> Result<Vec<RefResult>> {
22193×
        let remote = self.open_named_remote(remote_name)?;
22203×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
22213×
        let resp = remote.refs()?;
22223×
        let name = format!("tags/{tag}");
22233×
        if resp.withdrawn.iter().any(|t| t.name == tag) {
22241×
            return Ok(vec![RefResult {
22251×
                name,
22261×
                ok: true,
22271×
                reason: "already withdrawn".into(),
22281×
            }]);
22292×
        }
22302×
        let Some(there) = resp.tags.iter().find(|t| t.name == tag) else {
22310×
            return fail(format!("{remote_name} has no tag {tag}"));
2232
        };
22332×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
22340×
            return fail(format!("{remote_name} enforces a trust policy; withdrawing a tag needs an identity (`oxy identity create`)"));
22352×
        }
22362×
        if self.tag_withdrawal(tag)?.is_none() {
22372×
            match self.view()?.tags.get(tag) {
22382×
                Some(st) if *st == there.state => {
22392×
                    self.tag_delete(tag, "")?;
2240
                }
2241
                Some(_) => {
22420×
                    return fail(format!(
2243
                        "tag {tag} names another state here than on {remote_name}"
2244
                    ))
2245
                }
2246
                None => {
22470×
                    return fail(format!(
2248
                        "there is no tag {tag} here to withdraw: `oxy fetch {remote_name}` first"
2249
                    ))
2250
                }
2251
            }
22520×
        }
22532×
        let Some(w) = self
22542×
            .withdrawn_refs()?
22552×
            .into_iter()
22562×
            .find(|w| w.name == tag && w.state == there.state)
2257
        else {
22580×
            return fail(format!(
2259
                "tag {tag} was withdrawn here at another state than {remote_name}'s"
2260
            ));
2261
        };
22622×
        let mut bundle = Bundle::default();
22632×
        let signers: Vec<KeyId> = w
22642×
            .attestation
22652×
            .iter()
22662×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
22672×
            .collect();
22682×
        for k in &signers {
22692×
            if let Ok(id) = self.identity(k) {
22702×
                bundle.objects.push((ObjectType::Identity, id.encode()));
22712×
            }
2272
        }
22732×
        self.attach_certificates_for(&mut bundle, &signers)?;
22742×
        remote.push(bundle, vec![], None, vec![w])
22753×
    }
2276
2277
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2278
    /// changes and attesting the reference when a key is available.
2279
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2280
    /// state, attested when we have an identity. The local bookmark, if
2281
    /// any, is kept; only the remote-tracking entry goes.
22828×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
22838×
        if let Some(tag) = bookmark.strip_prefix("tags/") {
22843×
            return self.push_tag_withdrawal(remote_name, tag);
22855×
        }
22865×
        let remote = self.open_named_remote(remote_name)?;
22875×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
22885×
        let resp = remote.refs()?;
22897×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
22901×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2291
        };
22924×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
22930×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
22944×
        }
22954×
        let attestation = match self.secret_key()? {
22962×
            Some(_) => Some(self.sign_attest(&Attest {
22972×
                repo: self.id()?,
22982×
                hlc: Hlc::now(),
22992×
                body: AttestBody::Ref {
23002×
                    name: bookmark.to_string(),
23012×
                    old_state: r.state,
23022×
                    new_state: ObjectRef::ZERO,
23032×
                    serial: r.last_serial.unwrap_or(0) + 1,
23042×
                },
23050×
            })?),
23062×
            None => None,
2307
        };
23084×
        let results = remote.push(
23094×
            Bundle::default(),
23104×
            vec![RefUpdate {
23114×
                name: bookmark.to_string(),
23124×
                old_state: r.state,
23134×
                new_state: ObjectRef::ZERO,
23144×
                force: true,
23154×
                attestation,
23164×
            }],
23174×
            None,
23184×
            vec![],
23190×
        )?;
23204×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
23212×
            let (op_ref, op) = self.head_op()?;
23222×
            let mut view = op.view.clone();
23232×
            if let Some(m) = view.remotes.get_mut(remote_name) {
23242×
                m.remove(bookmark);
23252×
            }
23262×
            self.record_op(
23272×
                &[op_ref],
23282×
                &format!("oxy push {remote_name} --delete {bookmark}"),
23292×
                view,
23300×
            )?;
23312×
        }
23324×
        Ok(results)
23338×
    }
2334
2335
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2336
    /// repository's config (its URL, token, CA and store settings), its
2337
    /// tracking bookmarks in the view, and a store remote's mirror under
2338
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
23393×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
23403×
        if !self.config.remotes.contains_key(name) {
23411×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
23422×
        }
23432×
        let prefix = format!("remote.{name}.");
23442×
        let keys: Vec<String> = self
23452×
            .config
23462×
            .repo_layer()
23472×
            .keys()
23484×
            .filter(|k| k.starts_with(&prefix))
23492×
            .cloned()
23502×
            .collect();
23513×
        for k in keys {
23523×
            self.config.set(&k, "")?;
2353
        }
23542×
        self.config.remotes.remove(name);
23552×
        self.save_config()?;
23562×
        let (op_ref, op) = self.head_op()?;
23572×
        if op.view.remotes.contains_key(name) {
23581×
            let mut view = op.view.clone();
23591×
            view.remotes.remove(name);
23601×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
23611×
        }
23622×
        let mirror = self.oxy.join("remotes").join(name);
23632×
        if mirror.is_dir() {
23640×
            fs::remove_dir_all(&mirror)?;
23652×
        }
23662×
        Ok(())
23673×
    }
2368
2369
    /// Send `bundle`'s blobs and chunks ahead of it, in parts of about
2370
    /// `push.batch-bytes` of objects alone, when the whole would be larger
2371
    /// (oxygen#133): one change can bring more blobs than one request may
2372
    /// carry, and a proxy in front of a hub refuses a request past its limit
2373
    /// (Cloudflare's is 100 MB). What is left, the changes with their
2374
    /// identities and states, is returned to send as before. A receiver
2375
    /// stores objects as they come, and checks a change's blobs are stored.
2376323×
    fn send_objects_ahead(
2377323×
        &self,
2378323×
        remote: &dyn crate::protocol::Remote,
2379323×
        remote_name: &str,
2380323×
        mut bundle: Bundle,
2381323×
        progress: crate::store::Progress,
2382323×
    ) -> Result<Bundle> {
2383323×
        let limit = self.config.push_batch_bytes;
2384323×
        let changes: u64 = bundle
2385323×
            .changes
2386323×
            .iter()
2387422×
            .map(|(c, _)| c.encode().len() as u64)
2388323×
            .sum();
2389323×
        let objects: u64 = bundle.objects.iter().map(|(_, b)| b.len() as u64).sum();
2390323×
        if changes + objects <= limit {
2391316×
            return Ok(bundle);
23927×
        }
23937×
        let (mut kept, mut parts, mut part, mut bytes) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
23949×
        for (ty, body) in std::mem::take(&mut bundle.objects) {
23959×
            if !matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
23960×
                kept.push((ty, body));
23970×
                continue;
23989×
            }
23999×
            if !part.is_empty() && bytes + body.len() as u64 > limit {
24003×
                parts.push(std::mem::take(&mut part));
24013×
                bytes = 0;
24026×
            }
24039×
            bytes += body.len() as u64;
24049×
            part.push((ty, body));
2405
        }
24067×
        if !part.is_empty() {
24071×
            parts.push(part);
24086×
        }
24097×
        let n = parts.len();
24107×
        for (i, objects) in parts.into_iter().enumerate() {
24114×
            progress(&format!(
24124×
                "objects {} of {n}: {} blobs and chunks",
24134×
                i + 1,
24144×
                objects.len()
24154×
            ));
24164×
            let results = remote.push(
24174×
                Bundle {
24184×
                    objects,
24194×
                    ..Default::default()
24204×
                },
24214×
                vec![],
24224×
                None,
24234×
                vec![],
24240×
            )?;
24254×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
24264×
                Some(r) if r.ok => {}
24270×
                Some(r) => {
24280×
                    return fail(format!(
2429
                        "{remote_name} refused objects part {} of {n}: {}",
24300×
                        i + 1,
2431
                        r.reason
2432
                    ))
2433
                }
2434
                None => {
24350×
                    return fail(format!(
2436
                        "{remote_name} does not take a push in parts, and this one is too large for one: update the server's oxy"
2437
                    ))
2438
                }
2439
            }
2440
        }
24417×
        bundle.objects = kept;
24427×
        Ok(bundle)
2443323×
    }
2444
2445
    /// `changes`, in dependency order, cut into batches of about
2446
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2447
    /// There is always one, perhaps empty.
2448318×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2449318×
        let blob_len = |r: &ObjectRef| -> u64 {
245033×
            self.store
245133×
                .get_typed(r, ObjectType::Blob)
245233×
                .ok()
245333×
                .and_then(|b| Blob::decode(&b).ok())
245433×
                .map_or(0, |b| b.length)
245533×
        };
2456318×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2457422×
        for h in changes {
2458422×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2459422×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2460422×
            let mut weight = raw.len() as u64;
2461536×
            for t in &texts {
2462536×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
246326×
                    weight += blob_len(r);
2464510×
                }
2465
            }
2466681×
            for e in &c.edits {
24677×
                if let Edit::Replace { new: Some(b), .. } = e {
24687×
                    weight += blob_len(b);
2469674×
                }
2470
            }
2471422×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
24725×
                out.push(std::mem::take(&mut batch));
24735×
                bytes = 0;
2474417×
            }
2475422×
            batch.push(*h);
2476422×
            bytes += weight;
2477
        }
2478318×
        out.push(batch);
2479318×
        Ok(out)
2480318×
    }
2481
2482380×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2483380×
        let bookmark = self.config.bookmark.clone();
2484380×
        self.push_bookmark(remote_name, &bookmark, force)
2485380×
    }
2486
2487
    /// `push` for a named bookmark (`oxy push -b NAME`).
2488393×
    pub fn push_bookmark(
2489393×
        &self,
2490393×
        remote_name: &str,
2491393×
        bookmark: &str,
2492393×
        force: bool,
2493393×
    ) -> Result<Vec<RefResult>> {
2494393×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2495393×
    }
2496
2497
    /// `push_bookmark`, saying how a long push is going: one line per
2498
    /// batch sent (oxygen#95).
2499402×
    pub fn push_bookmark_with(
2500402×
        &self,
2501402×
        remote_name: &str,
2502402×
        bookmark: &str,
2503402×
        force: bool,
2504402×
        progress: crate::store::Progress,
2505402×
    ) -> Result<Vec<RefResult>> {
2506402×
        let (op_ref, op) = self.head_op()?;
2507402×
        if !op.view.bookmarks.contains_key(bookmark) {
25080×
            return fail(format!("no bookmark {bookmark}"));
2509402×
        }
2510402×
        let bookmark = bookmark.to_string();
2511402×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2512
        // pre-push hook: may veto before the remote is contacted.
2513402×
        self.run_hook(
2514402×
            "pre-push",
2515402×
            &format!(
2516
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2517402×
                json_str(remote_name),
2518402×
                json_str(&bookmark),
2519799×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2520
            ),
25211×
        )?;
2522401×
        let remote = self.open_named_remote(remote_name)?;
2523401×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2524398×
        let resp = remote.refs()?;
2525398×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2526398×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2527398×
        let policy_to_send = match (&local_policy, &resp.policy) {
252844×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
252916×
            (Some(l), None) => Some(l.clone()),
253026×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
25311×
                return fail(format!(
2532
                    "{remote_name} has a newer policy (serial {}); fetch first",
2533
                    r.policy.serial
2534
                ));
2535
            }
2536363×
            _ => None,
2537
        };
2538397×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2539397×
        if remote_has_policy && self.secret_key()?.is_none() {
25401×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2541396×
        }
2542396×
        let remote_tags: BTreeSet<String> = resp
2543396×
            .tags
2544396×
            .iter()
2545396×
            .chain(&resp.withdrawn)
2546396×
            .map(|t| t.name.clone())
2547396×
            .collect();
2548396×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2549396×
            .tag_refs()?
2550396×
            .into_iter()
2551396×
            .filter(|t| !remote_tags.contains(&t.name))
2552396×
            .collect();
2553
        // Tags withdrawn here that the remote still has, at the same state
2554
        // (oxygenhub#301).
2555396×
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2556396×
            .withdrawn_refs()?
2557396×
            .into_iter()
2558396×
            .filter(|w| {
25592×
                resp.tags
25602×
                    .iter()
25612×
                    .any(|t| t.name == w.name && t.state == w.state)
25622×
            })
2563396×
            .collect();
2564396×
        let refs = resp.refs;
2565396×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2566396×
        let (remote_state, remote_heads, last_serial) =
2567397×
            match refs.iter().find(|r| r.name == bookmark) {
2568374×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
256922×
                None => (empty, vec![], None),
2570
            };
2571396×
        let new_state = self
2572396×
            .store
2573396×
            .put_state(&StateObject::new(local_heads.clone()))?;
2574
        // A push that carries a policy re-attests the bookmark even when its
2575
        // state is unchanged, so the current attestation is always by a key
2576
        // the current policy authorizes (a revoked key's attestation would
2577
        // otherwise be refused by every later fetch).
2578396×
        if new_state == remote_state
257934×
            && policy_to_send.is_none()
258017×
            && tags_to_send.is_empty()
25818×
            && withdrawals_to_send.is_empty()
2582
        {
25837×
            return Ok(vec![RefResult {
25847×
                name: bookmark,
25857×
                ok: true,
25867×
                reason: "already up to date".into(),
25877×
            }]);
2588389×
        }
2589
        // A shallow repository knows the changes on its boundary without
2590
        // holding them: a depth-0 clone's are the heads it cloned (#137).
2591389×
        let boundary = self.boundary();
2592435×
        for h in &remote_heads {
2593435×
            if !self.store.has(h) && !boundary.contains(h) {
259470×
                return fail(format!(
2595
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
259670×
                    h.short(12)
2597
                ));
2598365×
            }
2599
        }
2600319×
        if !force {
2601319×
            let closure = self.closure_in_store(&local_heads)?;
2602319×
            if let Some(h) = remote_heads
2603319×
                .iter()
2604340×
                .find(|h| !closure.contains(h) && !boundary.contains(h))
2605
            {
26060×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2607319×
            }
26080×
        }
2609319×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2610319×
        let key = self.secret_key()?.map(|(k, _)| k);
2611319×
        if let Some(key) = key {
2612
            // Seal this author's changes that carry no valid authenticator,
2613
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2614
            // are stored, so each batch's bundle carries those it needs.
2615112×
            let mut unsigned = Vec::new();
2616112×
            for h in &to_send {
261792×
                let c = self.store.get_change_meta(h)?;
261892×
                if self.seals_for_author(&c.author, &key)
261987×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
262053×
                {
262153×
                    unsigned.push(*h);
262253×
                }
2623
            }
2624112×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
262550×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2626
            }
2627207×
        }
2628
        // A long history goes in batches, in dependency order, so neither
2629
        // side holds it whole and no request passes the remote's limit:
2630
        // all but the last carry objects alone; the last moves the bookmark
2631
        // (oxygen#95).
2632318×
        let batches = self.push_batches(&to_send)?;
2633318×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2634318×
        for (i, batch) in earlier.iter().enumerate() {
26355×
            progress(&format!(
26365×
                "part {} of {}: {} changes",
26375×
                i + 1,
26385×
                batches.len(),
26395×
                batch.len()
26405×
            ));
26415×
            let bundle = self.send_objects_ahead(
26425×
                remote.as_ref(),
26435×
                remote_name,
26445×
                self.bundle_for(batch)?,
26455×
                &mut *progress,
26460×
            )?;
26475×
            let results = remote.push(bundle, vec![], None, vec![])?;
26485×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
26495×
                Some(r) if r.ok => {}
26500×
                Some(r) => {
26510×
                    return fail(format!(
2652
                        "{remote_name} refused part {} of the push: {}",
26530×
                        i + 1,
2654
                        r.reason
2655
                    ))
2656
                }
2657
                None => {
26580×
                    return fail(format!(
2659
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2660
                    ))
2661
                }
2662
            }
2663
        }
2664318×
        if batches.len() > 1 {
26651×
            progress(&format!(
26661×
                "part {} of {}: {} changes",
26671×
                batches.len(),
26681×
                batches.len(),
26691×
                last.len()
26701×
            ));
2671317×
        }
2672318×
        let mut bundle = self.send_objects_ahead(
2673318×
            remote.as_ref(),
2674318×
            remote_name,
2675318×
            self.bundle_for(last)?,
2676318×
            &mut *progress,
26770×
        )?;
2678318×
        bundle.objects.push((
2679318×
            ObjectType::State,
2680318×
            StateObject::new(local_heads.clone()).encode(),
2681318×
        ));
2682318×
        let attestation = match key {
2683111×
            Some(_) => Some(self.sign_attest(&Attest {
2684111×
                repo: self.id()?,
2685111×
                hlc: Hlc::now(),
2686111×
                body: AttestBody::Ref {
2687111×
                    name: bookmark.clone(),
2688111×
                    old_state: remote_state,
2689111×
                    new_state,
2690111×
                    serial: next_serial(last_serial),
2691111×
                },
26921×
            })?),
2693207×
            None => None,
2694
        };
2695
        // Whoever signed the move, and whom a delegate acts for, travel with
2696
        // it: a receiver that has never seen a change by this delegate could
2697
        // not otherwise check its signature (oxygenhub#129).
2698317×
        if attestation.is_some() {
2699220×
            for k in [self.signing_key(), self.config.author_key]
2700110×
                .into_iter()
2701110×
                .flatten()
2702
            {
2703220×
                if let Ok(id) = self.identity(&k) {
2704220×
                    let body = id.encode();
2705220×
                    if !bundle
2706220×
                        .objects
2707220×
                        .iter()
2708267×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
270932×
                    {
271032×
                        bundle.objects.push((ObjectType::Identity, body));
2711188×
                    }
27120×
                }
2713
            }
2714
            // A short-lived signing key's certificate goes with it (§14.7).
2715110×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2716110×
            self.attach_certificates_for(&mut bundle, &signers)?;
2717207×
        }
2718317×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2719110×
            AttestBody::Ref { serial, .. } => Some(serial),
27200×
            _ => None,
2721110×
        });
2722317×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2723
        // Tag states must be present on the remote: bundle their changes too.
2724317×
        for t in &tags_to_send {
272516×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
272616×
            let extra: Vec<ChangeHash> =
272716×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
272816×
            if !extra.is_empty() {
27290×
                let more = self.bundle_for(&extra)?;
27300×
                bundle.changes.extend(more.changes);
27310×
                bundle.hashes.extend(more.hashes);
27320×
                bundle.attests.extend(more.attests);
27330×
                bundle.objects.extend(more.objects);
273416×
            }
273516×
            bundle.objects.push((
273616×
                ObjectType::State,
273716×
                StateObject::new(t.heads.clone()).encode(),
273816×
            ));
2739
        }
2740
        // A tag's signer travels with it, as the bookmark's does: a tag made
2741
        // by `oxy tag create` under a short-lived key was signed by a key the
2742
        // receiver has never seen, so its identity and certificate go too.
2743317×
        let tag_signers: Vec<KeyId> = tags_to_send
2744317×
            .iter()
2745317×
            .chain(&withdrawals_to_send)
2746317×
            .filter_map(|t| t.attestation.as_ref())
2747317×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2748317×
            .collect();
2749317×
        for k in &tag_signers {
275016×
            if let Ok(id) = self.identity(k) {
275116×
                let body = id.encode();
275216×
                if !bundle
275316×
                    .objects
275416×
                    .iter()
275530×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
27562×
                {
27572×
                    bundle.objects.push((ObjectType::Identity, body));
275814×
                }
27590×
            }
2760
        }
2761317×
        if !tag_signers.is_empty() {
276215×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2763302×
        }
2764317×
        if let Some(l) = &policy_to_send {
276534×
            let remote_serial = resp_policy_serial;
276634×
            bundle.policies = self
276734×
                .policy_history()?
276834×
                .into_iter()
276966×
                .filter(|sp| {
277066×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
277136×
                        && sp.policy.serial < l.policy.serial
277266×
                })
277334×
                .collect();
2774283×
        }
2775317×
        let results = remote.push(
2776317×
            bundle,
2777317×
            vec![RefUpdate {
2778317×
                name: bookmark.clone(),
2779317×
                old_state: remote_state,
2780317×
                new_state,
2781317×
                force,
2782317×
                attestation,
2783317×
            }],
2784317×
            policy_to_send,
2785317×
            tags_to_send
2786317×
                .into_iter()
2787317×
                .chain(withdrawals_to_send)
2788317×
                .collect(),
27898×
        )?;
279034×
        if let (Some(serial), true) = (
2791309×
            sent_serial,
2792323×
            results.iter().any(|r| r.ok && r.name == "policy"),
2793
        ) {
279434×
            self.record_policy_serial(remote_name, serial)?;
2795275×
        }
2796346×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2797284×
            let mut view = op.view.clone();
2798284×
            view.remotes
2799284×
                .entry(remote_name.to_string())
2800284×
                .or_default()
2801284×
                .insert(bookmark.clone(), new_state);
2802284×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2803281×
            if let Some(s) = serial {
280486×
                self.record_serial(remote_name, &bookmark, s)?;
2805195×
            }
280625×
        }
2807304×
        Ok(results)
2808402×
    }
2809
2810
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2811
    /// bookmark set to the remote's, working copy checked out.
2812259×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2813259×
        Self::clone_with(url, dest, None, &[])
2814259×
    }
2815
2816
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2817
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2818
    /// unless a size is given, so out-of-scope binaries are never fetched).
2819262×
    pub fn clone_with(
2820262×
        url: &str,
2821262×
        dest: &Path,
2822262×
        max_blob: Option<u64>,
2823262×
        sparse: &[String],
2824262×
    ) -> Result<Repo> {
2825262×
        Self::clone_full(url, dest, max_blob, sparse, None)
2826262×
    }
2827
2828
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2829
    /// changes within `depth` steps of them; the rest is the boundary.
28303×
    pub fn clone_shallow(
28313×
        url: &str,
28323×
        dest: &Path,
28333×
        depth: u32,
28343×
        max_blob: Option<u64>,
28353×
        sparse: &[String],
28363×
    ) -> Result<Repo> {
28373×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
28383×
    }
2839
2840265×
    fn clone_full(
2841265×
        url: &str,
2842265×
        dest: &Path,
2843265×
        max_blob: Option<u64>,
2844265×
        sparse: &[String],
2845265×
        depth: Option<u32>,
2846265×
    ) -> Result<Repo> {
2847265×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2848265×
    }
2849
2850
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2851
    /// `depth`), also returning the bookmarks the fetch left out because
2852
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2853
    /// for the caller to warn about. The bookmark checked out is never one
2854
    /// of them: that fails the clone.
2855271×
    pub fn clone_reporting(
2856271×
        url: &str,
2857271×
        dest: &Path,
2858271×
        max_blob: Option<u64>,
2859271×
        sparse: &[String],
2860271×
        depth: Option<u32>,
2861271×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2862271×
        let options = crate::credentials::Credentials::user().options_for(url);
2863271×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2864271×
    }
2865
2866
    /// Clone a subrepo with the credentials the parent would use for its
2867
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2868
    /// subrepo: it finds the same ones again through its parent.
286910×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
287010×
        let options = self.credentials_for(url);
287110×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
287210×
    }
2873
2874
    /// The name of a remote of this repository on the same hub (scheme,
2875
    /// host and port) as `url`.
287623×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
287727×
        let origin = |u: &str| -> Option<String> {
287827×
            let (scheme, rest) = u.split_once("://")?;
28798×
            if !matches!(scheme, "http" | "https") {
28800×
                return None;
28818×
            }
28828×
            let host = rest.split('/').next()?;
28838×
            Some(format!(
28848×
                "{}://{}",
28858×
                scheme.to_ascii_lowercase(),
28868×
                host.to_ascii_lowercase()
28878×
            ))
288827×
        };
288923×
        let want = origin(url)?;
28904×
        self.config
28914×
            .remotes
28924×
            .iter()
28934×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
28944×
            .map(|(name, _)| name.clone())
289523×
    }
2896
2897
    /// The token and CA to reach `url` with: those of a remote of this
2898
    /// repository on the same hub (scheme, host and port), else the
2899
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2900
    /// and enclosing checkouts', as a clone would use them.
290123×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
290223×
        match self.remote_on_same_hub(url) {
29031×
            Some(name) => RemoteOptions {
29041×
                repo_id: None,
29051×
                cache_dir: None,
29061×
                ..self.remote_options(&name)
29071×
            },
2908
            None => {
290922×
                let mut options = RemoteOptions::default();
291022×
                self.fill_credentials(url, &mut options);
291122×
                options
2912
            }
2913
        }
291423×
    }
2915
2916281×
    fn clone_using(
2917281×
        url: &str,
2918281×
        dest: &Path,
2919281×
        max_blob: Option<u64>,
2920281×
        sparse: &[String],
2921281×
        depth: Option<u32>,
2922281×
        options: &RemoteOptions,
2923281×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2924281×
        let remote = open_remote(url, options)?;
2925281×
        let id = remote.repo_id()?;
2926277×
        if id == crate::protocol::UNBOUND_ID {
29272×
            return fail(format!(
2928
                "{url} is empty and unbound: push a repository to it first"
2929
            ));
2930275×
        }
2931275×
        let mut repo = Repo::init_with_id(dest, id)?;
2932275×
        repo.config
2933275×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2934275×
        if let Some(m) = max_blob {
29353×
            repo.config.set("filter.max-blob", &m.to_string())?;
2936272×
        } else if !sparse.is_empty() {
29371×
            repo.config.set("filter.max-blob", "0")?;
2938271×
        }
2939275×
        if !sparse.is_empty() {
29401×
            repo.config.set("filter.paths", &sparse.join(","))?;
2941274×
        }
2942275×
        repo.save_config()?;
2943275×
        let skipped = if let Some(depth) = depth {
29443×
            repo.fetch_shallow("origin", depth)?;
29453×
            Vec::new()
2946
        } else {
2947272×
            repo.fetch("origin")?.skipped
2948
        };
2949273×
        let (op_ref, op) = repo.head_op()?;
2950
        // The remote's default bookmark, else ours (main), else its only
2951
        // one; a bookmark the fetch skipped counts, so the clone fails
2952
        // rather than check out another (oxygenhub#266).
2953273×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2954273×
        for (name, _) in &skipped {
29553×
            theirs.insert(name.clone(), ObjectRef::ZERO);
29563×
        }
2957
        // Asked of the remote as now configured, so a store-backed one
2958
        // answers from the mirror the fetch just filled.
2959273×
        let advertised = repo
2960273×
            .open_named_remote("origin")
2961273×
            .ok()
2962273×
            .and_then(|r| r.refs().ok())
2963273×
            .and_then(|r| r.default_bookmark);
2964273×
        let bookmark = advertised
2965273×
            .filter(|b| theirs.contains_key(b))
2966273×
            .or_else(|| {
29677×
                theirs
29687×
                    .contains_key(&repo.config.bookmark)
29697×
                    .then(|| repo.config.bookmark.clone())
29707×
            })
2971273×
            .or_else(|| {
29720×
                (theirs.len() == 1)
29730×
                    .then(|| theirs.keys().next().cloned())
29740×
                    .flatten()
29750×
            })
2976273×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2977273×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
29780×
            return fail(format!("cannot check out {bookmark}: {why}"));
2979273×
        }
2980273×
        let initial = repo.config.bookmark.clone();
2981273×
        if bookmark != repo.config.bookmark {
29821×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
29831×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
29841×
            repo.config.bookmark = bookmark.clone();
2985272×
        }
2986273×
        if let Some(state) = theirs.get(&bookmark).copied() {
2987273×
            let heads = repo.store.get_state(&state)?.heads;
2988273×
            let mut view = op.view.clone();
2989
            // The empty bookmark `init` made goes when another is checked out.
2990273×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
29911×
                view.bookmarks.remove(&initial);
2992272×
            }
2993273×
            view.bookmarks.insert(bookmark, state);
2994273×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2995273×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
29960×
        }
2997273×
        Ok((repo, skipped))
2998281×
    }
2999
}
3000
3001
/// The serial of a reference's next attestation: one more than the last the
3002
/// remote reports, or, for a bookmark the remote does not have, the clock in
3003
/// milliseconds, so a bookmark created again after a deletion goes past the
3004
/// deletion's serial the remote keeps.
3005111×
fn next_serial(last: Option<u64>) -> u64 {
3006111×
    match last {
300769×
        Some(l) => l + 1,
300842×
        None => Hlc::now().wall_ms.max(1),
3009
    }
3010111×
}