OXYGENHUB

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

2181 of 2433 lines run, 340 of 460 functions · run #419 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
/// Graph blobs asked for in one `objects` request when a shallow clone
66
/// fetches its checkpoint in parts (#137): their chunk lists and chunks,
67
/// a few MiB a request rather than one answer of gigabytes.
68
const CHECKPOINT_PART: usize = 2048;
69
70
impl Repo {
71
    // ------------------------------------------------------------ serving (spec §16)
72
731850×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
741850×
        self.oxy.join("attest").join(name_file(bookmark))
751850×
    }
76
77
    /// The latest reference attestation stored for a bookmark.
781429×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
791429×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
80345×
            Ok(h) => {
81345×
                let r = ObjectRef::from_hex(h.trim())
82345×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
83
                Ok(Some((
84345×
                    r,
85
                    SignedAttest {
86345×
                        attest: self.store.get_attest(&r)?,
87345×
                        sigs: self.store.signatures(&r)?,
88
                    },
89
                )))
90
            }
911084×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
920×
            Err(e) => Err(e.into()),
93
        }
941429×
    }
95
96109×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
97109×
        fs::create_dir_all(self.oxy.join("attest"))?;
98109×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
99109×
    }
100
1011133×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
1021133×
        let view = self.view()?;
1031133×
        let mut out = Vec::new();
1041188×
        for (name, state) in &view.bookmarks {
1051188×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
1061188×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
107230×
                AttestBody::Ref { serial, .. } => Some(serial),
1080×
                _ => None,
109230×
            });
1101188×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1111188×
            let accepted = match &attestation {
112219×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
113969×
                None => None,
114
            };
1151188×
            out.push(RemoteRef {
1161188×
                name: name.clone(),
1171188×
                state: *state,
1181188×
                heads: self.store.get_state(state)?.heads,
1191188×
                attestation,
1201188×
                last_serial,
1211188×
                accepted,
1221188×
                logged: None,
1231188×
                integration: vec![],
124
            });
125
        }
1261133×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1271133×
        let history = self
1281133×
            .policy_history()?
1291133×
            .into_iter()
1301133×
            .filter(|sp| {
131221×
                policy
132221×
                    .as_ref()
133221×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
134221×
            })
1351133×
            .collect();
136
        Ok(RefsResponse {
1371133×
            refs: out,
1381133×
            policy,
1391133×
            tags: self.tag_refs()?,
1401133×
            history,
1411133×
            default_bookmark: Some(self.config.bookmark.clone()),
1421133×
            log: None,
1431133×
            witnesses: vec![],
1441133×
            withdrawn: self.withdrawn_refs()?,
145
        })
1461133×
    }
147
148
    /// Every change reachable from `heads` that is in the store.
1491542×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1501542×
        let mut seen = BTreeSet::new();
1511542×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1524910×
        while let Some(h) = stack.pop() {
1533368×
            if seen.contains(&h) || !self.store.has(&h) {
154969×
                continue;
1552399×
            }
1562399×
            seen.insert(h);
1572399×
            stack.extend(self.store.get_change_meta(&h)?.deps);
158
        }
1591542×
        Ok(seen)
1601542×
    }
161
162
    /// The changes within `depth` dependency steps of `heads` (spec §17),
163
    /// nearest first; depth 1 is the heads themselves.
1643×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1653×
        let mut out = Vec::new();
1663×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1673×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1683×
        for _ in 0..depth.max(1) {
1698×
            let mut next = Vec::new();
17012×
            for h in layer {
17112×
                if !seen.insert(h) || !self.store.has(&h) {
1722×
                    continue;
17310×
                }
17410×
                let c = self.store.get_change(&h)?;
17510×
                next.extend(c.deps.iter().copied());
17610×
                out.push(h);
177
            }
1788×
            if next.is_empty() {
1791×
                break;
1807×
            }
1817×
            layer = next;
182
        }
1833×
        out.reverse();
1843×
        Ok(out)
1853×
    }
186
1873905×
    fn shallow_path(&self) -> PathBuf {
1883905×
        self.oxy.join("shallow")
1893905×
    }
190
191
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1923896×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1933896×
        fs::read_to_string(self.shallow_path())
1943896×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1953896×
            .unwrap_or_default()
1963896×
    }
197
1981515×
    pub fn is_shallow(&self) -> bool {
1991515×
        !self.boundary().is_empty()
2001515×
    }
201
2029×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
2039×
        if boundary.is_empty() {
2041×
            let _ = fs::remove_file(self.shallow_path());
2051×
            return Ok(());
2068×
        }
2078×
        let text: String = boundary
2088×
            .iter()
2099×
            .map(|h| format!("{}\n", h.to_hex()))
2108×
            .collect();
2118×
        write_atomic(&self.shallow_path(), text.as_bytes())
2129×
    }
213
214
    /// Recompute the boundary from what is stored: every dependency of a
215
    /// stored change that is not itself stored.
2167×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2177×
        let mut boundary = self.boundary();
2187×
        boundary.retain(|h| !self.store.has(h));
21912×
        for h in imported {
22015×
            for d in self.store.get_change_meta(h)?.deps {
22115×
                if !self.store.has(&d) {
2223×
                    boundary.insert(d);
22312×
                }
224
            }
225
        }
2267×
        self.write_boundary(&boundary)
2277×
    }
228
229
    /// Fetch `depth` more levels of history below the shallow boundary.
2302×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2312×
        let boundary = self.boundary();
2322×
        if boundary.is_empty() {
2330×
            return Ok(0);
2342×
        }
2352×
        let remote = self.open_named_remote(remote_name)?;
2362×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2372×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2382×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2392×
        if self.config.max_blob.is_some() {
2400×
            self.register_missing_blobs(&imported, remote_name)?;
2412×
        }
2422×
        self.refresh_boundary(&imported)?;
2432×
        Ok(imported.len())
2442×
    }
245
246
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
247893×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
248893×
        let have = self.closure_in_store(have)?;
249
        // In a shallow repository the walk stops at the boundary, whose
250
        // changes the remote is assumed to hold.
251893×
        let boundary = self.boundary();
252893×
        let mut out = Vec::new();
253893×
        let mut done: BTreeSet<ChangeHash> = have.clone();
254893×
        done.extend(boundary.iter().copied());
255
        // Iterative post-order DFS.
256893×
        let shallow = self.is_shallow();
2571291×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2583431×
        while let Some((h, expanded)) = stack.pop() {
2592538×
            if done.contains(&h) {
260453×
                continue;
2612085×
            }
2622085×
            if !self.store.has(&h) {
263
                // A shallow repository holds only part of its history; a
264
                // change it lacks is below what it cloned (in a depth-0
265
                // clone, any change of the checkpoint), which the remote
266
                // is assumed to hold, as it is for the boundary (#137).
2671×
                if shallow {
2681×
                    done.insert(h);
2691×
                    continue;
2700×
                }
2710×
                return fail(format!("change {} is not in this repository", h.short(12)));
2722084×
            }
2732084×
            if expanded {
2741042×
                done.insert(h);
2751042×
                out.push(h);
2761042×
                continue;
2771042×
            }
2781042×
            stack.push((h, true));
2791042×
            for d in self.store.get_change_meta(&h)?.deps {
280670×
                if !done.contains(&d) {
281205×
                    stack.push((d, false));
282465×
                }
283
            }
284
        }
285893×
        Ok(out)
286893×
    }
287
288
    /// Bundle changes (in the given dependency order) with their signatures,
289
    /// seals, identities, blobs, chunks.
290341×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
291341×
        self.bundle_of(changes, None, false, false)
292341×
    }
293
294
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2956×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
296
        // In two reads in pack order (#137): a checkpoint's graph blobs come
297
        // this way in parts, tens of thousands for a big state.
2986×
        let mut found = Vec::with_capacity(refs.len());
2996×
        for got in self.store.get_many(refs) {
3000×
            match got {
3016×
                Ok(x) => found.push(x),
3020×
                Err(StoreError::NotFound(_)) => {}
3030×
                Err(e) => return Err(e.into()),
304
            }
305
        }
3066×
        let mut chunks = Vec::new();
3076×
        for (ty, body) in &found {
3086×
            if *ty == ObjectType::Blob {
3096×
                chunks.extend(Blob::decode(body)?.chunks);
3100×
            }
311
        }
3126×
        let mut out = Vec::with_capacity(found.len() + chunks.len());
3137×
        for got in self.store.get_many(&chunks) {
3140×
            match got {
3157×
                Ok(x) => out.push(x),
3160×
                Err(StoreError::NotFound(_)) => {}
3170×
                Err(e) => return Err(e.into()),
318
            }
319
        }
3206×
        out.extend(found);
3216×
        Ok(out)
3226×
    }
323
324
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
325
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
326
    ///
327
    /// This is what a server answers a fetch with, so it also carries what
328
    /// verifies the attestations it serves beside it (see
329
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
33055×
    pub fn bundle_for_filtered(
33155×
        &self,
33255×
        changes: &[ChangeHash],
33355×
        max_blob: Option<u64>,
33455×
    ) -> Result<Bundle> {
33555×
        self.bundle_of(changes, max_blob, false, true)
33655×
    }
337
338
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
339
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
340
    /// with their text blobs and chunks among the objects, so neither side
341
    /// decodes or encodes their text.
342378×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
343378×
        self.bundle_of(changes, max_blob, true, true)
344378×
    }
345
346
    /// The keys that signed the attestations this repository serves with
347
    /// its references: each bookmark's latest and each tag's. A fetch
348
    /// bundle carries their identities and certificates (spec §16.2), so a
349
    /// client can check an attestation whose signer signed none of the
350
    /// changes it receives, a delegate or a short-lived key that only
351
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
352
    /// list per reference, computed once per operation head and kept
353
    /// (every bookmark move and tag is an operation): a client sends one
354
    /// fetch per bookmark, and on a bucket store each signature list is a
355
    /// LIST request, so recomputing per fetch cost metalgear2 (145
356
    /// bookmarks) 14 s a fetch.
357433×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
358
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
359
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
360433×
        let key = (self.oxy.clone(), self.head_op()?.0);
361433×
        if let Some(keys) = SERVED
362433×
            .lock()
363433×
            .unwrap_or_else(|p| p.into_inner())
364433×
            .as_ref()
365433×
            .and_then(|m| m.get(&key))
366
        {
367132×
            return Ok(keys.clone());
368301×
        }
369301×
        let keys = self.attest_signers_now()?;
370301×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
371301×
        let map = served.get_or_insert_with(Default::default);
372
        // One entry per repository: an older operation head is never asked
373
        // for again once a newer one is current.
3742507×
        map.retain(|(oxy, _), _| *oxy != key.0);
375301×
        if map.len() >= 1024 {
3760×
            map.clear();
377301×
        }
378301×
        map.insert(key, keys.clone());
379301×
        Ok(keys)
380433×
    }
381
382301×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
383301×
        let view = self.view()?;
384301×
        let pointers = view
385301×
            .bookmarks
386301×
            .keys()
387312×
            .map(|b| self.ref_attest_path(b))
388301×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
389301×
        let mut keys = BTreeSet::new();
390334×
        for p in pointers {
391334×
            let Ok(text) = fs::read_to_string(&p) else {
392271×
                continue;
393
            };
39463×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3950×
                continue;
396
            };
39763×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
398
        }
399301×
        Ok(keys)
400301×
    }
401
402
    /// `serving`: a fetch's answer, which carries the identities and
403
    /// certificates of [`Repo::served_attest_signers`] too.
404774×
    fn bundle_of(
405774×
        &self,
406774×
        changes: &[ChangeHash],
407774×
        max_blob: Option<u64>,
408774×
        raw: bool,
409774×
        serving: bool,
410774×
    ) -> Result<Bundle> {
411774×
        let mut bundle = Bundle::default();
412774×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
413774×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
4141206×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
4151206×
            if !r.is_zero() && self.store.has(r) {
416364×
                objects.insert(*r);
417842×
            }
4181206×
        };
419958×
        for h in changes {
420
            // Raw: the stored bytes, and a skeleton for the rest.
421958×
            let (c, encoded) = if raw {
422506×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
423506×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
4244948×
                for t in texts {
4254948×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
4263×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4273×
                        objects.insert(r);
4283×
                        objects.extend(blob.chunks);
4294945×
                    }
430
                }
431506×
                (skel, Some(bytes))
432
            } else {
433452×
                (self.store.get_change(h)?, None)
434
            };
435958×
            let sigs = self.store.signatures(h)?;
436958×
            add_object(&c.author, &mut objects);
437958×
            for s in &sigs {
43832×
                add_object(&s.key, &mut objects);
43932×
            }
440
            // A replacement's new content only: its old content is the new
441
            // content of a change it depends on, which the receiver holds or
442
            // which this bundle carries (oxygen#136: removing ~1,100 binary
443
            // files sent them all again).
4445946×
            for e in &c.edits {
44532×
                if let Edit::Replace { new: Some(b), .. } = e {
44632×
                    if self.store.has(b) {
44732×
                        if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
448
                        {
44932×
                            if max_blob.is_some_and(|m| blob.length > m) {
4504×
                                continue;
45128×
                            }
45228×
                            objects.insert(*b);
45328×
                            objects.extend(blob.chunks.iter().copied());
4540×
                        }
4550×
                    }
4565914×
                }
457
            }
458958×
            for s in self.store.seals_for(h)? {
459105×
                seals.insert(s);
460105×
            }
461958×
            match encoded {
462506×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
463452×
                None => {
464452×
                    bundle.changes.push((c, sigs));
465452×
                    bundle.hashes.push(*h);
466452×
                }
467
            }
468
        }
469774×
        for r in seals {
470100×
            let attest = self.store.get_attest(&r)?;
471100×
            let sigs = self.store.signatures(&r)?;
472100×
            for s in &sigs {
473100×
                add_object(&s.key, &mut objects);
474100×
            }
475100×
            bundle.attests.push(SignedAttest { attest, sigs });
476
        }
477774×
        let signers: Vec<KeyId> = if serving {
478433×
            let signers = self.served_attest_signers()?;
479433×
            for k in &signers {
480116×
                add_object(k, &mut objects);
481116×
            }
482433×
            signers.into_iter().collect()
483
        } else {
484341×
            Vec::new()
485
        };
486774×
        for r in objects {
487334×
            let (ty, body) = self.store.get(&r)?;
488334×
            bundle.objects.push((ty, body));
489
        }
490774×
        self.attach_certificates_for(&mut bundle, &signers)?;
491774×
        Ok(bundle)
492774×
    }
493
494
    /// Add the certificates of short-lived keys that signed what `bundle`
495
    /// carries, and their issuers' identities, so a receiver can tell who
496
    /// they stand for (spec §14.7). `also` names more signers (a reference
497
    /// attestation sent beside the bundle).
498901×
    pub(crate) fn attach_certificates_for(
499901×
        &self,
500901×
        bundle: &mut Bundle,
501901×
        also: &[KeyId],
502901×
    ) -> Result<()> {
503901×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
504901×
        keys.extend(
505901×
            bundle
506901×
                .changes
507901×
                .iter()
508901×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
509
        );
510901×
        keys.extend(
511901×
            bundle
512901×
                .raw_changes
513901×
                .iter()
514901×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
515
        );
516901×
        keys.extend(
517901×
            bundle
518901×
                .attests
519901×
                .iter()
520901×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
521
        );
522901×
        for k in keys {
523338×
            let Some(r) = self.store.certificate_of(&k)? else {
524289×
                continue;
525
            };
52649×
            let cert = self.store.get_certificate(&r)?;
52749×
            if bundle
52849×
                .certificates
52949×
                .iter()
53049×
                .any(|c| c.cert.hash() == cert.cert.hash())
531
            {
53212×
                continue;
53337×
            }
534
            // An agent's certificate brings its grant's signer too, so the
535
            // receiver can check the grant (oxygen#134).
53637×
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
53781×
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
53881×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
53980×
                    if !bundle
54080×
                        .objects
54180×
                        .iter()
542137×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
54335×
                    {
54435×
                        bundle.objects.push((ObjectType::Identity, body));
54545×
                    }
5461×
                }
547
            }
54837×
            bundle.certificates.push(cert);
549
        }
550901×
        Ok(())
551901×
    }
552
553
    /// Keep the certificates a bundle brings once each verifies with the
554
    /// identity of the issuer it names; one that does not refuses the bundle.
555820×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
556820×
        for c in certs {
55736×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5580×
                RepoError::Msg(format!(
5590×
                    "a certificate names issuer {}, whose identity did not come with it",
5600×
                    c.cert.issuer.short(12)
5610×
                ))
5620×
            })?;
56336×
            c.verify(&issuer)
56436×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
56536×
            self.store.put_identity(&c.cert.key)?;
56636×
            self.store.put_certificate(c)?;
567
        }
568820×
        Ok(())
569820×
    }
570
571
    /// A signer authorized for `reference` by what an issuer certified it
572
    /// as (spec §14.7): a short-lived key with a kept certificate that
573
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
574
    /// signer did not choose) and names a subject the policy grants.
57557×
    pub(crate) fn certified_authorized(
57657×
        &self,
57757×
        p: &crate::policy::Policy,
57857×
        signer: &KeyId,
57957×
        reference: &str,
58057×
        scope: Scope,
58157×
        at_ms: u64,
58257×
    ) -> bool {
58357×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5845×
            return false;
585
        };
58652×
        let Ok(c) = self.store.get_certificate(&r) else {
5870×
            return false;
588
        };
58952×
        let Some(issuer) = p
59052×
            .identity(&c.cert.issuer)
59152×
            .cloned()
59252×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
593
        else {
5940×
            return false;
595
        };
59652×
        c.verify(&issuer).is_ok()
59752×
            && c.cert.key_id() == *signer
59852×
            && c.cert.covers(scope, at_ms)
59942×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
60057×
    }
601
602
    /// Store a bundle's contents. With `strict`, every change must
603
    /// authenticate (signature or seal by its author or a delegate).
604815×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
605815×
        self.import_bundle_inner(bundle, strict, false)
606815×
    }
607
608
    /// Like `import_bundle`, accepting changes whose dependencies are absent
609
    /// (they join the shallow boundary).
6105×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
6115×
        self.import_bundle_inner(bundle, strict, true)
6125×
    }
613
614820×
    fn import_bundle_inner(
615820×
        &self,
616820×
        bundle: &Bundle,
617820×
        strict: bool,
618820×
        shallow: bool,
619820×
    ) -> Result<Vec<ChangeHash>> {
620820×
        let batch = self.store.begin_batch()?;
621820×
        let result = self.import_bundle_batched(bundle, strict, shallow);
622820×
        batch.finish()?;
623818×
        result
624820×
    }
625
626820×
    fn import_bundle_batched(
627820×
        &self,
628820×
        bundle: &Bundle,
629820×
        strict: bool,
630820×
        shallow: bool,
631820×
    ) -> Result<Vec<ChangeHash>> {
632820×
        for (ty, _) in &bundle.objects {
6330×
            if !matches!(
634801×
                ty,
635
                ObjectType::Chunk
636
                    | ObjectType::Blob
637
                    | ObjectType::Identity
638
                    | ObjectType::State
639
                    | ObjectType::Checkpoint
640
            ) {
6410×
                return fail(format!("bundle may not carry {} objects", ty.name()));
642801×
            }
643
        }
644
        // All at once: in a large batch they are compressed on every core.
645820×
        let objects: Vec<(ObjectType, &[u8])> = bundle
646820×
            .objects
647820×
            .iter()
648820×
            .map(|(ty, body)| (*ty, body.as_slice()))
649820×
            .collect();
650820×
        self.store.put_many(&objects)?;
651820×
        self.adopt_certificates(&bundle.certificates)?;
652820×
        for sa in &bundle.attests {
653103×
            let r = self.store.put_attest(&sa.attest)?;
654103×
            for sig in &sa.sigs {
655103×
                self.store.put_signature(&r, sig)?;
656
            }
657103×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
658108×
                for h in hashes {
659108×
                    self.store.index_seal(h, &r)?;
660
                }
6610×
            }
662
        }
663
        // Each change's hash: from the bundle when its maker knew it, else
664
        // worked out once (for a change adding a whole tree, hashing is
665
        // chunking all its text).
666820×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
667811×
            bundle.hashes.clone()
668
        } else {
6699×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
670
        };
671820×
        let raw_hashes: Vec<ChangeHash> = bundle
672820×
            .raw_changes
673820×
            .iter()
674820×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
675820×
            .collect();
676820×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
677820×
        let boundary = self.boundary();
678820×
        let mut imported = Vec::new();
679
        // Changes as stored: checked, then stored as they are, their text
680
        // blobs having come with the objects.
681820×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
682507×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
683507×
            for d in &skel.deps {
684346×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
685
                {
6860×
                    return fail(format!(
687
                        "change {} depends on {}, which is neither stored nor in the bundle",
6880×
                        h.short(12),
6890×
                        d.short(12)
690
                    ));
691346×
                }
692
            }
6934949×
            for t in texts {
6944949×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6954×
                    if !self.store.has(&r) {
6961×
                        return fail(format!(
697
                            "change {} came without its text blob {}",
6981×
                            h.short(12),
6991×
                            r.short(12)
700
                        ));
7013×
                    }
7024945×
                }
703
            }
704506×
            self.store.put(ObjectType::Change, bytes)?;
705506×
            for sig in sigs {
70613×
                self.store.put_signature(&h, sig)?;
707
            }
708506×
            imported.push(h);
709
        }
710819×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
711476×
            for d in &c.deps {
712278×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
713
                {
7143×
                    return fail(format!(
715
                        "change {} depends on {}, which is neither stored nor in the bundle",
7163×
                        h.short(12),
7173×
                        d.short(12)
718
                    ));
719275×
                }
720
            }
721473×
            let stored = self.store.put_change(c)?;
722473×
            if stored != h {
7230×
                return fail(format!(
724
                    "change {} is not the change the bundle names",
7250×
                    h.short(12)
726
                ));
727473×
            }
728473×
            for sig in sigs {
72928×
                self.store.put_signature(&h, sig)?;
730
            }
731473×
            imported.push(h);
732
        }
733816×
        if strict {
73467×
            for h in &imported {
73536×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7364×
                    return fail(format!(
737
                        "change {} is not authenticated by its author",
7384×
                        h.short(12)
739
                    ));
74032×
                }
741
            }
742749×
        }
743812×
        Ok(imported)
744820×
    }
745
746
    /// Verify a reference attestation against an update it claims to describe.
747
    /// `allow_equal` lets a client re-read the attestation it already has; a
748
    /// server receiving a push requires a strictly greater serial.
749
    /// A reference attestation signed by a delegate of an identity the
750
    /// rule lists is authorized as that identity (spec §14.5): the identity
751
    /// named the delegate with the `refs` scope, still in force at `at_ms`
752
    /// (the attestation's wall time), and the policy names the identity.
753
    /// Revoked keys authorize nothing either way.
75472×
    pub(crate) fn delegate_authorized(
75572×
        &self,
75672×
        p: &crate::policy::Policy,
75772×
        signer: &KeyId,
75872×
        reference: &str,
75972×
        at_ms: u64,
76072×
    ) -> bool {
76172×
        if p.is_revoked(signer) {
7621×
            return false;
76371×
        }
76471×
        let Some(rule) = p.rule_for(reference) else {
7650×
            return false;
766
        };
76772×
        rule.keys.iter().any(|k| {
76872×
            !p.is_revoked(k)
76972×
                && p.identity(k)
77072×
                    .cloned()
77172×
                    .or_else(|| self.store.get_identity(k).ok())
77272×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
77372×
        })
77472×
    }
775
776
    /// A lasting attestation (a tag) signed by a key the policy has since
777
    /// rotated away from (spec §14.2) is authorized as the key that
778
    /// succeeded it: a key the rule lists reaches the signer through
779
    /// `previous` links, and the attestation is dated (`at_ms`) before the
780
    /// signer's successor was made, so a superseded key makes nothing new.
781
    /// Revoked keys authorize nothing.
78227×
    pub(crate) fn predecessor_authorized(
78327×
        &self,
78427×
        p: &crate::policy::Policy,
78527×
        signer: &KeyId,
78627×
        reference: &str,
78727×
        at_ms: u64,
78827×
    ) -> bool {
78927×
        if p.is_revoked(signer) {
7900×
            return false;
79127×
        }
79227×
        let Some(rule) = p.rule_for(reference) else {
7930×
            return false;
794
        };
79528×
        let identity = |k: &KeyId| {
79628×
            p.identity(k)
79728×
                .cloned()
79828×
                .or_else(|| self.store.get_identity(k).ok())
79928×
        };
80027×
        rule.keys.iter().any(|k| {
80127×
            if p.is_revoked(k) {
8020×
                return false;
80327×
            }
80427×
            let mut cur = identity(k);
80527×
            for _ in 0..32 {
80628×
                let Some(id) = cur else {
8070×
                    return false;
808
                };
8091×
                match id.previous {
8106×
                    Some(prev) if prev == *signer => return at_ms < id.created,
8111×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
81222×
                    _ => return false,
813
                }
814
            }
8150×
            false
81627×
        })
81727×
    }
818
819106×
    fn check_ref_attest(
820106×
        &self,
821106×
        sa: &SignedAttest,
822106×
        name: &str,
823106×
        old_state: &ObjectRef,
824106×
        new_state: &ObjectRef,
825106×
        last_serial: Option<u64>,
826106×
        allow_equal: bool,
827106×
    ) -> std::result::Result<u64, String> {
828104×
        let serial =
829106×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
830104×
        self.verify_attest_signature(sa)?;
831104×
        Ok(serial)
832106×
    }
833
834
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
835
    /// attestation describes this update of this repository with a serial
836
    /// past the last seen.
837179×
    fn check_ref_attest_body(
838179×
        &self,
839179×
        sa: &SignedAttest,
840179×
        name: &str,
841179×
        old_state: &ObjectRef,
842179×
        new_state: &ObjectRef,
843179×
        last_serial: Option<u64>,
844179×
        allow_equal: bool,
845179×
    ) -> std::result::Result<u64, String> {
846
        let AttestBody::Ref {
847179×
            name: n,
848179×
            old_state: o,
849179×
            new_state: nw,
850179×
            serial,
851179×
        } = &sa.attest.body
852
        else {
8530×
            return Err("attestation is not a ref attestation".into());
854
        };
855179×
        if n != name || o != old_state || nw != new_state {
8561×
            return Err("attestation does not describe this update".into());
857178×
        }
858178×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8590×
            return Err("attestation is for a different repository".into());
860178×
        }
861178×
        if let Some(last) = last_serial {
86293×
            if *serial < last || (*serial == last && !allow_equal) {
8631×
                return Err(format!(
8641×
                    "attestation serial {serial} is not greater than the last seen {last}"
8651×
                ));
86692×
            }
86785×
        }
868177×
        Ok(*serial)
869179×
    }
870
871
    /// An attestation's first signature verifies with its signer's
872
    /// identity, which must be stored here.
873177×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
874177×
        let r = sa.attest.hash();
875177×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
876177×
        let id = self
877177×
            .store
878177×
            .get_identity(&sig.key)
879177×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
880171×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
881177×
    }
882
883
    /// Accept a push (spec §16.4). Without a trust policy every repository
884
    /// is unverified, so unsigned changes and unattested updates are accepted;
885
    /// attestations that are present must still be valid. With a policy,
886
    /// every change and update is checked against it. A newer policy in the
887
    /// push is applied first when it is signed by the current roots.
888317×
    pub fn receive_push(
889317×
        &self,
890317×
        bundle: Bundle,
891317×
        updates: Vec<RefUpdate>,
892317×
        policy: Option<SignedPolicy>,
893317×
        tags: Vec<crate::protocol::TagRef>,
894317×
    ) -> Result<Vec<RefResult>> {
895317×
        Ok(self
896317×
            .receive_push_report(bundle, updates, policy, tags)?
897
            .results)
898317×
    }
899
900
    /// `receive_push` with what a host wants to log: each accepted
901
    /// reference's old and new state and heads, and the changes this push
902
    /// stored (hub spec §6.12).
903363×
    pub fn receive_push_report(
904363×
        &self,
905363×
        bundle: Bundle,
906363×
        updates: Vec<RefUpdate>,
907363×
        policy: Option<SignedPolicy>,
908363×
        tags: Vec<crate::protocol::TagRef>,
909363×
    ) -> Result<PushReport> {
910
        // Updates are checked against the head as it is now, not as this
911
        // handle first read it (oxygenhub#249): another push may have
912
        // landed since.
913363×
        self.refresh()?;
914363×
        let mut report = PushReport::default();
915363×
        let results = &mut report.results;
916363×
        if let Some(sp) = policy {
91736×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
91834×
                Ok(()) => {
91934×
                    results.push(RefResult {
92034×
                        name: "policy".into(),
92134×
                        ok: true,
92234×
                        reason: format!("serial {}", sp.policy.serial),
92334×
                    });
92434×
                }
9252×
                Err(e) => {
9262×
                    results.push(RefResult {
9272×
                        name: "policy".into(),
9282×
                        ok: false,
9292×
                        reason: e,
9302×
                    });
9312×
                    for u in updates {
9320×
                        results.push(RefResult {
9330×
                            name: u.name,
9340×
                            ok: false,
9350×
                            reason: "policy update was rejected".into(),
9360×
                        });
9370×
                    }
9382×
                    return Ok(report);
939
                }
940
            }
941327×
        }
942361×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
943
        // A push of objects alone (one batch of a long history, oxygen#95)
944
        // names no reference: its outcome is reported as `objects`.
945361×
        let objects_only = updates.is_empty() && tags.is_empty();
946361×
        match self.import_bundle(&bundle, policy.is_some()) {
947355×
            Ok(imported) => {
948355×
                if objects_only {
94911×
                    results.push(RefResult {
95011×
                        name: OBJECTS_RESULT.into(),
95111×
                        ok: true,
95211×
                        reason: format!("{} changes stored", imported.len()),
95311×
                    });
954344×
                }
955355×
                report.imported = imported;
956
            }
9576×
            Err(e) => {
9586×
                if objects_only {
9590×
                    results.push(RefResult {
9600×
                        name: OBJECTS_RESULT.into(),
9610×
                        ok: false,
9620×
                        reason: e.to_string(),
9630×
                    });
9646×
                }
9656×
                for u in updates {
9666×
                    results.push(RefResult {
9676×
                        name: u.name,
9686×
                        ok: false,
9696×
                        reason: e.to_string(),
9706×
                    });
9716×
                }
9726×
                return Ok(report);
973
            }
974
        }
975355×
        let (op_ref, op) = self.head_op()?;
976355×
        let mut view = op.view.clone();
977355×
        let mut names = Vec::new();
978355×
        for u in updates {
979339×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
980339×
            let (ok, reason) = match outcome {
981313×
                Ok(()) => (true, String::new()),
98226×
                Err(e) => (false, e),
983
            };
984339×
            if ok {
985313×
                names.push(u.name.clone());
986313×
                let heads = self
987313×
                    .store
988313×
                    .get_state(&u.new_state)
989313×
                    .map(|s| s.heads)
990313×
                    .unwrap_or_default();
991313×
                report.updated.push(RefUpdated {
992313×
                    name: u.name.clone(),
993313×
                    old_state: u.old_state,
994313×
                    new_state: u.new_state,
995313×
                    heads,
996313×
                });
99726×
            }
998339×
            results.push(RefResult {
999339×
                name: u.name,
1000339×
                ok,
1001339×
                reason,
1002339×
            });
1003
        }
1004355×
        for t in &tags {
100522×
            let name = format!("tags/{}", t.name);
100622×
            if t.is_withdrawal() {
10073×
                match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut TagCheck::Received)
1008
                {
10092×
                    Ok(removed) => {
1010
                        // A withdrawal is an update to nothing, as a
1011
                        // bookmark's deletion is.
10122×
                        if removed {
10132×
                            report.updated.push(RefUpdated {
10142×
                                name: name.clone(),
10152×
                                old_state: t.state,
10162×
                                new_state: ObjectRef::ZERO,
10172×
                                heads: vec![],
10182×
                            });
10192×
                        }
10202×
                        names.push(name.clone());
10212×
                        results.push(RefResult {
10222×
                            name,
1023
                            ok: true,
10242×
                            reason: if removed {
10252×
                                "withdrawn"
1026
                            } else {
10270×
                                "already withdrawn"
1028
                            }
10292×
                            .into(),
1030
                        });
1031
                    }
10321×
                    Err(e) => results.push(RefResult {
10331×
                        name,
10341×
                        ok: false,
10351×
                        reason: e.reason,
10361×
                    }),
1037
                }
10383×
                continue;
103919×
            }
104019×
            let new = !view.tags.contains_key(&t.name);
104119×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
1042
                Ok(()) => {
1043
                    // A tag new here is an update too, so a hub can start
1044
                    // its pipeline's tag jobs (oxygenflow#24); one it
1045
                    // already had, sent again, is not.
104614×
                    if new {
104713×
                        report.updated.push(RefUpdated {
104813×
                            name: name.clone(),
104913×
                            old_state: ObjectRef::ZERO,
105013×
                            new_state: t.state,
105113×
                            heads: t.heads.clone(),
105213×
                        });
105313×
                    }
105414×
                    names.push(name.clone());
105514×
                    results.push(RefResult {
105614×
                        name,
105714×
                        ok: true,
105814×
                        reason: String::new(),
105914×
                    });
1060
                }
10615×
                Err(e) => results.push(RefResult {
10625×
                    name,
10635×
                    ok: false,
10645×
                    reason: e.reason,
10655×
                }),
1066
            }
1067
        }
1068355×
        if !names.is_empty() {
1069315×
            self.record_op(
1070315×
                &[op_ref],
1071315×
                &format!("push received: {}", names.join(" ")),
1072315×
                view,
10733×
            )?;
107440×
        }
1075352×
        Ok(report)
1076363×
    }
1077
1078
    /// Check an update's attestation against the latest one for its
1079
    /// reference and store it as the new latest. Failures say what was
1080
    /// being done, for which reference, so a refused push can be diagnosed
1081
    /// from its reason alone.
1082106×
    fn record_update_attest(
1083106×
        &self,
1084106×
        u: &RefUpdate,
1085106×
        sa: &SignedAttest,
1086106×
    ) -> std::result::Result<(), String> {
1087106×
        let name = &u.name;
1088106×
        let last = self
1089106×
            .latest_ref_attest(name)
1090106×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1091106×
            .and_then(|(_, a)| match a.attest.body {
109265×
                AttestBody::Ref { serial, .. } => Some(serial),
10930×
                _ => None,
109465×
            });
1095106×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1096104×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1097104×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1098103×
        for sig in &sa.sigs {
1099103×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1100
        }
1101103×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1102
        // Signed by a short-lived key: a host records when it accepted it.
1103100×
        let certified = sa
1104100×
            .sigs
1105100×
            .first()
1106100×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
1107100×
        if certified {
11086×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
110994×
        }
1110100×
        Ok(())
1111106×
    }
1112
1113
    /// Record that this host accepted attestation `r` now, signed with its
1114
    /// acceptor key (spec §14.7); nothing without one.
111511×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
111611×
        let Some(acceptor) = &self.acceptor else {
11177×
            return Ok(());
1118
        };
11194×
        let (id, sk) = (&acceptor.0, &acceptor.1);
11204×
        let attest = Attest {
11214×
            repo: self.id()?,
11224×
            hlc: Hlc::now(),
11234×
            body: AttestBody::Accepted { attest: *r },
1124
        };
11254×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
11264×
        self.store.put_identity(id)?;
11274×
        let a = self.store.put_attest(&attest)?;
11284×
        self.store.put_signature(&a, &sig)?;
11294×
        self.store.index_add_pub("accepted", r, &a)?;
11304×
        Ok(())
113111×
    }
1132
1133
    /// The host's acceptance of attestation `r`, if one was recorded.
1134227×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1135227×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1136206×
            return Ok(None);
1137
        };
1138
        Ok(Some(SignedAttest {
113921×
            attest: self.store.get_attest(&a)?,
114021×
            sigs: self.store.signatures(&a)?,
1141
        }))
1142227×
    }
1143
1144
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1145
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1146
    /// signer's certificate and accepts `sa`; else the attestation's own
1147
    /// time, which the signer chose.
114831×
    pub(crate) fn certified_time(
114931×
        &self,
115031×
        signer: &KeyId,
115131×
        sa: &SignedAttest,
115231×
        accepted: Option<&SignedAttest>,
115331×
    ) -> u64 {
115431×
        self.issuer_acceptance(signer, sa, accepted)
115531×
            .unwrap_or(sa.attest.hlc.wall_ms)
115631×
    }
1157
1158
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1159
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
1160101×
    pub(crate) fn issuer_acceptance(
1161101×
        &self,
1162101×
        signer: &KeyId,
1163101×
        sa: &SignedAttest,
1164101×
        accepted: Option<&SignedAttest>,
1165101×
    ) -> Option<u64> {
1166101×
        let acc = accepted?;
116746×
        let c = self.store.certificate_of(signer).ok().flatten()?;
116846×
        let cert = self.store.get_certificate(&c).ok()?;
116946×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11700×
            return None;
1171
        };
117246×
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
117343×
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
117443×
        (*attest == sa.attest.hash()
117542×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
117643×
        .then_some(acc.attest.hlc.wall_ms)
1177101×
    }
1178
1179
    /// Keep an acceptance this repository was given for attestation `r`
1180
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1181
    /// what it accepts.
11829×
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
11839×
        let a = self.store.put_attest(&acc.attest)?;
118411×
        for sig in &acc.sigs {
118511×
            self.store.put_signature(&a, sig)?;
1186
        }
11879×
        self.store.index_add_pub("accepted", r, &a)?;
11889×
        Ok(())
11899×
    }
1190
1191
    /// A fetched bookmark's attestation by a signer the policy does not
1192
    /// list itself: a delegate or a short-lived key, whose authority
1193
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1194
    /// attestation's integrated time when the host's log gives one; else
1195
    /// as before, at the host's acceptance for a certified signer, when it
1196
    /// countersigned one, or at the attestation's own time, and said so
1197
    /// when the host keeps a log. Failing at the integrated time but not
1198
    /// as before is a note while logs are new; a large gap between the
1199
    /// claimed and the integrated time is a note.
1200
    #[allow(clippy::too_many_arguments)]
120127×
    pub(crate) fn authorize_in_time(
120227×
        &self,
120327×
        p: &crate::policy::Policy,
120427×
        remote_name: &str,
120527×
        r: &crate::protocol::RemoteRef,
120627×
        sa: &SignedAttest,
120727×
        signer: &KeyId,
120827×
        log: &super::transparency::LogCheck,
120927×
        notes: &mut Vec<String>,
121027×
    ) -> Result<()> {
1211
        use super::transparency::{gap_note, judge, Timed};
121227×
        let own = sa.attest.hlc.wall_ms;
121327×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
121427×
        let time = log.time_of(&r.name);
121529×
        let check = |t_delegate: u64, t_cert: u64| {
121629×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
121727×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
121829×
        };
121927×
        let before = if at != own {
12207×
            "the host's acceptance"
1221
        } else {
122220×
            "the time it claims"
1223
        };
122427×
        let what = format!("{remote_name}/{}", r.name);
122527×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1226
            Timed::Refused => {
12271×
                return fail(format!(
1228
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
12291×
                    signer.short(12)
1230
                ))
1231
            }
12323×
            Timed::Integrated => {}
12331×
            Timed::Disagrees => notes.push(format!(
1234
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
12351×
                signer.short(12),
12361×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1237
            )),
12381×
            Timed::Fallback if log.kept => notes.push(format!(
1239
                "{what}: {} checked at {before}, not at a witnessed time: {}",
12401×
                signer.short(12),
12411×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1242
            )),
124321×
            Timed::Fallback => {}
1244
        }
124526×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
12462×
            notes.push(format!("{what}'s attestation {n}"));
124724×
        }
124826×
        Ok(())
124927×
    }
1250
1251
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1252
    /// at `old_state`, is never the bookmark a non-bare repository has
1253
    /// checked out (a bare one's default is its host's to protect, see
1254
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1255
    /// an attestation by a key that may update it.
1256
    /// The deletion's attestation stays the bookmark's latest, so an older
1257
    /// one cannot be replayed to bring it back.
12583×
    fn apply_deletion(
12593×
        &self,
12603×
        view: &mut View,
12613×
        u: &RefUpdate,
12623×
        policy: Option<&crate::policy::Policy>,
12633×
    ) -> std::result::Result<(), String> {
12643×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
12650×
            return Err(format!("no bookmark {:?} to delete", u.name));
1266
        };
12673×
        if current != u.old_state {
12680×
            return Err("stale: the remote bookmark has moved; pull first".into());
12693×
        }
12703×
        if !self.is_bare() && u.name == self.config.bookmark {
12711×
            return Err(format!(
12721×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
12731×
                u.name
12741×
            ));
12752×
        }
12762×
        if let Some(p) = policy {
12770×
            let Some(sa) = &u.attestation else {
12780×
                return Err(format!(
12790×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12800×
                    u.name
12810×
                ));
1282
            };
12830×
            let signer = sa
12840×
                .sigs
12850×
                .first()
12860×
                .map(|s| s.key)
12870×
                .ok_or("attestation carries no signature")?;
1288
            // Received now: the receiver's own clock is the trusted time.
12890×
            let now = Hlc::now().wall_ms;
12900×
            if !p.authorizes(&signer, &u.name)
12910×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12920×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1293
            {
12940×
                return Err(format!(
12950×
                    "key {} may not delete {:?} under this repository's policy",
12960×
                    signer.short(12),
12970×
                    u.name
12980×
                ));
12990×
            }
13002×
        }
13012×
        if let Some(sa) = &u.attestation {
13021×
            self.record_update_attest(u, sa)?;
13031×
        }
13042×
        view.bookmarks.remove(&u.name);
13052×
        Ok(())
13063×
    }
1307
1308339×
    fn apply_update(
1309339×
        &self,
1310339×
        view: &mut View,
1311339×
        u: &RefUpdate,
1312339×
        policy: Option<&crate::policy::Policy>,
1313339×
    ) -> std::result::Result<(), String> {
1314339×
        if u.name == "policy" {
13150×
            return Err(
13160×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
13170×
            );
1318339×
        }
1319339×
        let empty = self
1320339×
            .store
1321339×
            .put_state(&StateObject::new(vec![]))
1322339×
            .map_err(|e| e.to_string())?;
1323339×
        if u.new_state.is_zero() {
13243×
            return self.apply_deletion(view, u, policy);
1325336×
        }
1326336×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1327336×
        if current != u.old_state {
13286×
            return Err("stale: the remote bookmark has moved; pull first".into());
1329330×
        }
1330330×
        let new_state = self
1331330×
            .store
1332330×
            .get_state(&u.new_state)
1333330×
            .map_err(|_| "new state object is missing".to_string())?;
1334574×
        for h in &new_state.heads {
1335574×
            if !self.store.has(h) {
13361×
                return Err(format!("head {} is missing", h.short(12)));
1337573×
            }
1338
        }
1339329×
        if !u.force {
1340328×
            let old_heads = self
1341328×
                .store
1342328×
                .get_state(&current)
1343328×
                .map_err(|e| e.to_string())?
1344
                .heads;
1345328×
            let closure = self
1346328×
                .closure_in_store(&new_state.heads)
1347328×
                .map_err(|e| e.to_string())?;
1348328×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
13491×
                return Err(format!(
13501×
                    "not a fast-forward: current head {} would be dropped (use --force)",
13511×
                    h.short(12)
13521×
                ));
1353327×
            }
13541×
        }
1355328×
        if let Some(p) = policy {
135659×
            let Some(sa) = &u.attestation else {
13571×
                return Err(format!(
13581×
                    "{:?} requires a signed reference attestation under this repository's policy",
13591×
                    u.name
13601×
                ));
1361
            };
136258×
            let signer = sa
136358×
                .sigs
136458×
                .first()
136558×
                .map(|s| s.key)
136658×
                .ok_or("attestation carries no signature")?;
1367
            // Received now: the receiver's own clock is the trusted time.
136858×
            let now = Hlc::now().wall_ms;
136958×
            if !p.authorizes(&signer, &u.name)
137019×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
137116×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1372
            {
137310×
                return Err(format!(
137410×
                    "key {} may not update {:?} under this repository's policy",
137510×
                    signer.short(12),
137610×
                    u.name
137710×
                ));
137848×
            }
137948×
            let old_heads = self
138048×
                .store
138148×
                .get_state(&current)
138248×
                .map_err(|e| e.to_string())?
1383
                .heads;
138448×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1385269×
        }
1386317×
        if let Some(sa) = &u.attestation {
1387105×
            self.record_update_attest(u, sa)?;
1388212×
        }
1389311×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1390311×
        Ok(())
1391339×
    }
1392
1393
    // ------------------------------------------------------------ client side
1394
13951504×
    fn remote_url(&self, name: &str) -> Result<String> {
13961504×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13973×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13983×
            RepoError::Msg(match names.as_slice() {
13993×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
14001×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1401
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
14021×
                    names.join(", "),
14031×
                    names[0],
14041×
                    names[0]
1405
                ),
14060×
                _ => format!(
1407
                    "no remote named {name:?}; this repository has {}",
14080×
                    names.join(", ")
1409
                ),
1410
            })
14113×
        })
14121504×
    }
1413
1414
    /// Refuse a remote that is another repository. An **unbound** remote
1415
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1416
    /// for pushes, which bind it to this repository's id (spec §16.1).
1417815×
    fn check_remote_id(
1418815×
        &self,
1419815×
        remote: &dyn crate::protocol::Remote,
1420815×
        remote_name: &str,
1421815×
        allow_unbound: bool,
1422815×
    ) -> Result<()> {
1423815×
        let theirs = remote.repo_id()?;
1424814×
        if theirs == self.id()? {
1425784×
            return Ok(());
142630×
        }
142730×
        if theirs == crate::protocol::UNBOUND_ID {
142827×
            if allow_unbound {
142926×
                return Ok(());
14301×
            }
14311×
            return fail(format!(
1432
                "remote {remote_name:?} is empty and unbound: push to it first"
1433
            ));
14343×
        }
14353×
        fail(format!(
1436
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1437
        ))
1438815×
    }
1439
1440
    /// Credentials and trust for a remote: `remote.<name>.token` and
1441
    /// `remote.<name>.ca`, else the defaults for its URL
1442
    /// ([`Repo::fill_credentials`]).
14431123×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
14441123×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
14451123×
        let mut options = RemoteOptions {
14461123×
            repo_id: self.id().ok(),
14471123×
            token: self.config.remote_tokens.get(name).cloned(),
14481123×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
14491123×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
14501123×
            ..RemoteOptions::default()
14511123×
        };
14521123×
        self.fill_credentials(&url, &mut options);
14531123×
        options
14541123×
    }
1455
1456
    /// The user's credential store (`credentials.toml` beside the user
1457
    /// configuration file).
14581149×
    pub fn credentials(&self) -> crate::credentials::Credentials {
14591149×
        crate::credentials::Credentials::at(
14601149×
            self.user_config
14611149×
                .parent()
14621149×
                .map(Path::to_path_buf)
14631149×
                .unwrap_or_else(default_home),
1464
        )
14651149×
    }
1466
1467
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1468
    /// then the user's credential store for its hub, then a remote on the
1469
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1470
    /// When the token is not this remote's own or the environment's, the
1471
    /// other tokens enclosing checkouts hold for the hub are kept to try
1472
    /// if it is refused: a stale stored login must not hide a parent's
1473
    /// good token (oxygen#112).
14741149×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14751149×
        if options.token.is_some() && options.ca.is_some() {
14761×
            return;
14771148×
        }
14781148×
        let own = options.token.is_some();
14791148×
        let env = std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14801148×
        let explicit = own || env;
14811148×
        let stored = self.credentials().options_for(url);
1482
        // A checkout's own token refused as expired or unknown (401) falls
1483
        // back to this computer's sign-in for the hub, never to another
1484
        // checkout's, and never when it is refused for permission (#155).
14851148×
        if own && !env {
14869×
            if let Some(t) = stored
14879×
                .token
14889×
                .clone()
14899×
                .filter(|t| options.token.as_ref() != Some(t))
14903×
            {
14913×
                options.fallback_tokens.push(t);
14923×
                options.fallback_on_401_only = true;
14936×
            }
14941139×
        }
14951148×
        options.token = options.token.take().or(stored.token);
14961148×
        options.ca = options.ca.take().or(stored.ca);
14971148×
        let enclosing = self.enclosing_credentials(url);
14981148×
        if options.token.is_none() {
14991136×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
150012×
        }
15011148×
        if options.ca.is_none() {
15021142×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
15036×
        }
15041148×
        if !explicit {
15051139×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
15065×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
15072×
                    options.fallback_tokens.push(t);
15083×
                }
1509
            }
15109×
        }
15111149×
    }
1512
1513
    /// What to do when `remote`'s own token was refused (`message` says
1514
    /// HTTP 401) and so was this computer's sign-in for its hub, which it
1515
    /// falls back to (oxygen#155).
15163×
    pub fn stale_token_note(&self, remote: &str, message: &str) -> Option<String> {
15173×
        if !message.contains("HTTP 401") {
15182×
            return None;
15191×
        }
15201×
        let own = self.config.remote_tokens.get(remote)?;
15211×
        let url = self.config.remotes.get(remote)?;
15221×
        let stored = self.credentials().options_for(url).token?;
15231×
        (stored != *own).then(|| {
15241×
            format!(
1525
                "the hub refused both this checkout's own token for {remote} (remote.{remote}.token) and your sign-in: \
1526
                 `oxy auth login HUB`, then `oxy config --unset remote.{remote}.token` so the sign-in is used"
1527
            )
15281×
        })
15293×
    }
1530
1531
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1532
    /// checkouts, nearest first.
15331148×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
15341148×
        let mut out = Vec::new();
15351148×
        let Some(hub) = crate::credentials::hub_of(url) else {
1536989×
            return out;
1537
        };
1538159×
        let mut at = self.root.parent();
1539648×
        while let Some(dir) = at {
1540489×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
15410×
                break;
1542
            };
1543489×
            for (key, remote_url) in &cfg {
154419×
                let Some(name) = key
154519×
                    .strip_prefix("remote.")
154619×
                    .and_then(|k| k.strip_suffix(".url"))
1547
                else {
15489×
                    continue;
1549
                };
155010×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
15511×
                    continue;
15529×
                }
15539×
                out.push((
15549×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
15559×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
15569×
                ));
1557
            }
1558489×
            at = dir.parent();
1559
        }
1560159×
        out
15611148×
    }
1562
1563
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1564
    /// no changes and no reference updates, which the receiver stores.
15650×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
15660×
        let remote = self.open_named_remote(remote_name)?;
15670×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
15680×
        let mut bundle = Bundle::default();
15690×
        for r in seals {
15700×
            let attest = self.store.get_attest(r)?;
15710×
            let sigs = self.store.signatures(r)?;
15720×
            bundle
15730×
                .attests
15740×
                .push(crate::protocol::SignedAttest { attest, sigs });
1575
        }
15760×
        let results = remote.push(bundle, vec![], None, vec![])?;
15770×
        if let Some(r) = results.iter().find(|r| !r.ok) {
15780×
            return fail(format!("{}: {}", r.name, r.reason));
15790×
        }
15800×
        Ok(())
15810×
    }
1582
1583
    /// The remote whose URL starts with `base` (a hub), if configured.
15845×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
15855×
        let base = base.trim_end_matches('/');
15865×
        self.config
15875×
            .remotes
15885×
            .iter()
15895×
            .find(|(_, url)| url.trim_end_matches('/') == base)
15905×
            .map(|(name, _)| name.clone())
15915×
    }
1592
1593
    /// Open a remote by name or, failing that, by URL with the default
1594
    /// credentials (see [`Repo::credentials_for`]).
15950×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15960×
        if let Some(name) = self.remote_for_url(url) {
15970×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15980×
        }
15990×
        let options = RemoteOptions {
16000×
            repo_id: self.id().ok(),
16010×
            ..self.credentials_for(url)
16020×
        };
16030×
        Ok((url.to_string(), open_remote(url, &options)?))
16040×
    }
1605
1606
    /// Credentials for a URL: those of the configured remote with that
1607
    /// URL, else the environment's.
16085×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
16095×
        match self.remote_for_url(url) {
16105×
            Some(name) => self.remote_options(&name),
16110×
            None => RemoteOptions {
16120×
                repo_id: self.id().ok(),
16130×
                ..self.credentials_for(url)
16140×
            },
1615
        }
16165×
    }
1617
16181105×
    pub(crate) fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
16191105×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
16201105×
    }
1621
1622220×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1623220×
        self.oxy
1624220×
            .join("remotes")
1625220×
            .join(remote)
1626220×
            .join(format!("{bookmark}.serial"))
1627220×
    }
1628
162973×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
163073×
        fs::read_to_string(self.serial_path(remote, bookmark))
163173×
            .ok()
163273×
            .and_then(|s| s.trim().parse().ok())
163373×
    }
1634
1635147×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1636147×
        let p = self.serial_path(remote, bookmark);
1637147×
        fs::create_dir_all(p.parent().unwrap())?;
1638147×
        write_atomic(&p, serial.to_string().as_bytes())
1639147×
    }
1640
1641471×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1642471×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1643471×
    }
1644
1645
    /// The highest policy serial `remote` has ever presented.
1646399×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1647399×
        fs::read_to_string(self.policy_serial_path(remote))
1648399×
            .ok()
1649399×
            .and_then(|s| s.trim().parse().ok())
1650399×
    }
1651
165272×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
165372×
        let p = self.policy_serial_path(remote);
165472×
        fs::create_dir_all(p.parent().unwrap())?;
165572×
        write_atomic(&p, serial.to_string().as_bytes())
165672×
    }
1657
165832×
    fn lazy_dir(&self) -> PathBuf {
165932×
        self.oxy.join("lazy")
166032×
    }
1661
1662
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
16635×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
16645×
        fs::create_dir_all(self.lazy_dir())?;
16655×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
16665×
    }
1667
1668
    /// Which remote promised an absent blob, if any.
166917×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
167017×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
167117×
            .ok()
167217×
            .map(|s| s.trim().to_string())
167317×
    }
1674
1675
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
16765×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
16775×
        let Some(remote_name) = self.lazy_remote(blob) else {
16780×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1679
        };
16805×
        let remote = self.open_named_remote(&remote_name)?;
16815×
        let objects = remote.objects(&[*blob])?;
168211×
        for (ty, body) in objects {
168311×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
168411×
                self.store.put(ty, &body)?;
16850×
            }
1686
        }
16875×
        if !self.store.has(blob) {
16880×
            return fail(format!(
1689
                "{remote_name} did not send blob {}",
16900×
                blob.short(12)
1691
            ));
16925×
        }
16935×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
16945×
        Ok(())
16955×
    }
1696
1697
    /// After importing from `remote`, record every blob the changes reference
1698
    /// that the store lacks as lazily available from that remote.
16995×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
17005×
        let mut n = 0;
17015×
        for h in changes {
17024×
            let c = self.store.get_change(h)?;
170313×
            for e in &c.edits {
170413×
                if let Edit::Replace { old, new, .. } = e {
17056×
                    for b in [old, new].into_iter().flatten() {
17066×
                        if !self.store.has(b) {
17074×
                            self.register_lazy(b, remote)?;
17084×
                            n += 1;
17092×
                        }
1710
                    }
17117×
                }
1712
            }
1713
        }
17145×
        Ok(n)
17155×
    }
1716
1717
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1718399×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1719399×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1720535×
        for st in view
1721399×
            .bookmarks
1722399×
            .values()
1723399×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1724
        {
1725535×
            if let Ok(s) = self.store.get_state(st) {
1726535×
                have.extend(s.heads);
1727535×
            }
1728
        }
1729399×
        have.extend(view.workspaces.values().copied());
1730399×
        Ok(have.into_iter().collect())
1731399×
    }
1732
1733
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1734405×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1735405×
        let remote = self.open_named_remote(remote_name)?;
1736402×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1737400×
        let resp = remote.refs()?;
1738
        // The host's transparency log (spec §14.8): a fork fails here.
1739399×
        let log = self.check_log(
1740399×
            &self.remote_url(remote_name)?,
1741399×
            self.config.remote_cas.get(remote_name).map(Path::new),
1742399×
            &resp,
17430×
        )?;
1744399×
        let mut log_notes = log.notes.clone();
1745
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1746
        // and signed by roots we trust, or on first contact. A remote that
1747
        // once presented a policy may never present none or an older one:
1748
        // that is a downgrade. A remote that never presented one is
1749
        // unverified, and this fetch is checked only as far as possible.
1750399×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1751399×
        let seen = self.remote_policy_serial(remote_name);
1752399×
        let mut unverified = false;
1753399×
        match &resp.policy {
175438×
            Some(sp) => {
175538×
                if seen.is_some_and(|s| sp.policy.serial < s) {
17560×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
175738×
                }
175814×
                match &local_policy {
175914×
                    Some(l) if sp.policy.serial < l.serial => {}
176014×
                    Some(l) if sp.policy.serial == l.serial => {
176110×
                        if sp.policy.hash() != l.hash() {
17620×
                            return fail(format!(
1763
                                "{remote_name} presents a different policy with the same serial {}",
1764
                                l.serial
1765
                            ));
176610×
                        }
1767
                    }
1768
                    _ => {
176928×
                        self.adopt_policy_chain(
177028×
                            &resp.history,
177128×
                            sp,
177228×
                            &format!("oxy fetch {remote_name}"),
1773
                        )
177428×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1775
                    }
1776
                }
177738×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1778
            }
1779
            None => {
1780361×
                if seen.is_some() {
17810×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1782361×
                }
1783361×
                unverified = true;
1784
            }
1785
        }
1786399×
        let policy = if unverified {
1787361×
            None
1788
        } else {
178938×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1790
        };
1791399×
        let (op_ref, op) = self.head_op()?;
1792399×
        let mut view = op.view.clone();
1793399×
        let have = self.known_heads(&view)?;
1794399×
        let mut report = Vec::new();
1795399×
        let mut skipped = Vec::new();
1796399×
        let max_blob = self.config.max_blob;
1797426×
        for r in resp.refs {
1798426×
            let needed = {
1799426×
                let _t = crate::timing::phase("fetch: negotiate");
1800426×
                remote.negotiate(&have, &r.heads)?
1801
            };
1802426×
            let bundle = {
1803426×
                let _t = crate::timing::phase("fetch: bundle");
1804426×
                remote.fetch(&needed, max_blob)?
1805
            };
1806
            // Changes are not individually re-verified here: the bookmark's
1807
            // attestation (checked below) binds its whole state, and the
1808
            // receiver of the push verified the added changes at that time.
1809
            // A shallow repository takes changes whose dependencies it never
1810
            // held (below what it cloned), as its clone did (#137).
1811426×
            let shallow = self.is_shallow();
1812426×
            let imported = {
1813426×
                let _t = crate::timing::phase("fetch: import");
1814426×
                if shallow {
18152×
                    self.import_bundle_shallow(&bundle, false)?
1816
                } else {
1817424×
                    self.import_bundle(&bundle, false)?
1818
                }
1819
            };
1820426×
            if shallow {
18212×
                self.refresh_boundary(&imported)?;
1822424×
            }
1823426×
            if max_blob.is_some() {
18244×
                self.register_missing_blobs(&imported, remote_name)?;
1825422×
            }
1826426×
            let boundary = if shallow {
18272×
                self.boundary()
1828
            } else {
1829424×
                BTreeSet::new()
1830
            };
1831533×
            for h in &r.heads {
1832533×
                if !self.store.has(h) && !boundary.contains(h) {
18330×
                    return fail(format!("remote did not send head {}", h.short(12)));
1834533×
                }
1835
            }
1836426×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1837426×
            if state != r.state {
18380×
                return fail(format!(
1839
                    "remote state {} does not match its heads",
18400×
                    r.state.short(12)
1841
                ));
1842426×
            }
1843426×
            if let Some(p) = &policy {
184441×
                let Some(sa) = &r.attestation else {
18450×
                    return fail(format!(
1846
                        "{remote_name}/{} has no attestation, which its policy requires",
1847
                        r.name
1848
                    ));
1849
                };
185041×
                let signer = sa
185141×
                    .sigs
185241×
                    .first()
185341×
                    .map(|s| s.key)
185441×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
185541×
                if !p.authorizes(&signer, &r.name) {
185620×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
185721×
                }
1858385×
            }
1859426×
            if let Some(sa) = &r.attestation {
1860
                let AttestBody::Ref {
186173×
                    old_state,
186273×
                    new_state,
1863
                    ..
186473×
                } = &sa.attest.body
1865
                else {
18660×
                    return fail("remote sent a non-ref attestation for a bookmark");
1867
                };
186873×
                let (old_state, new_state) = (*old_state, *new_state);
186973×
                let serial = self
187073×
                    .check_ref_attest_body(
187173×
                        sa,
187273×
                        &r.name,
187373×
                        &old_state,
187473×
                        &new_state,
187573×
                        self.last_seen_serial(remote_name, &r.name),
1876
                        true,
1877
                    )
187873×
                    .map_err(|e| {
18790×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
18800×
                    })?;
188173×
                if new_state != r.state {
18820×
                    return fail(format!(
1883
                        "attestation for {}/{} does not cover its current state",
1884
                        remote_name, r.name
1885
                    ));
188673×
                }
1887
                // A signature this client cannot verify (its signer unknown
1888
                // here, as from a host that did not send the identity, or
1889
                // bad) fails that bookmark alone: it stays as it was and
1890
                // the rest are fetched (oxygenhub#266). The current
1891
                // bookmark, which a pull would take, still fails the fetch.
1892
                // A policy's requirements were checked above and still fail.
189373×
                if let Err(e) = self.verify_attest_signature(sa) {
189412×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
189512×
                    if r.name == self.config.bookmark {
18963×
                        return fail(why);
18979×
                    }
18989×
                    skipped.push((r.name, why));
18999×
                    continue;
190061×
                }
190161×
                let ar = self.store.put_attest(&sa.attest)?;
190261×
                for sig in &sa.sigs {
190361×
                    self.store.put_signature(&ar, sig)?;
1904
                }
190561×
                self.record_serial(remote_name, &r.name, serial)?;
1906353×
            }
1907414×
            view.remotes
1908414×
                .entry(remote_name.to_string())
1909414×
                .or_default()
1910414×
                .insert(r.name.clone(), state);
1911414×
            report.push((r.name, r.heads, imported.len()));
1912
        }
1913396×
        let mut new_tags = 0;
1914396×
        for t in &resp.tags {
191531×
            if view.tags.contains_key(&t.name) {
19167×
                continue;
191724×
            }
1918
            // Withdrawn here: the name is not used again.
191924×
            if self.tag_withdrawal(&t.name)?.is_some() {
19200×
                continue;
192124×
            }
1922
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
192324×
            let missing: Vec<ChangeHash> = t
192424×
                .heads
192524×
                .iter()
192624×
                .filter(|h| !self.store.has(h))
192724×
                .copied()
192824×
                .collect();
192924×
            if !missing.is_empty() {
19300×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
19310×
                let bundle = remote.fetch(&needed, max_blob)?;
19320×
                self.import_bundle(&bundle, false)?;
193324×
            }
193424×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
193524×
            let mut check = TagCheck::Fetched {
193624×
                remote: remote_name,
193724×
                log: &log,
193824×
                notes: &mut log_notes,
193924×
            };
194024×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
194122×
                Ok(()) => new_tags += 1,
1942
                // Nothing says when a short-lived key signed it: the tag is
1943
                // left out, said so, and the rest is fetched (oxygen#129).
19442×
                Err(e) if e.untimed => {
19452×
                    skipped.push((format!("tags/{}", t.name), e.reason));
19462×
                }
19470×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1948
            }
1949
        }
1950
        // The remote withdrew a tag this repository has: so does this one,
1951
        // once the withdrawal is checked as a push's would be; one that is
1952
        // not is left as it is, said so (oxygenhub#301).
1953396×
        let mut withdrawn_tags = Vec::new();
1954396×
        for t in &resp.withdrawn {
19551×
            if !view.tags.contains_key(&t.name) {
19560×
                continue;
19571×
            }
19581×
            let mut check = TagCheck::Fetched {
19591×
                remote: remote_name,
19601×
                log: &log,
19611×
                notes: &mut log_notes,
19621×
            };
19631×
            match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut check) {
19641×
                Ok(true) => withdrawn_tags.push(t.name.clone()),
19650×
                Ok(false) => {}
19660×
                Err(e) => skipped.push((
19670×
                    format!("tags/{}", t.name),
19680×
                    format!("withdrawn on {remote_name}, kept here: {}", e.reason),
19690×
                )),
1970
            }
1971
        }
1972396×
        if view != op.view {
1973380×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
197416×
        }
1975396×
        let _ = self.run_hook(
1976396×
            "post-fetch",
1977396×
            &format!(
1978
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1979396×
                json_str(remote_name),
1980411×
                json_array(report.iter().map(|(n, heads, _)| format!(
1981
                    "{{\"name\":{},\"heads\":{}}}",
1982411×
                    json_str(n),
1983518×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1984
                )))
1985
            ),
1986
        );
1987396×
        Ok(FetchReport {
1988396×
            refs: report,
1989396×
            unverified,
1990396×
            new_tags,
1991396×
            withdrawn_tags,
1992396×
            log_notes,
1993396×
            skipped,
1994396×
        })
1995405×
    }
1996
1997
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1998
    /// the changes within `depth` steps of its heads, and the boundary below.
19993×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
20003×
        let remote = self.open_named_remote(remote_name)?;
20013×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
20023×
        let resp = remote.refs()?;
20033×
        let bookmark = self.config.bookmark.clone();
20043×
        if let Some(sp) = &resp.policy {
20050×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
20060×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
20070×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
20083×
        }
20093×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
20100×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
2011
        };
20123×
        if r.heads.is_empty() {
20130×
            return Ok(0);
20143×
        }
2015
        // Base: the remote's checkpoint of exactly these heads, without its
2016
        // graph blobs, which come in parts below (#137).
20173×
        let cp_bundle = {
20183×
            let _t = crate::timing::phase("shallow: checkpoint request");
20193×
            remote.checkpoint_index(&r.heads)?
2020
        };
2021
        // In one batch: a big state's checkpoint is tens of thousands of
2022
        // graph blobs and chunks, which stored one by one were each written
2023
        // loose and flushed (a VS Code clone ran at 27 objects a second).
20243×
        let objects: Vec<(ObjectType, &[u8])> = cp_bundle
20253×
            .objects
20263×
            .iter()
20279×
            .map(|(ty, body)| (*ty, body.as_slice()))
20283×
            .collect();
20293×
        let t_store = crate::timing::phase("shallow: store the checkpoint");
20303×
        let batch = self.store.begin_batch()?;
20313×
        let stored = self.store.put_many(&objects);
20323×
        batch.finish()?;
20333×
        drop(t_store);
20343×
        let cp_ref = objects
20353×
            .iter()
20363×
            .zip(stored?)
20379×
            .find(|((ty, _), _)| *ty == ObjectType::Checkpoint)
20383×
            .map(|(_, r)| r);
20393×
        let Some(cp_ref) = cp_ref else {
20400×
            return fail(format!("{remote_name} sent no checkpoint"));
2041
        };
2042
        // The graph blobs the payload names, with their chunks, a part at
2043
        // a time (#137): one answer for a big state was gigabytes, held
2044
        // whole on both sides. A remote that sent the whole checkpoint has
2045
        // left none to ask for.
20463×
        let cp = crate::objects::Checkpoint::decode(
20473×
            &self.store.get_typed(&cp_ref, ObjectType::Checkpoint)?,
20480×
        )?;
20493×
        let graphs: Vec<ObjectRef> = self
20503×
            .checkpoint_graph_blobs(&cp)?
20513×
            .into_iter()
20523×
            .filter(|b| !self.store.has(b))
20533×
            .collect();
2054
        {
20553×
            let _t = crate::timing::phase("shallow: the checkpoint's graphs, in parts");
20563×
            for part in graphs.chunks(CHECKPOINT_PART) {
20570×
                let objects = remote.objects(part)?;
20580×
                let objects: Vec<(ObjectType, &[u8])> = objects
20590×
                    .iter()
20600×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
20610×
                    .map(|(ty, body)| (*ty, body.as_slice()))
20620×
                    .collect();
20630×
                let batch = self.store.begin_batch()?;
20640×
                let stored = self.store.put_many(&objects);
20650×
                batch.finish()?;
20660×
                stored?;
2067
            }
20683×
            if let Some(b) = graphs.iter().find(|b| !self.store.has(b)) {
20690×
                return fail(format!(
2070
                    "{remote_name} did not send graph blob {}",
20710×
                    b.short(12)
2072
                ));
20733×
            }
2074
        }
20753×
        self.install_checkpoint(&bookmark, &cp_ref)?;
20763×
        let _t_blobs = crate::timing::phase("shallow: the binary files' blobs");
2077
        // The blobs of the state's opaque files come with no change when the
2078
        // window holds none of the changes that set them (#137): fetch them
2079
        // now, or under `filter.max-blob` leave them to be fetched on read.
20803×
        let base = State::from_checkpoint_history(&self.read_blob(&cp.payload)?)?;
20813×
        let mut missing: Vec<ObjectRef> = base
20823×
            .opaque_nodes()
20833×
            .iter()
20843×
            .flat_map(|n| base.live_blobs(n))
20853×
            .filter(|b| !self.store.has(b))
20863×
            .collect();
20873×
        missing.sort();
20883×
        missing.dedup();
20893×
        if self.config.max_blob.is_some() {
20901×
            for b in &missing {
20911×
                self.register_lazy(b, remote_name)?;
2092
            }
2093
        } else {
20942×
            for part in missing.chunks(512) {
20951×
                let objects = remote.objects(part)?;
20961×
                let objects: Vec<(ObjectType, &[u8])> = objects
20971×
                    .iter()
20982×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
20992×
                    .map(|(ty, body)| (*ty, body.as_slice()))
21001×
                    .collect();
21011×
                let batch = self.store.begin_batch()?;
21021×
                let stored = self.store.put_many(&objects);
21031×
                batch.finish()?;
21041×
                stored?;
2105
            }
21062×
            if let Some(b) = missing.iter().find(|b| !self.store.has(b)) {
21070×
                return fail(format!("{remote_name} did not send blob {}", b.short(12)));
21082×
            }
2109
        }
2110
        // History window. Depth 0 takes none (#137): the checkpoint holds
2111
        // every change's metadata, and its heads become the boundary, so a
2112
        // state of many heads (33,835 in the VS Code import) costs nothing
2113
        // to fetch.
21143×
        let imported = if depth == 0 {
21152×
            let mut boundary = self.boundary();
21162×
            boundary.extend(r.heads.iter().filter(|h| !self.store.has(h)).copied());
21172×
            self.write_boundary(&boundary)?;
21182×
            Vec::new()
2119
        } else {
21201×
            let wanted = remote.shallow(&r.heads, depth)?;
21211×
            let bundle = remote.fetch(&wanted, self.config.max_blob)?;
21221×
            self.import_bundle_shallow(&bundle, false)?
2123
        };
21243×
        if self.config.max_blob.is_some() {
21251×
            self.register_missing_blobs(&imported, remote_name)?;
21262×
        }
21273×
        self.refresh_boundary(&imported)?;
21283×
        if let Some(sa) = &r.attestation {
21290×
            let ar = self.store.put_attest(&sa.attest)?;
21300×
            for sig in &sa.sigs {
21310×
                self.store.put_signature(&ar, sig)?;
2132
            }
21330×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
21340×
                self.record_serial(remote_name, &r.name, serial)?;
21350×
            }
21363×
        }
21373×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
21383×
        let (op_ref, op) = self.head_op()?;
21393×
        let mut view = op.view.clone();
21403×
        view.remotes
21413×
            .entry(remote_name.to_string())
21423×
            .or_default()
21433×
            .insert(r.name.clone(), state);
21443×
        self.record_op(
21453×
            &[op_ref],
21463×
            &format!("oxy fetch {remote_name} --depth {depth}"),
21473×
            view,
21480×
        )?;
21493×
        Ok(imported.len())
21503×
    }
2151
2152
    /// Fetch, then take the union of the local bookmark's state with the
2153
    /// remote's: no merge change, conflicts become reified (spec §9.4).
2154106×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
2155106×
        let _wc = self.lock_working_copy()?;
2156106×
        let skipped = self.fetch(remote_name)?.skipped;
2157102×
        let (op_ref, op) = self.head_op()?;
2158102×
        let current = self.config.bookmark.clone();
2159102×
        let mut local_current = self.heads_of(&op.view, &current)?;
2160102×
        local_current.sort();
2161102×
        let mut view = op.view.clone();
2162102×
        let mut current_heads = local_current.clone();
2163102×
        let mut changed = false;
2164102×
        let mut others = Vec::new();
2165102×
        let tracked = op
2166102×
            .view
2167102×
            .remotes
2168102×
            .get(remote_name)
2169102×
            .cloned()
2170102×
            .unwrap_or_default();
2171107×
        for (name, remote_state) in tracked {
2172
            // Every local bookmark tracks the remote's of the same name;
2173
            // the current one may be new here.
2174107×
            let local_state = op.view.bookmarks.get(&name).copied();
2175107×
            if local_state.is_none() && name != current {
21761×
                continue;
2177106×
            }
2178106×
            if local_state == Some(remote_state) {
217910×
                continue;
218096×
            }
218196×
            let local = self.heads_of(&op.view, &name)?;
218296×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2183126×
            if remote_heads.iter().all(|h| local.contains(h)) {
21840×
                continue;
218596×
            }
218696×
            let mut all = local.clone();
218796×
            all.extend(remote_heads);
218896×
            let st = self.load_state_history(&all)?;
218996×
            let mut heads = st.maximal(&all);
219096×
            heads.sort();
219196×
            let mut sorted_local = local;
219296×
            sorted_local.sort();
219396×
            if heads == sorted_local {
21941×
                continue;
219595×
            }
219695×
            view.bookmarks.insert(
219795×
                name.clone(),
219895×
                self.store.put_state(&StateObject::new(heads.clone()))?,
2199
            );
220095×
            if name == current {
220193×
                changed = true;
220293×
                current_heads = heads;
220393×
            } else {
22042×
                others.push(name);
22052×
            }
2206
        }
2207102×
        if changed || !others.is_empty() {
220894×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
22098×
        }
2210
        // The working copy follows its bookmark whenever nothing would be
2211
        // lost, also when this pull brought nothing new but it had been
2212
        // left behind (oxygen#89).
2213102×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2214
        Ok(PullReport {
2215102×
            heads: if changed {
221693×
                current_heads
2217
            } else {
22189×
                local_current
2219
            },
2220102×
            changed,
2221102×
            checked_out,
2222102×
            others,
2223102×
            skipped,
2224
        })
2225106×
    }
2226
2227
    /// How many changes the working copy's bookmark has that its base
2228
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2229
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2230
    /// the bookmark or holds changes the bookmark lacks. History is read
2231
    /// only when the base and the bookmark's heads differ (oxygen#89).
22327×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
22337×
        let (_, wc) = self.working_copy()?;
22347×
        let mut base = wc.deps.clone();
22357×
        base.sort();
22367×
        let mut heads = self.bookmark_heads()?;
22377×
        heads.sort();
22387×
        if base == heads || heads.is_empty() {
22396×
            return Ok(None);
22401×
        }
22411×
        let state = self.load_state_history(&heads)?;
22421×
        if !base.iter().all(|h| state.contains(h)) {
22430×
            return Ok(None);
22441×
        }
22451×
        let had = if base.is_empty() {
22460×
            0
2247
        } else {
22481×
            self.load_state_history(&base)?.len()
2249
        };
22501×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
22517×
    }
2252
2253
    /// Bring the working copy to `heads`, the state of its bookmark
2254
    /// `bookmark`, when nothing would be lost: its base is part of that
2255
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2256
    /// with uncommitted work, the work comes along when the new changes
2257
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2258
    /// it followed only from exactly the bookmark's old heads, so a working
2259
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2260
    /// or a pull from another workspace) never caught up, and nothing said
2261
    /// so (oxygen#74, #89). Returns whether it moved.
2262102×
    pub fn follow_bookmark(
2263102×
        &self,
2264102×
        heads: &[ChangeHash],
2265102×
        bookmark: &str,
2266102×
        command: &str,
2267102×
    ) -> Result<bool> {
2268102×
        let snap = self.snapshot(command)?;
2269102×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2270102×
        let mut base = snap.base.maximal(&snap.wc.deps);
2271102×
        base.sort();
2272102×
        let mut target = heads.to_vec();
2273102×
        target.sort();
2274102×
        if base == target {
22758×
            return Ok(false);
227694×
        }
227794×
        let state = self.load_state_history(heads)?;
2278170×
        if !base.iter().all(|h| state.contains(h)) {
2279
            // The working copy holds changes the bookmark lacks: not ours to move.
22800×
            return Ok(false);
228194×
        }
228294×
        if clean {
228394×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
228494×
            Ok(true)
2285
        } else {
22860×
            Ok(self
22870×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
22880×
                .is_ok())
2289
        }
2290102×
    }
2291
2292
    /// Withdraw tag `tag` on `remote_name` (`oxy push --delete tags/NAME`,
2293
    /// oxygenhub#301): withdrawn here first when it still is a tag here
2294
    /// (`oxy tag delete`), then the withdrawal alone is sent, with its
2295
    /// signer's identity and certificate.
22963×
    pub fn push_tag_withdrawal(&self, remote_name: &str, tag: &str) -> Result<Vec<RefResult>> {
22973×
        let remote = self.open_named_remote(remote_name)?;
22983×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
22993×
        let resp = remote.refs()?;
23003×
        let name = format!("tags/{tag}");
23013×
        if resp.withdrawn.iter().any(|t| t.name == tag) {
23021×
            return Ok(vec![RefResult {
23031×
                name,
23041×
                ok: true,
23051×
                reason: "already withdrawn".into(),
23061×
            }]);
23072×
        }
23082×
        let Some(there) = resp.tags.iter().find(|t| t.name == tag) else {
23090×
            return fail(format!("{remote_name} has no tag {tag}"));
2310
        };
23112×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
23120×
            return fail(format!("{remote_name} enforces a trust policy; withdrawing a tag needs an identity (`oxy identity create`)"));
23132×
        }
23142×
        if self.tag_withdrawal(tag)?.is_none() {
23152×
            match self.view()?.tags.get(tag) {
23162×
                Some(st) if *st == there.state => {
23172×
                    self.tag_delete(tag, "")?;
2318
                }
2319
                Some(_) => {
23200×
                    return fail(format!(
2321
                        "tag {tag} names another state here than on {remote_name}"
2322
                    ))
2323
                }
2324
                None => {
23250×
                    return fail(format!(
2326
                        "there is no tag {tag} here to withdraw: `oxy fetch {remote_name}` first"
2327
                    ))
2328
                }
2329
            }
23300×
        }
23312×
        let Some(w) = self
23322×
            .withdrawn_refs()?
23332×
            .into_iter()
23342×
            .find(|w| w.name == tag && w.state == there.state)
2335
        else {
23360×
            return fail(format!(
2337
                "tag {tag} was withdrawn here at another state than {remote_name}'s"
2338
            ));
2339
        };
23402×
        let mut bundle = Bundle::default();
23412×
        let signers: Vec<KeyId> = w
23422×
            .attestation
23432×
            .iter()
23442×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
23452×
            .collect();
23462×
        for k in &signers {
23472×
            if let Ok(id) = self.identity(k) {
23482×
                bundle.objects.push((ObjectType::Identity, id.encode()));
23492×
            }
2350
        }
23512×
        self.attach_certificates_for(&mut bundle, &signers)?;
23522×
        remote.push(bundle, vec![], None, vec![w])
23533×
    }
2354
2355
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2356
    /// changes and attesting the reference when a key is available.
2357
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2358
    /// state, attested when we have an identity. The local bookmark, if
2359
    /// any, is kept; only the remote-tracking entry goes.
23608×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
23618×
        if let Some(tag) = bookmark.strip_prefix("tags/") {
23623×
            return self.push_tag_withdrawal(remote_name, tag);
23635×
        }
23645×
        let remote = self.open_named_remote(remote_name)?;
23655×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
23665×
        let resp = remote.refs()?;
23677×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
23681×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2369
        };
23704×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
23710×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
23724×
        }
23734×
        let attestation = match self.secret_key()? {
23742×
            Some(_) => Some(self.sign_attest(&Attest {
23752×
                repo: self.id()?,
23762×
                hlc: Hlc::now(),
23772×
                body: AttestBody::Ref {
23782×
                    name: bookmark.to_string(),
23792×
                    old_state: r.state,
23802×
                    new_state: ObjectRef::ZERO,
23812×
                    serial: r.last_serial.unwrap_or(0) + 1,
23822×
                },
23830×
            })?),
23842×
            None => None,
2385
        };
23864×
        let results = remote.push(
23874×
            Bundle::default(),
23884×
            vec![RefUpdate {
23894×
                name: bookmark.to_string(),
23904×
                old_state: r.state,
23914×
                new_state: ObjectRef::ZERO,
23924×
                force: true,
23934×
                attestation,
23944×
            }],
23954×
            None,
23964×
            vec![],
23970×
        )?;
23984×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
23992×
            let (op_ref, op) = self.head_op()?;
24002×
            let mut view = op.view.clone();
24012×
            if let Some(m) = view.remotes.get_mut(remote_name) {
24022×
                m.remove(bookmark);
24032×
            }
24042×
            self.record_op(
24052×
                &[op_ref],
24062×
                &format!("oxy push {remote_name} --delete {bookmark}"),
24072×
                view,
24080×
            )?;
24092×
        }
24104×
        Ok(results)
24118×
    }
2412
2413
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2414
    /// repository's config (its URL, token, CA and store settings), its
2415
    /// tracking bookmarks in the view, and a store remote's mirror under
2416
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
24173×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
24183×
        if !self.config.remotes.contains_key(name) {
24191×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
24202×
        }
24212×
        let prefix = format!("remote.{name}.");
24222×
        let keys: Vec<String> = self
24232×
            .config
24242×
            .repo_layer()
24252×
            .keys()
24264×
            .filter(|k| k.starts_with(&prefix))
24272×
            .cloned()
24282×
            .collect();
24293×
        for k in keys {
24303×
            self.config.set(&k, "")?;
2431
        }
24322×
        self.config.remotes.remove(name);
24332×
        self.save_config()?;
24342×
        let (op_ref, op) = self.head_op()?;
24352×
        if op.view.remotes.contains_key(name) {
24361×
            let mut view = op.view.clone();
24371×
            view.remotes.remove(name);
24381×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
24391×
        }
24402×
        let mirror = self.oxy.join("remotes").join(name);
24412×
        if mirror.is_dir() {
24420×
            fs::remove_dir_all(&mirror)?;
24432×
        }
24442×
        Ok(())
24453×
    }
2446
2447
    /// Send `bundle`'s blobs and chunks ahead of it, in parts of about
2448
    /// `push.batch-bytes` of objects alone, when the whole would be larger
2449
    /// (oxygen#133): one change can bring more blobs than one request may
2450
    /// carry, and a proxy in front of a hub refuses a request past its limit
2451
    /// (Cloudflare's is 100 MB). What is left, the changes with their
2452
    /// identities and states, is returned to send as before. A receiver
2453
    /// stores objects as they come, and checks a change's blobs are stored.
2454325×
    fn send_objects_ahead(
2455325×
        &self,
2456325×
        remote: &dyn crate::protocol::Remote,
2457325×
        remote_name: &str,
2458325×
        mut bundle: Bundle,
2459325×
        progress: crate::store::Progress,
2460325×
    ) -> Result<Bundle> {
2461325×
        let limit = self.config.push_batch_bytes;
2462325×
        let changes: u64 = bundle
2463325×
            .changes
2464325×
            .iter()
2465393×
            .map(|(c, _)| c.encode().len() as u64)
2466325×
            .sum();
2467325×
        let objects: u64 = bundle.objects.iter().map(|(_, b)| b.len() as u64).sum();
2468325×
        if changes + objects <= limit {
2469318×
            return Ok(bundle);
24707×
        }
24717×
        let (mut kept, mut parts, mut part, mut bytes) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
24729×
        for (ty, body) in std::mem::take(&mut bundle.objects) {
24739×
            if !matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
24740×
                kept.push((ty, body));
24750×
                continue;
24769×
            }
24779×
            if !part.is_empty() && bytes + body.len() as u64 > limit {
24783×
                parts.push(std::mem::take(&mut part));
24793×
                bytes = 0;
24806×
            }
24819×
            bytes += body.len() as u64;
24829×
            part.push((ty, body));
2483
        }
24847×
        if !part.is_empty() {
24851×
            parts.push(part);
24866×
        }
24877×
        let n = parts.len();
24887×
        for (i, objects) in parts.into_iter().enumerate() {
24894×
            progress(&format!(
24904×
                "objects {} of {n}: {} blobs and chunks",
24914×
                i + 1,
24924×
                objects.len()
24934×
            ));
24944×
            let results = remote.push(
24954×
                Bundle {
24964×
                    objects,
24974×
                    ..Default::default()
24984×
                },
24994×
                vec![],
25004×
                None,
25014×
                vec![],
25020×
            )?;
25034×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
25044×
                Some(r) if r.ok => {}
25050×
                Some(r) => {
25060×
                    return fail(format!(
2507
                        "{remote_name} refused objects part {} of {n}: {}",
25080×
                        i + 1,
2509
                        r.reason
2510
                    ))
2511
                }
2512
                None => {
25130×
                    return fail(format!(
2514
                        "{remote_name} does not take a push in parts, and this one is too large for one: update the server's oxy"
2515
                    ))
2516
                }
2517
            }
2518
        }
25197×
        bundle.objects = kept;
25207×
        Ok(bundle)
2521325×
    }
2522
2523
    /// `changes`, in dependency order, cut into batches of about
2524
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2525
    /// There is always one, perhaps empty.
2526320×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2527320×
        let blob_len = |r: &ObjectRef| -> u64 {
252837×
            self.store
252937×
                .get_typed(r, ObjectType::Blob)
253037×
                .ok()
253137×
                .and_then(|b| Blob::decode(&b).ok())
253237×
                .map_or(0, |b| b.length)
253337×
        };
2534320×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2535393×
        for h in changes {
2536393×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2537393×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2538393×
            let mut weight = raw.len() as u64;
2539496×
            for t in &texts {
2540496×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
254126×
                    weight += blob_len(r);
2542470×
                }
2543
            }
2544661×
            for e in &c.edits {
254511×
                if let Edit::Replace { new: Some(b), .. } = e {
254611×
                    weight += blob_len(b);
2547650×
                }
2548
            }
2549393×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
25505×
                out.push(std::mem::take(&mut batch));
25515×
                bytes = 0;
2552388×
            }
2553393×
            batch.push(*h);
2554393×
            bytes += weight;
2555
        }
2556320×
        out.push(batch);
2557320×
        Ok(out)
2558320×
    }
2559
2560379×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2561379×
        let bookmark = self.config.bookmark.clone();
2562379×
        self.push_bookmark(remote_name, &bookmark, force)
2563379×
    }
2564
2565
    /// `push` for a named bookmark (`oxy push -b NAME`).
2566394×
    pub fn push_bookmark(
2567394×
        &self,
2568394×
        remote_name: &str,
2569394×
        bookmark: &str,
2570394×
        force: bool,
2571394×
    ) -> Result<Vec<RefResult>> {
2572394×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2573394×
    }
2574
2575
    /// `push_bookmark`, saying how a long push is going: one line per
2576
    /// batch sent (oxygen#95).
2577
    /// What a push may take the remote to hold already: the heads of the
2578
    /// bookmark pushed, and of every other bookmark it lists that are held
2579
    /// here, so a new bookmark made from main sends only what main lacks
2580
    /// (oxygen#142), not its whole history again.
2581322×
    pub(crate) fn remote_holds(
2582322×
        &self,
2583322×
        refs: &[crate::protocol::RemoteRef],
2584322×
        bookmark_heads: &[ChangeHash],
2585322×
    ) -> Vec<ChangeHash> {
2586322×
        let mut have: Vec<ChangeHash> = bookmark_heads.to_vec();
2587325×
        for h in refs.iter().flat_map(|r| &r.heads) {
2588325×
            if !have.contains(h) && self.store.has(h) {
258921×
                have.push(*h);
2590304×
            }
2591
        }
2592322×
        have
2593322×
    }
2594
2595403×
    pub fn push_bookmark_with(
2596403×
        &self,
2597403×
        remote_name: &str,
2598403×
        bookmark: &str,
2599403×
        force: bool,
2600403×
        progress: crate::store::Progress,
2601403×
    ) -> Result<Vec<RefResult>> {
2602403×
        let (op_ref, op) = self.head_op()?;
2603403×
        if !op.view.bookmarks.contains_key(bookmark) {
26040×
            return fail(format!("no bookmark {bookmark}"));
2605403×
        }
2606403×
        let bookmark = bookmark.to_string();
2607403×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2608
        // pre-push hook: may veto before the remote is contacted.
2609403×
        self.run_hook(
2610403×
            "pre-push",
2611403×
            &format!(
2612
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2613403×
                json_str(remote_name),
2614403×
                json_str(&bookmark),
2615762×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2616
            ),
26171×
        )?;
2618402×
        let remote = self.open_named_remote(remote_name)?;
2619402×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2620399×
        let resp = remote.refs()?;
2621399×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2622399×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2623399×
        let policy_to_send = match (&local_policy, &resp.policy) {
262444×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
262516×
            (Some(l), None) => Some(l.clone()),
262626×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
26271×
                return fail(format!(
2628
                    "{remote_name} has a newer policy (serial {}); fetch first",
2629
                    r.policy.serial
2630
                ));
2631
            }
2632364×
            _ => None,
2633
        };
2634398×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2635398×
        if remote_has_policy && self.secret_key()?.is_none() {
26361×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2637397×
        }
2638397×
        let remote_tags: BTreeSet<String> = resp
2639397×
            .tags
2640397×
            .iter()
2641397×
            .chain(&resp.withdrawn)
2642397×
            .map(|t| t.name.clone())
2643397×
            .collect();
2644397×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2645397×
            .tag_refs()?
2646397×
            .into_iter()
2647397×
            .filter(|t| !remote_tags.contains(&t.name))
2648397×
            .collect();
2649
        // Tags withdrawn here that the remote still has, at the same state
2650
        // (oxygenhub#301).
2651397×
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2652397×
            .withdrawn_refs()?
2653397×
            .into_iter()
2654397×
            .filter(|w| {
26552×
                resp.tags
26562×
                    .iter()
26572×
                    .any(|t| t.name == w.name && t.state == w.state)
26582×
            })
2659397×
            .collect();
2660397×
        let refs = resp.refs;
2661397×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2662397×
        let (remote_state, remote_heads, last_serial) =
2663398×
            match refs.iter().find(|r| r.name == bookmark) {
2664373×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
266524×
                None => (empty, vec![], None),
2666
            };
2667397×
        let new_state = self
2668397×
            .store
2669397×
            .put_state(&StateObject::new(local_heads.clone()))?;
2670
        // A push that carries a policy re-attests the bookmark even when its
2671
        // state is unchanged, so the current attestation is always by a key
2672
        // the current policy authorizes (a revoked key's attestation would
2673
        // otherwise be refused by every later fetch).
2674397×
        if new_state == remote_state
267536×
            && policy_to_send.is_none()
267619×
            && tags_to_send.is_empty()
267710×
            && withdrawals_to_send.is_empty()
2678
        {
26799×
            return Ok(vec![RefResult {
26809×
                name: bookmark,
26819×
                ok: true,
26829×
                reason: "already up to date".into(),
26839×
            }]);
2684388×
        }
2685
        // A shallow repository knows the changes on its boundary without
2686
        // holding them: a depth-0 clone's are the heads it cloned (#137).
2687388×
        let boundary = self.boundary();
2688388×
        for h in &remote_heads {
2689384×
            if !self.store.has(h) && !boundary.contains(h) {
269067×
                return fail(format!(
2691
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
269267×
                    h.short(12)
2693
                ));
2694317×
            }
2695
        }
2696321×
        if !force {
2697321×
            let closure = self.closure_in_store(&local_heads)?;
2698321×
            if let Some(h) = remote_heads
2699321×
                .iter()
2700321×
                .find(|h| !closure.contains(h) && !boundary.contains(h))
2701
            {
27020×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2703321×
            }
27040×
        }
2705321×
        let to_send = self.negotiate(&self.remote_holds(&refs, &remote_heads), &local_heads)?;
2706321×
        let key = self.secret_key()?.map(|(k, _)| k);
2707321×
        if let Some(key) = key {
2708
            // Seal this author's changes that carry no valid authenticator,
2709
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2710
            // are stored, so each batch's bundle carries those it needs.
2711112×
            let mut unsigned = Vec::new();
2712112×
            for h in &to_send {
271382×
                let c = self.store.get_change_meta(h)?;
271482×
                if self.seals_for_author(&c.author, &key)
271580×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
271653×
                {
271753×
                    unsigned.push(*h);
271853×
                }
2719
            }
2720112×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
272150×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2722
            }
2723209×
        }
2724
        // A long history goes in batches, in dependency order, so neither
2725
        // side holds it whole and no request passes the remote's limit:
2726
        // all but the last carry objects alone; the last moves the bookmark
2727
        // (oxygen#95).
2728320×
        let batches = self.push_batches(&to_send)?;
2729320×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2730320×
        for (i, batch) in earlier.iter().enumerate() {
27315×
            progress(&format!(
27325×
                "part {} of {}: {} changes",
27335×
                i + 1,
27345×
                batches.len(),
27355×
                batch.len()
27365×
            ));
27375×
            let bundle = self.send_objects_ahead(
27385×
                remote.as_ref(),
27395×
                remote_name,
27405×
                self.bundle_for(batch)?,
27415×
                &mut *progress,
27420×
            )?;
27435×
            let results = remote.push(bundle, vec![], None, vec![])?;
27445×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
27455×
                Some(r) if r.ok => {}
27460×
                Some(r) => {
27470×
                    return fail(format!(
2748
                        "{remote_name} refused part {} of the push: {}",
27490×
                        i + 1,
2750
                        r.reason
2751
                    ))
2752
                }
2753
                None => {
27540×
                    return fail(format!(
2755
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2756
                    ))
2757
                }
2758
            }
2759
        }
2760320×
        if batches.len() > 1 {
27611×
            progress(&format!(
27621×
                "part {} of {}: {} changes",
27631×
                batches.len(),
27641×
                batches.len(),
27651×
                last.len()
27661×
            ));
2767319×
        }
2768320×
        let mut bundle = self.send_objects_ahead(
2769320×
            remote.as_ref(),
2770320×
            remote_name,
2771320×
            self.bundle_for(last)?,
2772320×
            &mut *progress,
27730×
        )?;
2774320×
        bundle.objects.push((
2775320×
            ObjectType::State,
2776320×
            StateObject::new(local_heads.clone()).encode(),
2777320×
        ));
2778320×
        let attestation = match key {
2779111×
            Some(_) => Some(self.sign_attest(&Attest {
2780111×
                repo: self.id()?,
2781111×
                hlc: Hlc::now(),
2782111×
                body: AttestBody::Ref {
2783111×
                    name: bookmark.clone(),
2784111×
                    old_state: remote_state,
2785111×
                    new_state,
2786111×
                    serial: next_serial(last_serial),
2787111×
                },
27881×
            })?),
2789209×
            None => None,
2790
        };
2791
        // Whoever signed the move, and whom a delegate acts for, travel with
2792
        // it: a receiver that has never seen a change by this delegate could
2793
        // not otherwise check its signature (oxygenhub#129).
2794319×
        if attestation.is_some() {
2795220×
            for k in [self.signing_key(), self.config.author_key]
2796110×
                .into_iter()
2797110×
                .flatten()
2798
            {
2799220×
                if let Ok(id) = self.identity(&k) {
2800220×
                    let body = id.encode();
2801220×
                    if !bundle
2802220×
                        .objects
2803220×
                        .iter()
2804267×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
280538×
                    {
280638×
                        bundle.objects.push((ObjectType::Identity, body));
2807182×
                    }
28080×
                }
2809
            }
2810
            // A short-lived signing key's certificate goes with it (§14.7).
2811110×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2812110×
            self.attach_certificates_for(&mut bundle, &signers)?;
2813209×
        }
2814319×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2815110×
            AttestBody::Ref { serial, .. } => Some(serial),
28160×
            _ => None,
2817110×
        });
2818319×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2819
        // Tag states must be present on the remote: bundle their changes too.
2820319×
        for t in &tags_to_send {
282116×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
282216×
            let extra: Vec<ChangeHash> =
282316×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
282416×
            if !extra.is_empty() {
28250×
                let more = self.bundle_for(&extra)?;
28260×
                bundle.changes.extend(more.changes);
28270×
                bundle.hashes.extend(more.hashes);
28280×
                bundle.attests.extend(more.attests);
28290×
                bundle.objects.extend(more.objects);
283016×
            }
283116×
            bundle.objects.push((
283216×
                ObjectType::State,
283316×
                StateObject::new(t.heads.clone()).encode(),
283416×
            ));
2835
        }
2836
        // A tag's signer travels with it, as the bookmark's does: a tag made
2837
        // by `oxy tag create` under a short-lived key was signed by a key the
2838
        // receiver has never seen, so its identity and certificate go too.
2839319×
        let tag_signers: Vec<KeyId> = tags_to_send
2840319×
            .iter()
2841319×
            .chain(&withdrawals_to_send)
2842319×
            .filter_map(|t| t.attestation.as_ref())
2843319×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2844319×
            .collect();
2845319×
        for k in &tag_signers {
284616×
            if let Ok(id) = self.identity(k) {
284716×
                let body = id.encode();
284816×
                if !bundle
284916×
                    .objects
285016×
                    .iter()
285130×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
28522×
                {
28532×
                    bundle.objects.push((ObjectType::Identity, body));
285414×
                }
28550×
            }
2856
        }
2857319×
        if !tag_signers.is_empty() {
285815×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2859304×
        }
2860319×
        if let Some(l) = &policy_to_send {
286134×
            let remote_serial = resp_policy_serial;
286234×
            bundle.policies = self
286334×
                .policy_history()?
286434×
                .into_iter()
286566×
                .filter(|sp| {
286666×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
286736×
                        && sp.policy.serial < l.policy.serial
286866×
                })
286934×
                .collect();
2870285×
        }
2871319×
        let results = remote.push(
2872319×
            bundle,
2873319×
            vec![RefUpdate {
2874319×
                name: bookmark.clone(),
2875319×
                old_state: remote_state,
2876319×
                new_state,
2877319×
                force,
2878319×
                attestation,
2879319×
            }],
2880319×
            policy_to_send,
2881319×
            tags_to_send
2882319×
                .into_iter()
2883319×
                .chain(withdrawals_to_send)
2884319×
                .collect(),
28858×
        )?;
288634×
        if let (Some(serial), true) = (
2887311×
            sent_serial,
2888325×
            results.iter().any(|r| r.ok && r.name == "policy"),
2889
        ) {
289034×
            self.record_policy_serial(remote_name, serial)?;
2891277×
        }
2892348×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2893288×
            let mut view = op.view.clone();
2894288×
            view.remotes
2895288×
                .entry(remote_name.to_string())
2896288×
                .or_default()
2897288×
                .insert(bookmark.clone(), new_state);
2898288×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2899285×
            if let Some(s) = serial {
290086×
                self.record_serial(remote_name, &bookmark, s)?;
2901199×
            }
290223×
        }
2903306×
        Ok(results)
2904403×
    }
2905
2906
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2907
    /// bookmark set to the remote's, working copy checked out.
2908263×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2909263×
        Self::clone_with(url, dest, None, &[])
2910263×
    }
2911
2912
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2913
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2914
    /// unless a size is given, so out-of-scope binaries are never fetched).
2915266×
    pub fn clone_with(
2916266×
        url: &str,
2917266×
        dest: &Path,
2918266×
        max_blob: Option<u64>,
2919266×
        sparse: &[String],
2920266×
    ) -> Result<Repo> {
2921266×
        Self::clone_full(url, dest, max_blob, sparse, None)
2922266×
    }
2923
2924
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2925
    /// changes within `depth` steps of them; the rest is the boundary.
29263×
    pub fn clone_shallow(
29273×
        url: &str,
29283×
        dest: &Path,
29293×
        depth: u32,
29303×
        max_blob: Option<u64>,
29313×
        sparse: &[String],
29323×
    ) -> Result<Repo> {
29333×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
29343×
    }
2935
2936269×
    fn clone_full(
2937269×
        url: &str,
2938269×
        dest: &Path,
2939269×
        max_blob: Option<u64>,
2940269×
        sparse: &[String],
2941269×
        depth: Option<u32>,
2942269×
    ) -> Result<Repo> {
2943269×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2944269×
    }
2945
2946
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2947
    /// `depth`), also returning the bookmarks the fetch left out because
2948
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2949
    /// for the caller to warn about. The bookmark checked out is never one
2950
    /// of them: that fails the clone.
2951275×
    pub fn clone_reporting(
2952275×
        url: &str,
2953275×
        dest: &Path,
2954275×
        max_blob: Option<u64>,
2955275×
        sparse: &[String],
2956275×
        depth: Option<u32>,
2957275×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2958275×
        let options = crate::credentials::Credentials::user().options_for(url);
2959275×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2960275×
    }
2961
2962
    /// Clone a subrepo with the credentials the parent would use for its
2963
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2964
    /// subrepo: it finds the same ones again through its parent.
296512×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
296612×
        let options = self.credentials_for(url);
296712×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
296812×
    }
2969
2970
    /// The name of a remote of this repository on the same hub (scheme,
2971
    /// host and port) as `url`.
297227×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
297331×
        let origin = |u: &str| -> Option<String> {
297431×
            let (scheme, rest) = u.split_once("://")?;
29758×
            if !matches!(scheme, "http" | "https") {
29760×
                return None;
29778×
            }
29788×
            let host = rest.split('/').next()?;
29798×
            Some(format!(
29808×
                "{}://{}",
29818×
                scheme.to_ascii_lowercase(),
29828×
                host.to_ascii_lowercase()
29838×
            ))
298431×
        };
298527×
        let want = origin(url)?;
29864×
        self.config
29874×
            .remotes
29884×
            .iter()
29894×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
29904×
            .map(|(name, _)| name.clone())
299127×
    }
2992
2993
    /// The token and CA to reach `url` with: those of a remote of this
2994
    /// repository on the same hub (scheme, host and port), else the
2995
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2996
    /// and enclosing checkouts', as a clone would use them.
299727×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
299827×
        match self.remote_on_same_hub(url) {
29991×
            Some(name) => RemoteOptions {
30001×
                repo_id: None,
30011×
                cache_dir: None,
30021×
                ..self.remote_options(&name)
30031×
            },
3004
            None => {
300526×
                let mut options = RemoteOptions::default();
300626×
                self.fill_credentials(url, &mut options);
300726×
                options
3008
            }
3009
        }
301027×
    }
3011
3012287×
    fn clone_using(
3013287×
        url: &str,
3014287×
        dest: &Path,
3015287×
        max_blob: Option<u64>,
3016287×
        sparse: &[String],
3017287×
        depth: Option<u32>,
3018287×
        options: &RemoteOptions,
3019287×
    ) -> Result<(Repo, Vec<(String, String)>)> {
3020287×
        let remote = open_remote(url, options)?;
3021287×
        let id = remote.repo_id()?;
3022283×
        if id == crate::protocol::UNBOUND_ID {
30232×
            return fail(format!(
3024
                "{url} is empty and unbound: push a repository to it first"
3025
            ));
3026281×
        }
3027281×
        let mut repo = Repo::init_with_id(dest, id)?;
3028281×
        repo.config
3029281×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
3030281×
        if let Some(m) = max_blob {
30313×
            repo.config.set("filter.max-blob", &m.to_string())?;
3032278×
        } else if !sparse.is_empty() {
30331×
            repo.config.set("filter.max-blob", "0")?;
3034277×
        }
3035281×
        if !sparse.is_empty() {
30361×
            repo.config.set("filter.paths", &sparse.join(","))?;
3037280×
        }
3038281×
        repo.save_config()?;
3039281×
        let skipped = if let Some(depth) = depth {
30403×
            repo.fetch_shallow("origin", depth)?;
30413×
            Vec::new()
3042
        } else {
3043278×
            repo.fetch("origin")?.skipped
3044
        };
3045279×
        let (op_ref, op) = repo.head_op()?;
3046
        // The remote's default bookmark, else ours (main), else its only
3047
        // one; a bookmark the fetch skipped counts, so the clone fails
3048
        // rather than check out another (oxygenhub#266).
3049279×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
3050279×
        for (name, _) in &skipped {
30513×
            theirs.insert(name.clone(), ObjectRef::ZERO);
30523×
        }
3053
        // Asked of the remote as now configured, so a store-backed one
3054
        // answers from the mirror the fetch just filled.
3055279×
        let advertised = repo
3056279×
            .open_named_remote("origin")
3057279×
            .ok()
3058279×
            .and_then(|r| r.refs().ok())
3059279×
            .and_then(|r| r.default_bookmark);
3060279×
        let bookmark = advertised
3061279×
            .filter(|b| theirs.contains_key(b))
3062279×
            .or_else(|| {
30637×
                theirs
30647×
                    .contains_key(&repo.config.bookmark)
30657×
                    .then(|| repo.config.bookmark.clone())
30667×
            })
3067279×
            .or_else(|| {
30680×
                (theirs.len() == 1)
30690×
                    .then(|| theirs.keys().next().cloned())
30700×
                    .flatten()
30710×
            })
3072279×
            .unwrap_or_else(|| repo.config.bookmark.clone());
3073279×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
30740×
            return fail(format!("cannot check out {bookmark}: {why}"));
3075279×
        }
3076279×
        let initial = repo.config.bookmark.clone();
3077279×
        if bookmark != repo.config.bookmark {
30781×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
30791×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
30801×
            repo.config.bookmark = bookmark.clone();
3081278×
        }
3082279×
        if let Some(state) = theirs.get(&bookmark).copied() {
3083279×
            let heads = repo.store.get_state(&state)?.heads;
3084279×
            let mut view = op.view.clone();
3085
            // The empty bookmark `init` made goes when another is checked out.
3086279×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
30871×
                view.bookmarks.remove(&initial);
3088278×
            }
3089279×
            view.bookmarks.insert(bookmark, state);
3090279×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
3091279×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
30920×
        }
3093279×
        Ok((repo, skipped))
3094287×
    }
3095
}
3096
3097
/// The serial of a reference's next attestation: one more than the last the
3098
/// remote reports, or, for a bookmark the remote does not have, the clock in
3099
/// milliseconds, so a bookmark created again after a deletion goes past the
3100
/// deletion's serial the remote keeps.
3101111×
fn next_serial(last: Option<u64>) -> u64 {
3102111×
    match last {
310369×
        Some(l) => l + 1,
310442×
        None => Hlc::now().wall_ms.max(1),
3105
    }
3106111×
}