OXYGENHUB

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

1859 of 2069 lines run, 276 of 398 functions · run #359 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
    /// What checking the host's transparency log found short of a fork
34
    /// (spec §14.8): attestations not logged yet, a log that could not be
35
    /// read. A fork fails the fetch instead.
36
    pub log_notes: Vec<String>,
37
    /// Bookmarks left as they were because their attestation could not be
38
    /// verified (its signer unknown here, or its signature bad), each with
39
    /// why (oxygenhub#266). The current bookmark is never skipped: its
40
    /// fetch fails instead.
41
    pub skipped: Vec<(String, String)>,
42
}
43
44
#[derive(Debug, Clone, PartialEq, Eq)]
45
pub struct PullReport {
46
    /// The current bookmark's heads after the pull.
47
    pub heads: Vec<ChangeHash>,
48
    /// Whether the current bookmark changed.
49
    pub changed: bool,
50
    pub checked_out: bool,
51
    /// Other bookmarks the pull moved: each local bookmark tracks the
52
    /// remote's of the same name.
53
    pub others: Vec<String>,
54
    /// What the fetch left as it was ([`FetchReport::skipped`]).
55
    pub skipped: Vec<(String, String)>,
56
}
57
58
/// The result a push of objects alone reports (a batch of a long history):
59
/// not a reference.
60
pub const OBJECTS_RESULT: &str = "objects";
61
62
impl Repo {
63
    // ------------------------------------------------------------ serving (spec §16)
64
651751×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
661751×
        self.oxy.join("attest").join(name_file(bookmark))
671751×
    }
68
69
    /// The latest reference attestation stored for a bookmark.
701359×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
711359×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
72292×
            Ok(h) => {
73292×
                let r = ObjectRef::from_hex(h.trim())
74292×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
75
                Ok(Some((
76292×
                    r,
77
                    SignedAttest {
78292×
                        attest: self.store.get_attest(&r)?,
79292×
                        sigs: self.store.signatures(&r)?,
80
                    },
81
                )))
82
            }
831067×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
840×
            Err(e) => Err(e.into()),
85
        }
861359×
    }
87
8897×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
8997×
        fs::create_dir_all(self.oxy.join("attest"))?;
9097×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
9197×
    }
92
931083×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
941083×
        let view = self.view()?;
951083×
        let mut out = Vec::new();
961136×
        for (name, state) in &view.bookmarks {
971136×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
981136×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
99186×
                AttestBody::Ref { serial, .. } => Some(serial),
1000×
                _ => None,
101186×
            });
1021136×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1031136×
            let accepted = match &attestation {
104175×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
105961×
                None => None,
106
            };
1071136×
            out.push(RemoteRef {
1081136×
                name: name.clone(),
1091136×
                state: *state,
1101136×
                heads: self.store.get_state(state)?.heads,
1111136×
                attestation,
1121136×
                last_serial,
1131136×
                accepted,
1141136×
                logged: None,
1151136×
                integration: vec![],
116
            });
117
        }
1181083×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1191083×
        let history = self
1201083×
            .policy_history()?
1211083×
            .into_iter()
1221083×
            .filter(|sp| {
123146×
                policy
124146×
                    .as_ref()
125146×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
126146×
            })
1271083×
            .collect();
128
        Ok(RefsResponse {
1291083×
            refs: out,
1301083×
            policy,
1311083×
            tags: self.tag_refs()?,
1321083×
            history,
1331083×
            default_bookmark: Some(self.config.bookmark.clone()),
1341083×
            log: None,
1351083×
            witnesses: vec![],
136
        })
1371083×
    }
138
139
    /// Every change reachable from `heads` that is in the store.
1401457×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1411457×
        let mut seen = BTreeSet::new();
1421457×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1434953×
        while let Some(h) = stack.pop() {
1443496×
            if seen.contains(&h) || !self.store.has(&h) {
1451039×
                continue;
1462457×
            }
1472457×
            seen.insert(h);
1482457×
            stack.extend(self.store.get_change_meta(&h)?.deps);
149
        }
1501457×
        Ok(seen)
1511457×
    }
152
153
    /// The changes within `depth` dependency steps of `heads` (spec §17),
154
    /// nearest first; depth 1 is the heads themselves.
1553×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1563×
        let mut out = Vec::new();
1573×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1583×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1593×
        for _ in 0..depth.max(1) {
1608×
            let mut next = Vec::new();
16112×
            for h in layer {
16212×
                if !seen.insert(h) || !self.store.has(&h) {
1632×
                    continue;
16410×
                }
16510×
                let c = self.store.get_change(&h)?;
16610×
                next.extend(c.deps.iter().copied());
16710×
                out.push(h);
168
            }
1698×
            if next.is_empty() {
1701×
                break;
1717×
            }
1727×
            layer = next;
173
        }
1743×
        out.reverse();
1753×
        Ok(out)
1763×
    }
177
1782086×
    fn shallow_path(&self) -> PathBuf {
1792086×
        self.oxy.join("shallow")
1802086×
    }
181
182
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1832083×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1842083×
        fs::read_to_string(self.shallow_path())
1852083×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1862083×
            .unwrap_or_default()
1872083×
    }
188
189190×
    pub fn is_shallow(&self) -> bool {
190190×
        !self.boundary().is_empty()
191190×
    }
192
1933×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1943×
        if boundary.is_empty() {
1951×
            let _ = fs::remove_file(self.shallow_path());
1961×
            return Ok(());
1972×
        }
1982×
        let text: String = boundary
1992×
            .iter()
2002×
            .map(|h| format!("{}\n", h.to_hex()))
2012×
            .collect();
2022×
        write_atomic(&self.shallow_path(), text.as_bytes())
2033×
    }
204
205
    /// Recompute the boundary from what is stored: every dependency of a
206
    /// stored change that is not itself stored.
2073×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2083×
        let mut boundary = self.boundary();
2093×
        boundary.retain(|h| !self.store.has(h));
21010×
        for h in imported {
21113×
            for d in self.store.get_change_meta(h)?.deps {
21213×
                if !self.store.has(&d) {
2132×
                    boundary.insert(d);
21411×
                }
215
            }
216
        }
2173×
        self.write_boundary(&boundary)
2183×
    }
219
220
    /// Fetch `depth` more levels of history below the shallow boundary.
2212×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2222×
        let boundary = self.boundary();
2232×
        if boundary.is_empty() {
2240×
            return Ok(0);
2252×
        }
2262×
        let remote = self.open_named_remote(remote_name)?;
2272×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2282×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2292×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2302×
        if self.config.max_blob.is_some() {
2310×
            self.register_missing_blobs(&imported, remote_name)?;
2322×
        }
2332×
        self.refresh_boundary(&imported)?;
2342×
        Ok(imported.len())
2352×
    }
236
237
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
238842×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
239842×
        let have = self.closure_in_store(have)?;
240
        // In a shallow repository the walk stops at the boundary, whose
241
        // changes the remote is assumed to hold.
242842×
        let boundary = self.boundary();
243842×
        let mut out = Vec::new();
244842×
        let mut done: BTreeSet<ChangeHash> = have.clone();
245842×
        done.extend(boundary.iter().copied());
246
        // Iterative post-order DFS.
2471308×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2483481×
        while let Some((h, expanded)) = stack.pop() {
2492639×
            if done.contains(&h) {
250423×
                continue;
2512216×
            }
2522216×
            if !self.store.has(&h) {
2530×
                return fail(format!("change {} is not in this repository", h.short(12)));
2542216×
            }
2552216×
            if expanded {
2561108×
                done.insert(h);
2571108×
                out.push(h);
2581108×
                continue;
2591108×
            }
2601108×
            stack.push((h, true));
2611108×
            for d in self.store.get_change_meta(&h)?.deps {
262740×
                if !done.contains(&d) {
263223×
                    stack.push((d, false));
264517×
                }
265
            }
266
        }
267842×
        Ok(out)
268842×
    }
269
270
    /// Bundle changes (in the given dependency order) with their signatures,
271
    /// seals, identities, blobs, chunks.
272324×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
273324×
        self.bundle_of(changes, None, false, false)
274324×
    }
275
276
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2774×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2784×
        let mut out = Vec::new();
2794×
        for r in refs {
2804×
            let (ty, body) = match self.store.get(r) {
2814×
                Ok(x) => x,
2820×
                Err(StoreError::NotFound(_)) => continue,
2830×
                Err(e) => return Err(e.into()),
284
            };
2854×
            if ty == ObjectType::Blob {
2865×
                for c in Blob::decode(&body)?.chunks {
2875×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2885×
                        out.push((cty, cb));
2895×
                    }
290
                }
2910×
            }
2924×
            out.push((ty, body));
293
        }
2944×
        Ok(out)
2954×
    }
296
297
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
298
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
299
    ///
300
    /// This is what a server answers a fetch with, so it also carries what
301
    /// verifies the attestations it serves beside it (see
302
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
30349×
    pub fn bundle_for_filtered(
30449×
        &self,
30549×
        changes: &[ChangeHash],
30649×
        max_blob: Option<u64>,
30749×
    ) -> Result<Bundle> {
30849×
        self.bundle_of(changes, max_blob, false, true)
30949×
    }
310
311
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
312
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
313
    /// with their text blobs and chunks among the objects, so neither side
314
    /// decodes or encodes their text.
315371×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
316371×
        self.bundle_of(changes, max_blob, true, true)
317371×
    }
318
319
    /// The keys that signed the attestations this repository serves with
320
    /// its references: each bookmark's latest and each tag's. A fetch
321
    /// bundle carries their identities and certificates (spec §16.2), so a
322
    /// client can check an attestation whose signer signed none of the
323
    /// changes it receives, a delegate or a short-lived key that only
324
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
325
    /// list per reference, computed once per operation head and kept
326
    /// (every bookmark move and tag is an operation): a client sends one
327
    /// fetch per bookmark, and on a bucket store each signature list is a
328
    /// LIST request, so recomputing per fetch cost metalgear2 (145
329
    /// bookmarks) 14 s a fetch.
330420×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
331
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
332
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
333420×
        let key = (self.oxy.clone(), self.head_op()?.0);
334420×
        if let Some(keys) = SERVED
335420×
            .lock()
336420×
            .unwrap_or_else(|p| p.into_inner())
337420×
            .as_ref()
338420×
            .and_then(|m| m.get(&key))
339
        {
340135×
            return Ok(keys.clone());
341285×
        }
342285×
        let keys = self.attest_signers_now()?;
343285×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
344285×
        let map = served.get_or_insert_with(Default::default);
345
        // One entry per repository: an older operation head is never asked
346
        // for again once a newer one is current.
3475700×
        map.retain(|(oxy, _), _| *oxy != key.0);
348285×
        if map.len() >= 1024 {
3490×
            map.clear();
350285×
        }
351285×
        map.insert(key, keys.clone());
352285×
        Ok(keys)
353420×
    }
354
355285×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
356285×
        let view = self.view()?;
357285×
        let pointers = view
358285×
            .bookmarks
359285×
            .keys()
360295×
            .map(|b| self.ref_attest_path(b))
361285×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
362285×
        let mut keys = BTreeSet::new();
363308×
        for p in pointers {
364308×
            let Ok(text) = fs::read_to_string(&p) else {
365262×
                continue;
366
            };
36746×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3680×
                continue;
369
            };
37046×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
371
        }
372285×
        Ok(keys)
373285×
    }
374
375
    /// `serving`: a fetch's answer, which carries the identities and
376
    /// certificates of [`Repo::served_attest_signers`] too.
377744×
    fn bundle_of(
378744×
        &self,
379744×
        changes: &[ChangeHash],
380744×
        max_blob: Option<u64>,
381744×
        raw: bool,
382744×
        serving: bool,
383744×
    ) -> Result<Bundle> {
384744×
        let mut bundle = Bundle::default();
385744×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
386744×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3871252×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3881252×
            if !r.is_zero() && self.store.has(r) {
389334×
                objects.insert(*r);
390918×
            }
3911252×
        };
3921029×
        for h in changes {
393
            // Raw: the stored bytes, and a skeleton for the rest.
3941029×
            let (c, encoded) = if raw {
395560×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
396560×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3975069×
                for t in texts {
3985069×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3993×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4003×
                        objects.insert(r);
4013×
                        objects.extend(blob.chunks);
4025066×
                    }
403
                }
404560×
                (skel, Some(bytes))
405
            } else {
406469×
                (self.store.get_change(h)?, None)
407
            };
4081029×
            let sigs = self.store.signatures(h)?;
4091029×
            add_object(&c.author, &mut objects);
4101029×
            for s in &sigs {
41137×
                add_object(&s.key, &mut objects);
41237×
            }
4136061×
            for e in &c.edits {
4146061×
                if let Edit::Replace { old, new, .. } = e {
41514×
                    for b in [old, new].into_iter().flatten() {
41614×
                        if self.store.has(b) {
41714×
                            if let Ok(blob) =
41814×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
419
                            {
42014×
                                if max_blob.is_some_and(|m| blob.length > m) {
4214×
                                    continue;
42210×
                                }
42310×
                                objects.insert(*b);
42410×
                                objects.extend(blob.chunks.iter().copied());
4250×
                            }
4260×
                        }
427
                    }
4286049×
                }
429
            }
4301029×
            for s in self.store.seals_for(h)? {
43195×
                seals.insert(s);
43295×
            }
4331029×
            match encoded {
434560×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
435469×
                None => {
436469×
                    bundle.changes.push((c, sigs));
437469×
                    bundle.hashes.push(*h);
438469×
                }
439
            }
440
        }
441744×
        for r in seals {
44290×
            let attest = self.store.get_attest(&r)?;
44390×
            let sigs = self.store.signatures(&r)?;
44490×
            for s in &sigs {
44590×
                add_object(&s.key, &mut objects);
44690×
            }
44790×
            bundle.attests.push(SignedAttest { attest, sigs });
448
        }
449744×
        let signers: Vec<KeyId> = if serving {
450420×
            let signers = self.served_attest_signers()?;
451420×
            for k in &signers {
45296×
                add_object(k, &mut objects);
45396×
            }
454420×
            signers.into_iter().collect()
455
        } else {
456324×
            Vec::new()
457
        };
458744×
        for r in objects {
459197×
            let (ty, body) = self.store.get(&r)?;
460197×
            bundle.objects.push((ty, body));
461
        }
462744×
        self.attach_certificates_for(&mut bundle, &signers)?;
463744×
        Ok(bundle)
464744×
    }
465
466
    /// Add the certificates of short-lived keys that signed what `bundle`
467
    /// carries, and their issuers' identities, so a receiver can tell who
468
    /// they stand for (spec §14.7). `also` names more signers (a reference
469
    /// attestation sent beside the bundle).
470839×
    pub(crate) fn attach_certificates_for(
471839×
        &self,
472839×
        bundle: &mut Bundle,
473839×
        also: &[KeyId],
474839×
    ) -> Result<()> {
475839×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
476839×
        keys.extend(
477839×
            bundle
478839×
                .changes
479839×
                .iter()
480839×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
481
        );
482839×
        keys.extend(
483839×
            bundle
484839×
                .raw_changes
485839×
                .iter()
486839×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
487
        );
488839×
        keys.extend(
489839×
            bundle
490839×
                .attests
491839×
                .iter()
492839×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
493
        );
494839×
        for k in keys {
495289×
            let Some(r) = self.store.certificate_of(&k)? else {
496263×
                continue;
497
            };
49826×
            let cert = self.store.get_certificate(&r)?;
49926×
            if bundle
50026×
                .certificates
50126×
                .iter()
50226×
                .any(|c| c.cert.hash() == cert.cert.hash())
503
            {
5047×
                continue;
50519×
            }
50638×
            for id in [&k, &cert.cert.issuer] {
50738×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
50838×
                    if !bundle
50938×
                        .objects
51038×
                        .iter()
51160×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
51219×
                    {
51319×
                        bundle.objects.push((ObjectType::Identity, body));
51419×
                    }
5150×
                }
516
            }
51719×
            bundle.certificates.push(cert);
518
        }
519839×
        Ok(())
520839×
    }
521
522
    /// Keep the certificates a bundle brings once each verifies with the
523
    /// identity of the issuer it names; one that does not refuses the bundle.
524785×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
525785×
        for c in certs {
52618×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5270×
                RepoError::Msg(format!(
5280×
                    "a certificate names issuer {}, whose identity did not come with it",
5290×
                    c.cert.issuer.short(12)
5300×
                ))
5310×
            })?;
53218×
            c.verify(&issuer)
53318×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
53418×
            self.store.put_identity(&c.cert.key)?;
53518×
            self.store.put_certificate(c)?;
536
        }
537785×
        Ok(())
538785×
    }
539
540
    /// A signer authorized for `reference` by what an issuer certified it
541
    /// as (spec §14.7): a short-lived key with a kept certificate that
542
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
543
    /// signer did not choose) and names a subject the policy grants.
54429×
    pub(crate) fn certified_authorized(
54529×
        &self,
54629×
        p: &crate::policy::Policy,
54729×
        signer: &KeyId,
54829×
        reference: &str,
54929×
        scope: Scope,
55029×
        at_ms: u64,
55129×
    ) -> bool {
55229×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5535×
            return false;
554
        };
55524×
        let Ok(c) = self.store.get_certificate(&r) else {
5560×
            return false;
557
        };
55824×
        let Some(issuer) = p
55924×
            .identity(&c.cert.issuer)
56024×
            .cloned()
56124×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
562
        else {
5630×
            return false;
564
        };
56524×
        c.verify(&issuer).is_ok()
56624×
            && c.cert.key_id() == *signer
56724×
            && c.cert.covers(scope, at_ms)
56820×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
56929×
    }
570
571
    /// Store a bundle's contents. With `strict`, every change must
572
    /// authenticate (signature or seal by its author or a delegate).
573782×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
574782×
        self.import_bundle_inner(bundle, strict, false)
575782×
    }
576
577
    /// Like `import_bundle`, accepting changes whose dependencies are absent
578
    /// (they join the shallow boundary).
5793×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5803×
        self.import_bundle_inner(bundle, strict, true)
5813×
    }
582
583785×
    fn import_bundle_inner(
584785×
        &self,
585785×
        bundle: &Bundle,
586785×
        strict: bool,
587785×
        shallow: bool,
588785×
    ) -> Result<Vec<ChangeHash>> {
589785×
        let batch = self.store.begin_batch()?;
590785×
        let result = self.import_bundle_batched(bundle, strict, shallow);
591785×
        batch.finish()?;
592783×
        result
593785×
    }
594
595785×
    fn import_bundle_batched(
596785×
        &self,
597785×
        bundle: &Bundle,
598785×
        strict: bool,
599785×
        shallow: bool,
600785×
    ) -> Result<Vec<ChangeHash>> {
601785×
        for (ty, _) in &bundle.objects {
6020×
            if !matches!(
603611×
                ty,
604
                ObjectType::Chunk
605
                    | ObjectType::Blob
606
                    | ObjectType::Identity
607
                    | ObjectType::State
608
                    | ObjectType::Checkpoint
609
            ) {
6100×
                return fail(format!("bundle may not carry {} objects", ty.name()));
611611×
            }
612
        }
613
        // All at once: in a large batch they are compressed on every core.
614785×
        let objects: Vec<(ObjectType, &[u8])> = bundle
615785×
            .objects
616785×
            .iter()
617785×
            .map(|(ty, body)| (*ty, body.as_slice()))
618785×
            .collect();
619785×
        self.store.put_many(&objects)?;
620785×
        self.adopt_certificates(&bundle.certificates)?;
621785×
        for sa in &bundle.attests {
62293×
            let r = self.store.put_attest(&sa.attest)?;
62393×
            for sig in &sa.sigs {
62493×
                self.store.put_signature(&r, sig)?;
625
            }
62693×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
62798×
                for h in hashes {
62898×
                    self.store.index_seal(h, &r)?;
629
                }
6300×
            }
631
        }
632
        // Each change's hash: from the bundle when its maker knew it, else
633
        // worked out once (for a change adding a whole tree, hashing is
634
        // chunking all its text).
635785×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
636776×
            bundle.hashes.clone()
637
        } else {
6389×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
639
        };
640785×
        let raw_hashes: Vec<ChangeHash> = bundle
641785×
            .raw_changes
642785×
            .iter()
643785×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
644785×
            .collect();
645785×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
646785×
        let boundary = self.boundary();
647785×
        let mut imported = Vec::new();
648
        // Changes as stored: checked, then stored as they are, their text
649
        // blobs having come with the objects.
650785×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
651561×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
652561×
            for d in &skel.deps {
653403×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
654
                {
6550×
                    return fail(format!(
656
                        "change {} depends on {}, which is neither stored nor in the bundle",
6570×
                        h.short(12),
6580×
                        d.short(12)
659
                    ));
660403×
                }
661
            }
6625070×
            for t in texts {
6635070×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6644×
                    if !self.store.has(&r) {
6651×
                        return fail(format!(
666
                            "change {} came without its text blob {}",
6671×
                            h.short(12),
6681×
                            r.short(12)
669
                        ));
6703×
                    }
6715066×
                }
672
            }
673560×
            self.store.put(ObjectType::Change, bytes)?;
674560×
            for sig in sigs {
67513×
                self.store.put_signature(&h, sig)?;
676
            }
677560×
            imported.push(h);
678
        }
679784×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
680496×
            for d in &c.deps {
681291×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
682
                {
6833×
                    return fail(format!(
684
                        "change {} depends on {}, which is neither stored nor in the bundle",
6853×
                        h.short(12),
6863×
                        d.short(12)
687
                    ));
688288×
                }
689
            }
690493×
            let stored = self.store.put_change(c)?;
691493×
            if stored != h {
6920×
                return fail(format!(
693
                    "change {} is not the change the bundle names",
6940×
                    h.short(12)
695
                ));
696493×
            }
697493×
            for sig in sigs {
69833×
                self.store.put_signature(&h, sig)?;
699
            }
700493×
            imported.push(h);
701
        }
702781×
        if strict {
70349×
            for h in &imported {
70434×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7054×
                    return fail(format!(
706
                        "change {} is not authenticated by its author",
7074×
                        h.short(12)
708
                    ));
70930×
                }
710
            }
711732×
        }
712777×
        Ok(imported)
713785×
    }
714
715
    /// Verify a reference attestation against an update it claims to describe.
716
    /// `allow_equal` lets a client re-read the attestation it already has; a
717
    /// server receiving a push requires a strictly greater serial.
718
    /// A reference attestation signed by a delegate of an identity the
719
    /// rule lists is authorized as that identity (spec §14.5): the identity
720
    /// named the delegate with the `refs` scope, still in force at `at_ms`
721
    /// (the attestation's wall time), and the policy names the identity.
722
    /// Revoked keys authorize nothing either way.
72336×
    pub(crate) fn delegate_authorized(
72436×
        &self,
72536×
        p: &crate::policy::Policy,
72636×
        signer: &KeyId,
72736×
        reference: &str,
72836×
        at_ms: u64,
72936×
    ) -> bool {
73036×
        if p.is_revoked(signer) {
7311×
            return false;
73235×
        }
73335×
        let Some(rule) = p.rule_for(reference) else {
7340×
            return false;
735
        };
73636×
        rule.keys.iter().any(|k| {
73736×
            !p.is_revoked(k)
73836×
                && p.identity(k)
73936×
                    .cloned()
74036×
                    .or_else(|| self.store.get_identity(k).ok())
74136×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
74236×
        })
74336×
    }
744
745
    /// A lasting attestation (a tag) signed by a key the policy has since
746
    /// rotated away from (spec §14.2) is authorized as the key that
747
    /// succeeded it: a key the rule lists reaches the signer through
748
    /// `previous` links, and the attestation is dated (`at_ms`) before the
749
    /// signer's successor was made, so a superseded key makes nothing new.
750
    /// Revoked keys authorize nothing.
7516×
    pub(crate) fn predecessor_authorized(
7526×
        &self,
7536×
        p: &crate::policy::Policy,
7546×
        signer: &KeyId,
7556×
        reference: &str,
7566×
        at_ms: u64,
7576×
    ) -> bool {
7586×
        if p.is_revoked(signer) {
7590×
            return false;
7606×
        }
7616×
        let Some(rule) = p.rule_for(reference) else {
7620×
            return false;
763
        };
7647×
        let identity = |k: &KeyId| {
7657×
            p.identity(k)
7667×
                .cloned()
7677×
                .or_else(|| self.store.get_identity(k).ok())
7687×
        };
7696×
        rule.keys.iter().any(|k| {
7706×
            if p.is_revoked(k) {
7710×
                return false;
7726×
            }
7736×
            let mut cur = identity(k);
7746×
            for _ in 0..32 {
7757×
                let Some(id) = cur else {
7760×
                    return false;
777
                };
7781×
                match id.previous {
7796×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7801×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
7811×
                    _ => return false,
782
                }
783
            }
7840×
            false
7856×
        })
7866×
    }
787
78894×
    fn check_ref_attest(
78994×
        &self,
79094×
        sa: &SignedAttest,
79194×
        name: &str,
79294×
        old_state: &ObjectRef,
79394×
        new_state: &ObjectRef,
79494×
        last_serial: Option<u64>,
79594×
        allow_equal: bool,
79694×
    ) -> std::result::Result<u64, String> {
79792×
        let serial =
79894×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
79992×
        self.verify_attest_signature(sa)?;
80092×
        Ok(serial)
80194×
    }
802
803
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
804
    /// attestation describes this update of this repository with a serial
805
    /// past the last seen.
806152×
    fn check_ref_attest_body(
807152×
        &self,
808152×
        sa: &SignedAttest,
809152×
        name: &str,
810152×
        old_state: &ObjectRef,
811152×
        new_state: &ObjectRef,
812152×
        last_serial: Option<u64>,
813152×
        allow_equal: bool,
814152×
    ) -> std::result::Result<u64, String> {
815
        let AttestBody::Ref {
816152×
            name: n,
817152×
            old_state: o,
818152×
            new_state: nw,
819152×
            serial,
820152×
        } = &sa.attest.body
821
        else {
8220×
            return Err("attestation is not a ref attestation".into());
823
        };
824152×
        if n != name || o != old_state || nw != new_state {
8251×
            return Err("attestation does not describe this update".into());
826151×
        }
827151×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8280×
            return Err("attestation is for a different repository".into());
829151×
        }
830151×
        if let Some(last) = last_serial {
83180×
            if *serial < last || (*serial == last && !allow_equal) {
8321×
                return Err(format!(
8331×
                    "attestation serial {serial} is not greater than the last seen {last}"
8341×
                ));
83579×
            }
83671×
        }
837150×
        Ok(*serial)
838152×
    }
839
840
    /// An attestation's first signature verifies with its signer's
841
    /// identity, which must be stored here.
842150×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
843150×
        let r = sa.attest.hash();
844150×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
845150×
        let id = self
846150×
            .store
847150×
            .get_identity(&sig.key)
848150×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
849144×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
850150×
    }
851
852
    /// Accept a push (spec §16.4). Without a trust policy every repository
853
    /// is unverified, so unsigned changes and unattested updates are accepted;
854
    /// attestations that are present must still be valid. With a policy,
855
    /// every change and update is checked against it. A newer policy in the
856
    /// push is applied first when it is signed by the current roots.
857299×
    pub fn receive_push(
858299×
        &self,
859299×
        bundle: Bundle,
860299×
        updates: Vec<RefUpdate>,
861299×
        policy: Option<SignedPolicy>,
862299×
        tags: Vec<crate::protocol::TagRef>,
863299×
    ) -> Result<Vec<RefResult>> {
864299×
        Ok(self
865299×
            .receive_push_report(bundle, updates, policy, tags)?
866
            .results)
867299×
    }
868
869
    /// `receive_push` with what a host wants to log: each accepted
870
    /// reference's old and new state and heads, and the changes this push
871
    /// stored (hub spec §6.12).
872341×
    pub fn receive_push_report(
873341×
        &self,
874341×
        bundle: Bundle,
875341×
        updates: Vec<RefUpdate>,
876341×
        policy: Option<SignedPolicy>,
877341×
        tags: Vec<crate::protocol::TagRef>,
878341×
    ) -> Result<PushReport> {
879
        // Updates are checked against the head as it is now, not as this
880
        // handle first read it (oxygenhub#249): another push may have
881
        // landed since.
882341×
        self.refresh()?;
883341×
        let mut report = PushReport::default();
884341×
        let results = &mut report.results;
885341×
        if let Some(sp) = policy {
88629×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
88727×
                Ok(()) => {
88827×
                    results.push(RefResult {
88927×
                        name: "policy".into(),
89027×
                        ok: true,
89127×
                        reason: format!("serial {}", sp.policy.serial),
89227×
                    });
89327×
                }
8942×
                Err(e) => {
8952×
                    results.push(RefResult {
8962×
                        name: "policy".into(),
8972×
                        ok: false,
8982×
                        reason: e,
8992×
                    });
9002×
                    for u in updates {
9010×
                        results.push(RefResult {
9020×
                            name: u.name,
9030×
                            ok: false,
9040×
                            reason: "policy update was rejected".into(),
9050×
                        });
9060×
                    }
9072×
                    return Ok(report);
908
                }
909
            }
910312×
        }
911339×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
912
        // A push of objects alone (one batch of a long history, oxygen#95)
913
        // names no reference: its outcome is reported as `objects`.
914339×
        let objects_only = updates.is_empty() && tags.is_empty();
915339×
        match self.import_bundle(&bundle, policy.is_some()) {
916333×
            Ok(imported) => {
917333×
                if objects_only {
9187×
                    results.push(RefResult {
9197×
                        name: OBJECTS_RESULT.into(),
9207×
                        ok: true,
9217×
                        reason: format!("{} changes stored", imported.len()),
9227×
                    });
923326×
                }
924333×
                report.imported = imported;
925
            }
9266×
            Err(e) => {
9276×
                if objects_only {
9280×
                    results.push(RefResult {
9290×
                        name: OBJECTS_RESULT.into(),
9300×
                        ok: false,
9310×
                        reason: e.to_string(),
9320×
                    });
9336×
                }
9346×
                for u in updates {
9356×
                    results.push(RefResult {
9366×
                        name: u.name,
9376×
                        ok: false,
9386×
                        reason: e.to_string(),
9396×
                    });
9406×
                }
9416×
                return Ok(report);
942
            }
943
        }
944333×
        let (op_ref, op) = self.head_op()?;
945333×
        let mut view = op.view.clone();
946333×
        let mut names = Vec::new();
947333×
        for u in updates {
948324×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
949324×
            let (ok, reason) = match outcome {
950297×
                Ok(()) => (true, String::new()),
95127×
                Err(e) => (false, e),
952
            };
953324×
            if ok {
954297×
                names.push(u.name.clone());
955297×
                let heads = self
956297×
                    .store
957297×
                    .get_state(&u.new_state)
958297×
                    .map(|s| s.heads)
959297×
                    .unwrap_or_default();
960297×
                report.updated.push(RefUpdated {
961297×
                    name: u.name.clone(),
962297×
                    old_state: u.old_state,
963297×
                    new_state: u.new_state,
964297×
                    heads,
965297×
                });
96627×
            }
967324×
            results.push(RefResult {
968324×
                name: u.name,
969324×
                ok,
970324×
                reason,
971324×
            });
972
        }
973333×
        for t in &tags {
9748×
            let name = format!("tags/{}", t.name);
9758×
            let new = !view.tags.contains_key(&t.name);
9768×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
977
                Ok(()) => {
978
                    // A tag new here is an update too, so a hub can start
979
                    // its pipeline's tag jobs (oxygenflow#24); one it
980
                    // already had, sent again, is not.
9816×
                    if new {
9826×
                        report.updated.push(RefUpdated {
9836×
                            name: name.clone(),
9846×
                            old_state: ObjectRef::ZERO,
9856×
                            new_state: t.state,
9866×
                            heads: t.heads.clone(),
9876×
                        });
9886×
                    }
9896×
                    names.push(name.clone());
9906×
                    results.push(RefResult {
9916×
                        name,
9926×
                        ok: true,
9936×
                        reason: String::new(),
9946×
                    });
995
                }
9962×
                Err(e) => results.push(RefResult {
9972×
                    name,
9982×
                    ok: false,
9992×
                    reason: e,
10002×
                }),
1001
            }
1002
        }
1003333×
        if !names.is_empty() {
1004297×
            self.record_op(
1005297×
                &[op_ref],
1006297×
                &format!("push received: {}", names.join(" ")),
1007297×
                view,
10083×
            )?;
100936×
        }
1010330×
        Ok(report)
1011341×
    }
1012
1013
    /// Check an update's attestation against the latest one for its
1014
    /// reference and store it as the new latest. Failures say what was
1015
    /// being done, for which reference, so a refused push can be diagnosed
1016
    /// from its reason alone.
101794×
    fn record_update_attest(
101894×
        &self,
101994×
        u: &RefUpdate,
102094×
        sa: &SignedAttest,
102194×
    ) -> std::result::Result<(), String> {
102294×
        let name = &u.name;
102394×
        let last = self
102494×
            .latest_ref_attest(name)
102594×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
102694×
            .and_then(|(_, a)| match a.attest.body {
102757×
                AttestBody::Ref { serial, .. } => Some(serial),
10280×
                _ => None,
102957×
            });
103094×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
103192×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
103292×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
103391×
        for sig in &sa.sigs {
103491×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1035
        }
103691×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1037
        // Signed by a short-lived key: a host records when it accepted it.
103888×
        let certified = sa
103988×
            .sigs
104088×
            .first()
104188×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
104288×
        if certified {
10433×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
104485×
        }
104588×
        Ok(())
104694×
    }
1047
1048
    /// Record that this host accepted attestation `r` now, signed with its
1049
    /// acceptor key (spec §14.7); nothing without one.
10504×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
10514×
        let Some(acceptor) = &self.acceptor else {
10523×
            return Ok(());
1053
        };
10541×
        let (id, sk) = (&acceptor.0, &acceptor.1);
10551×
        let attest = Attest {
10561×
            repo: self.id()?,
10571×
            hlc: Hlc::now(),
10581×
            body: AttestBody::Accepted { attest: *r },
1059
        };
10601×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
10611×
        self.store.put_identity(id)?;
10621×
        let a = self.store.put_attest(&attest)?;
10631×
        self.store.put_signature(&a, &sig)?;
10641×
        self.store.index_add_pub("accepted", r, &a)?;
10651×
        Ok(())
10664×
    }
1067
1068
    /// The host's acceptance of attestation `r`, if one was recorded.
1069177×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1070177×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1071167×
            return Ok(None);
1072
        };
1073
        Ok(Some(SignedAttest {
107410×
            attest: self.store.get_attest(&a)?,
107510×
            sigs: self.store.signatures(&a)?,
1076
        }))
1077177×
    }
1078
1079
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1080
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1081
    /// signer's certificate and accepts `sa`; else the attestation's own
1082
    /// time, which the signer chose.
108322×
    pub(crate) fn certified_time(
108422×
        &self,
108522×
        signer: &KeyId,
108622×
        sa: &SignedAttest,
108722×
        accepted: Option<&SignedAttest>,
108822×
    ) -> u64 {
108922×
        let own = sa.attest.hlc.wall_ms;
109022×
        let Some(acc) = accepted else {
109116×
            return own;
1092
        };
10936×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
10940×
            return own;
1095
        };
10966×
        let Ok(cert) = self.store.get_certificate(&c) else {
10970×
            return own;
1098
        };
10996×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11000×
            return own;
1101
        };
11026×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
11031×
            return own;
1104
        };
11055×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
11060×
            return own;
1107
        };
11085×
        if *attest == sa.attest.hash()
11094×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1110
        {
11114×
            acc.attest.hlc.wall_ms
1112
        } else {
11131×
            own
1114
        }
111522×
    }
1116
1117
    /// A fetched bookmark's attestation by a signer the policy does not
1118
    /// list itself: a delegate or a short-lived key, whose authority
1119
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1120
    /// attestation's integrated time when the host's log gives one; else
1121
    /// as before, at the host's acceptance for a certified signer, when it
1122
    /// countersigned one, or at the attestation's own time, and said so
1123
    /// when the host keeps a log. Failing at the integrated time but not
1124
    /// as before is a note while logs are new; a large gap between the
1125
    /// claimed and the integrated time is a note.
1126
    #[allow(clippy::too_many_arguments)]
112718×
    pub(crate) fn authorize_in_time(
112818×
        &self,
112918×
        p: &crate::policy::Policy,
113018×
        remote_name: &str,
113118×
        r: &crate::protocol::RemoteRef,
113218×
        sa: &SignedAttest,
113318×
        signer: &KeyId,
113418×
        log: &super::transparency::LogCheck,
113518×
        notes: &mut Vec<String>,
113618×
    ) -> Result<()> {
1137
        use super::transparency::{gap_note, judge, Timed};
113818×
        let own = sa.attest.hlc.wall_ms;
113918×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
114018×
        let time = log.time_of(&r.name);
114120×
        let check = |t_delegate: u64, t_cert: u64| {
114220×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
114318×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
114420×
        };
114518×
        let before = if at != own {
11463×
            "the host's acceptance"
1147
        } else {
114815×
            "the time it claims"
1149
        };
115018×
        let what = format!("{remote_name}/{}", r.name);
115118×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1152
            Timed::Refused => {
11531×
                return fail(format!(
1154
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
11551×
                    signer.short(12)
1156
                ))
1157
            }
11583×
            Timed::Integrated => {}
11591×
            Timed::Disagrees => notes.push(format!(
1160
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
11611×
                signer.short(12),
11621×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1163
            )),
11641×
            Timed::Fallback if log.kept => notes.push(format!(
1165
                "{what}: {} checked at {before}, not at a witnessed time: {}",
11661×
                signer.short(12),
11671×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1168
            )),
116912×
            Timed::Fallback => {}
1170
        }
117117×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
11722×
            notes.push(format!("{what}'s attestation {n}"));
117315×
        }
117417×
        Ok(())
117518×
    }
1176
1177
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1178
    /// at `old_state`, is never the bookmark a non-bare repository has
1179
    /// checked out (a bare one's default is its host's to protect, see
1180
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1181
    /// an attestation by a key that may update it.
1182
    /// The deletion's attestation stays the bookmark's latest, so an older
1183
    /// one cannot be replayed to bring it back.
11843×
    fn apply_deletion(
11853×
        &self,
11863×
        view: &mut View,
11873×
        u: &RefUpdate,
11883×
        policy: Option<&crate::policy::Policy>,
11893×
    ) -> std::result::Result<(), String> {
11903×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
11910×
            return Err(format!("no bookmark {:?} to delete", u.name));
1192
        };
11933×
        if current != u.old_state {
11940×
            return Err("stale: the remote bookmark has moved; pull first".into());
11953×
        }
11963×
        if !self.is_bare() && u.name == self.config.bookmark {
11971×
            return Err(format!(
11981×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
11991×
                u.name
12001×
            ));
12012×
        }
12022×
        if let Some(p) = policy {
12030×
            let Some(sa) = &u.attestation else {
12040×
                return Err(format!(
12050×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12060×
                    u.name
12070×
                ));
1208
            };
12090×
            let signer = sa
12100×
                .sigs
12110×
                .first()
12120×
                .map(|s| s.key)
12130×
                .ok_or("attestation carries no signature")?;
1214
            // Received now: the receiver's own clock is the trusted time.
12150×
            let now = Hlc::now().wall_ms;
12160×
            if !p.authorizes(&signer, &u.name)
12170×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12180×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1219
            {
12200×
                return Err(format!(
12210×
                    "key {} may not delete {:?} under this repository's policy",
12220×
                    signer.short(12),
12230×
                    u.name
12240×
                ));
12250×
            }
12262×
        }
12272×
        if let Some(sa) = &u.attestation {
12281×
            self.record_update_attest(u, sa)?;
12291×
        }
12302×
        view.bookmarks.remove(&u.name);
12312×
        Ok(())
12323×
    }
1233
1234324×
    fn apply_update(
1235324×
        &self,
1236324×
        view: &mut View,
1237324×
        u: &RefUpdate,
1238324×
        policy: Option<&crate::policy::Policy>,
1239324×
    ) -> std::result::Result<(), String> {
1240324×
        if u.name == "policy" {
12410×
            return Err(
12420×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
12430×
            );
1244324×
        }
1245324×
        let empty = self
1246324×
            .store
1247324×
            .put_state(&StateObject::new(vec![]))
1248324×
            .map_err(|e| e.to_string())?;
1249324×
        if u.new_state.is_zero() {
12503×
            return self.apply_deletion(view, u, policy);
1251321×
        }
1252321×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1253321×
        if current != u.old_state {
125410×
            return Err("stale: the remote bookmark has moved; pull first".into());
1255311×
        }
1256311×
        let new_state = self
1257311×
            .store
1258311×
            .get_state(&u.new_state)
1259311×
            .map_err(|_| "new state object is missing".to_string())?;
1260585×
        for h in &new_state.heads {
1261585×
            if !self.store.has(h) {
12621×
                return Err(format!("head {} is missing", h.short(12)));
1263584×
            }
1264
        }
1265310×
        if !u.force {
1266309×
            let old_heads = self
1267309×
                .store
1268309×
                .get_state(&current)
1269309×
                .map_err(|e| e.to_string())?
1270
                .heads;
1271309×
            let closure = self
1272309×
                .closure_in_store(&new_state.heads)
1273309×
                .map_err(|e| e.to_string())?;
1274309×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
12751×
                return Err(format!(
12761×
                    "not a fast-forward: current head {} would be dropped (use --force)",
12771×
                    h.short(12)
12781×
                ));
1279308×
            }
12801×
        }
1281309×
        if let Some(p) = policy {
128244×
            let Some(sa) = &u.attestation else {
12831×
                return Err(format!(
12841×
                    "{:?} requires a signed reference attestation under this repository's policy",
12851×
                    u.name
12861×
                ));
1287
            };
128843×
            let signer = sa
128943×
                .sigs
129043×
                .first()
129143×
                .map(|s| s.key)
129243×
                .ok_or("attestation carries no signature")?;
1293
            // Received now: the receiver's own clock is the trusted time.
129443×
            let now = Hlc::now().wall_ms;
129543×
            if !p.authorizes(&signer, &u.name)
129613×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
129710×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1298
            {
12997×
                return Err(format!(
13007×
                    "key {} may not update {:?} under this repository's policy",
13017×
                    signer.short(12),
13027×
                    u.name
13037×
                ));
130436×
            }
130536×
            let old_heads = self
130636×
                .store
130736×
                .get_state(&current)
130836×
                .map_err(|e| e.to_string())?
1309
                .heads;
131036×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1311265×
        }
1312301×
        if let Some(sa) = &u.attestation {
131393×
            self.record_update_attest(u, sa)?;
1314208×
        }
1315295×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1316295×
        Ok(())
1317324×
    }
1318
1319
    // ------------------------------------------------------------ client side
1320
13211447×
    fn remote_url(&self, name: &str) -> Result<String> {
13221447×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13233×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13243×
            RepoError::Msg(match names.as_slice() {
13253×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
13261×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1327
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
13281×
                    names.join(", "),
13291×
                    names[0],
13301×
                    names[0]
1331
                ),
13320×
                _ => format!(
1333
                    "no remote named {name:?}; this repository has {}",
13340×
                    names.join(", ")
1335
                ),
1336
            })
13373×
        })
13381447×
    }
1339
1340
    /// Refuse a remote that is another repository. An **unbound** remote
1341
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1342
    /// for pushes, which bind it to this repository's id (spec §16.1).
1343790×
    fn check_remote_id(
1344790×
        &self,
1345790×
        remote: &dyn crate::protocol::Remote,
1346790×
        remote_name: &str,
1347790×
        allow_unbound: bool,
1348790×
    ) -> Result<()> {
1349790×
        let theirs = remote.repo_id()?;
1350789×
        if theirs == self.id()? {
1351762×
            return Ok(());
135227×
        }
135327×
        if theirs == crate::protocol::UNBOUND_ID {
135424×
            if allow_unbound {
135523×
                return Ok(());
13561×
            }
13571×
            return fail(format!(
1358
                "remote {remote_name:?} is empty and unbound: push to it first"
1359
            ));
13603×
        }
13613×
        fail(format!(
1362
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1363
        ))
1364790×
    }
1365
1366
    /// Credentials and trust for a remote: `remote.<name>.token` and
1367
    /// `remote.<name>.ca`, else the defaults for its URL
1368
    /// ([`Repo::fill_credentials`]).
13691077×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
13701077×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
13711077×
        let mut options = RemoteOptions {
13721077×
            repo_id: self.id().ok(),
13731077×
            token: self.config.remote_tokens.get(name).cloned(),
13741077×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
13751077×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
13761077×
            ..RemoteOptions::default()
13771077×
        };
13781077×
        self.fill_credentials(&url, &mut options);
13791077×
        options
13801077×
    }
1381
1382
    /// The user's credential store (`credentials.toml` beside the user
1383
    /// configuration file).
13841098×
    pub fn credentials(&self) -> crate::credentials::Credentials {
13851098×
        crate::credentials::Credentials::at(
13861098×
            self.user_config
13871098×
                .parent()
13881098×
                .map(Path::to_path_buf)
13891098×
                .unwrap_or_else(default_home),
1390
        )
13911098×
    }
1392
1393
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1394
    /// then the user's credential store for its hub, then a remote on the
1395
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1396
    /// When the token is not this remote's own or the environment's, the
1397
    /// other tokens enclosing checkouts hold for the hub are kept to try
1398
    /// if it is refused: a stale stored login must not hide a parent's
1399
    /// good token (oxygen#112).
14001099×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14011099×
        if options.token.is_some() && options.ca.is_some() {
14021×
            return;
14031098×
        }
14041098×
        let explicit =
14051098×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14061098×
        let stored = self.credentials().options_for(url);
14071098×
        options.token = options.token.take().or(stored.token);
14081098×
        options.ca = options.ca.take().or(stored.ca);
14091098×
        let enclosing = self.enclosing_credentials(url);
14101098×
        if options.token.is_none() {
14111088×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
141210×
        }
14131098×
        if options.ca.is_none() {
14141079×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
141519×
        }
14161098×
        if !explicit {
14171091×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
14185×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
14192×
                    options.fallback_tokens.push(t);
14203×
                }
1421
            }
14227×
        }
14231099×
    }
1424
1425
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1426
    /// checkouts, nearest first.
14271098×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
14281098×
        let mut out = Vec::new();
14291098×
        let Some(hub) = crate::credentials::hub_of(url) else {
1430958×
            return out;
1431
        };
1432140×
        let mut at = self.root.parent();
1433568×
        while let Some(dir) = at {
1434428×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14350×
                break;
1436
            };
1437428×
            for (key, remote_url) in &cfg {
143815×
                let Some(name) = key
143915×
                    .strip_prefix("remote.")
144015×
                    .and_then(|k| k.strip_suffix(".url"))
1441
                else {
14427×
                    continue;
1443
                };
14448×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
14451×
                    continue;
14467×
                }
14477×
                out.push((
14487×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
14497×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
14507×
                ));
1451
            }
1452428×
            at = dir.parent();
1453
        }
1454140×
        out
14551098×
    }
1456
1457
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1458
    /// no changes and no reference updates, which the receiver stores.
14590×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
14600×
        let remote = self.open_named_remote(remote_name)?;
14610×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
14620×
        let mut bundle = Bundle::default();
14630×
        for r in seals {
14640×
            let attest = self.store.get_attest(r)?;
14650×
            let sigs = self.store.signatures(r)?;
14660×
            bundle
14670×
                .attests
14680×
                .push(crate::protocol::SignedAttest { attest, sigs });
1469
        }
14700×
        let results = remote.push(bundle, vec![], None, vec![])?;
14710×
        if let Some(r) = results.iter().find(|r| !r.ok) {
14720×
            return fail(format!("{}: {}", r.name, r.reason));
14730×
        }
14740×
        Ok(())
14750×
    }
1476
1477
    /// The remote whose URL starts with `base` (a hub), if configured.
14784×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
14794×
        let base = base.trim_end_matches('/');
14804×
        self.config
14814×
            .remotes
14824×
            .iter()
14834×
            .find(|(_, url)| url.trim_end_matches('/') == base)
14844×
            .map(|(name, _)| name.clone())
14854×
    }
1486
1487
    /// Open a remote by name or, failing that, by URL with the default
1488
    /// credentials (see [`Repo::credentials_for`]).
14890×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
14900×
        if let Some(name) = self.remote_for_url(url) {
14910×
            return Ok((name.clone(), self.open_named_remote(&name)?));
14920×
        }
14930×
        let options = RemoteOptions {
14940×
            repo_id: self.id().ok(),
14950×
            ..self.credentials_for(url)
14960×
        };
14970×
        Ok((url.to_string(), open_remote(url, &options)?))
14980×
    }
1499
1500
    /// Credentials for a URL: those of the configured remote with that
1501
    /// URL, else the environment's.
15024×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
15034×
        match self.remote_for_url(url) {
15044×
            Some(name) => self.remote_options(&name),
15050×
            None => RemoteOptions {
15060×
                repo_id: self.id().ok(),
15070×
                ..self.credentials_for(url)
15080×
            },
1509
        }
15104×
    }
1511
15121060×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15131060×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15141060×
    }
1515
1516178×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1517178×
        self.oxy
1518178×
            .join("remotes")
1519178×
            .join(remote)
1520178×
            .join(format!("{bookmark}.serial"))
1521178×
    }
1522
152358×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
152458×
        fs::read_to_string(self.serial_path(remote, bookmark))
152558×
            .ok()
152658×
            .and_then(|s| s.trim().parse().ok())
152758×
    }
1528
1529120×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1530120×
        let p = self.serial_path(remote, bookmark);
1531120×
        fs::create_dir_all(p.parent().unwrap())?;
1532120×
        write_atomic(&p, serial.to_string().as_bytes())
1533120×
    }
1534
1535437×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1536437×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1537437×
    }
1538
1539
    /// The highest policy serial `remote` has ever presented.
1540387×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1541387×
        fs::read_to_string(self.policy_serial_path(remote))
1542387×
            .ok()
1543387×
            .and_then(|s| s.trim().parse().ok())
1544387×
    }
1545
154650×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
154750×
        let p = self.policy_serial_path(remote);
154850×
        fs::create_dir_all(p.parent().unwrap())?;
154950×
        write_atomic(&p, serial.to_string().as_bytes())
155050×
    }
1551
155227×
    fn lazy_dir(&self) -> PathBuf {
155327×
        self.oxy.join("lazy")
155427×
    }
1555
1556
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
15574×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
15584×
        fs::create_dir_all(self.lazy_dir())?;
15594×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
15604×
    }
1561
1562
    /// Which remote promised an absent blob, if any.
156315×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
156415×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
156515×
            .ok()
156615×
            .map(|s| s.trim().to_string())
156715×
    }
1568
1569
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
15704×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
15714×
        let Some(remote_name) = self.lazy_remote(blob) else {
15720×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1573
        };
15744×
        let remote = self.open_named_remote(&remote_name)?;
15754×
        let objects = remote.objects(&[*blob])?;
15769×
        for (ty, body) in objects {
15779×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
15789×
                self.store.put(ty, &body)?;
15790×
            }
1580
        }
15814×
        if !self.store.has(blob) {
15820×
            return fail(format!(
1583
                "{remote_name} did not send blob {}",
15840×
                blob.short(12)
1585
            ));
15864×
        }
15874×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
15884×
        Ok(())
15894×
    }
1590
1591
    /// After importing from `remote`, record every blob the changes reference
1592
    /// that the store lacks as lazily available from that remote.
15934×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
15944×
        let mut n = 0;
15954×
        for h in changes {
15964×
            let c = self.store.get_change(h)?;
159713×
            for e in &c.edits {
159813×
                if let Edit::Replace { old, new, .. } = e {
15996×
                    for b in [old, new].into_iter().flatten() {
16006×
                        if !self.store.has(b) {
16014×
                            self.register_lazy(b, remote)?;
16024×
                            n += 1;
16032×
                        }
1604
                    }
16057×
                }
1606
            }
1607
        }
16084×
        Ok(n)
16094×
    }
1610
1611
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1612387×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1613387×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1614527×
        for st in view
1615387×
            .bookmarks
1616387×
            .values()
1617387×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1618
        {
1619527×
            if let Ok(s) = self.store.get_state(st) {
1620527×
                have.extend(s.heads);
1621527×
            }
1622
        }
1623387×
        have.extend(view.workspaces.values().copied());
1624387×
        Ok(have.into_iter().collect())
1625387×
    }
1626
1627
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1628393×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1629393×
        let remote = self.open_named_remote(remote_name)?;
1630390×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1631388×
        let resp = remote.refs()?;
1632
        // The host's transparency log (spec §14.8): a fork fails here.
1633387×
        let log = self.check_log(
1634387×
            &self.remote_url(remote_name)?,
1635387×
            self.config.remote_cas.get(remote_name).map(Path::new),
1636387×
            &resp,
16370×
        )?;
1638387×
        let mut log_notes = log.notes.clone();
1639
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1640
        // and signed by roots we trust, or on first contact. A remote that
1641
        // once presented a policy may never present none or an older one:
1642
        // that is a downgrade. A remote that never presented one is
1643
        // unverified, and this fetch is checked only as far as possible.
1644387×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1645387×
        let seen = self.remote_policy_serial(remote_name);
1646387×
        let mut unverified = false;
1647387×
        match &resp.policy {
164823×
            Some(sp) => {
164923×
                if seen.is_some_and(|s| sp.policy.serial < s) {
16500×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
165123×
                }
16529×
                match &local_policy {
16539×
                    Some(l) if sp.policy.serial < l.serial => {}
16549×
                    Some(l) if sp.policy.serial == l.serial => {
16555×
                        if sp.policy.hash() != l.hash() {
16560×
                            return fail(format!(
1657
                                "{remote_name} presents a different policy with the same serial {}",
1658
                                l.serial
1659
                            ));
16605×
                        }
1661
                    }
1662
                    _ => {
166318×
                        self.adopt_policy_chain(
166418×
                            &resp.history,
166518×
                            sp,
166618×
                            &format!("oxy fetch {remote_name}"),
1667
                        )
166818×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1669
                    }
1670
                }
167123×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1672
            }
1673
            None => {
1674364×
                if seen.is_some() {
16750×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1676364×
                }
1677364×
                unverified = true;
1678
            }
1679
        }
1680387×
        let policy = if unverified {
1681364×
            None
1682
        } else {
168323×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1684
        };
1685387×
        let (op_ref, op) = self.head_op()?;
1686387×
        let mut view = op.view.clone();
1687387×
        let have = self.known_heads(&view)?;
1688387×
        let mut report = Vec::new();
1689387×
        let mut skipped = Vec::new();
1690387×
        let max_blob = self.config.max_blob;
1691413×
        for r in resp.refs {
1692413×
            let needed = {
1693413×
                let _t = crate::timing::phase("fetch: negotiate");
1694413×
                remote.negotiate(&have, &r.heads)?
1695
            };
1696413×
            let bundle = {
1697413×
                let _t = crate::timing::phase("fetch: bundle");
1698413×
                remote.fetch(&needed, max_blob)?
1699
            };
1700
            // Changes are not individually re-verified here: the bookmark's
1701
            // attestation (checked below) binds its whole state, and the
1702
            // receiver of the push verified the added changes at that time.
1703413×
            let imported = {
1704413×
                let _t = crate::timing::phase("fetch: import");
1705413×
                self.import_bundle(&bundle, false)?
1706
            };
1707413×
            if max_blob.is_some() {
17084×
                self.register_missing_blobs(&imported, remote_name)?;
1709409×
            }
1710568×
            for h in &r.heads {
1711568×
                if !self.store.has(h) {
17120×
                    return fail(format!("remote did not send head {}", h.short(12)));
1713568×
                }
1714
            }
1715413×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1716413×
            if state != r.state {
17170×
                return fail(format!(
1718
                    "remote state {} does not match its heads",
17190×
                    r.state.short(12)
1720
                ));
1721413×
            }
1722413×
            if let Some(p) = &policy {
172326×
                let Some(sa) = &r.attestation else {
17240×
                    return fail(format!(
1725
                        "{remote_name}/{} has no attestation, which its policy requires",
1726
                        r.name
1727
                    ));
1728
                };
172926×
                let signer = sa
173026×
                    .sigs
173126×
                    .first()
173226×
                    .map(|s| s.key)
173326×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
173426×
                if !p.authorizes(&signer, &r.name) {
173511×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
173615×
                }
1737387×
            }
1738413×
            if let Some(sa) = &r.attestation {
1739
                let AttestBody::Ref {
174058×
                    old_state,
174158×
                    new_state,
1742
                    ..
174358×
                } = &sa.attest.body
1744
                else {
17450×
                    return fail("remote sent a non-ref attestation for a bookmark");
1746
                };
174758×
                let (old_state, new_state) = (*old_state, *new_state);
174858×
                let serial = self
174958×
                    .check_ref_attest_body(
175058×
                        sa,
175158×
                        &r.name,
175258×
                        &old_state,
175358×
                        &new_state,
175458×
                        self.last_seen_serial(remote_name, &r.name),
1755
                        true,
1756
                    )
175758×
                    .map_err(|e| {
17580×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
17590×
                    })?;
176058×
                if new_state != r.state {
17610×
                    return fail(format!(
1762
                        "attestation for {}/{} does not cover its current state",
1763
                        remote_name, r.name
1764
                    ));
176558×
                }
1766
                // A signature this client cannot verify (its signer unknown
1767
                // here, as from a host that did not send the identity, or
1768
                // bad) fails that bookmark alone: it stays as it was and
1769
                // the rest are fetched (oxygenhub#266). The current
1770
                // bookmark, which a pull would take, still fails the fetch.
1771
                // A policy's requirements were checked above and still fail.
177258×
                if let Err(e) = self.verify_attest_signature(sa) {
177312×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
177412×
                    if r.name == self.config.bookmark {
17753×
                        return fail(why);
17769×
                    }
17779×
                    skipped.push((r.name, why));
17789×
                    continue;
177946×
                }
178046×
                let ar = self.store.put_attest(&sa.attest)?;
178146×
                for sig in &sa.sigs {
178246×
                    self.store.put_signature(&ar, sig)?;
1783
                }
178446×
                self.record_serial(remote_name, &r.name, serial)?;
1785355×
            }
1786401×
            view.remotes
1787401×
                .entry(remote_name.to_string())
1788401×
                .or_default()
1789401×
                .insert(r.name.clone(), state);
1790401×
            report.push((r.name, r.heads, imported.len()));
1791
        }
1792384×
        let mut new_tags = 0;
1793384×
        for t in &resp.tags {
179413×
            if view.tags.contains_key(&t.name) {
17954×
                continue;
17969×
            }
1797
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
17989×
            let missing: Vec<ChangeHash> = t
17999×
                .heads
18009×
                .iter()
18019×
                .filter(|h| !self.store.has(h))
18029×
                .copied()
18039×
                .collect();
18049×
            if !missing.is_empty() {
18050×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
18060×
                let bundle = remote.fetch(&needed, max_blob)?;
18070×
                self.import_bundle(&bundle, false)?;
18089×
            }
18099×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
18109×
            self.adopt_tag(&mut view, t, policy.as_ref())
18119×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
18129×
            new_tags += 1;
1813
        }
1814384×
        if view != op.view {
1815370×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
181614×
        }
1817384×
        let _ = self.run_hook(
1818384×
            "post-fetch",
1819384×
            &format!(
1820
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1821384×
                json_str(remote_name),
1822398×
                json_array(report.iter().map(|(n, heads, _)| format!(
1823
                    "{{\"name\":{},\"heads\":{}}}",
1824398×
                    json_str(n),
1825553×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1826
                )))
1827
            ),
1828
        );
1829384×
        Ok(FetchReport {
1830384×
            refs: report,
1831384×
            unverified,
1832384×
            new_tags,
1833384×
            log_notes,
1834384×
            skipped,
1835384×
        })
1836393×
    }
1837
1838
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1839
    /// the changes within `depth` steps of its heads, and the boundary below.
18401×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
18411×
        let remote = self.open_named_remote(remote_name)?;
18421×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
18431×
        let resp = remote.refs()?;
18441×
        let bookmark = self.config.bookmark.clone();
18451×
        if let Some(sp) = &resp.policy {
18460×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
18470×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
18480×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
18491×
        }
18501×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
18510×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1852
        };
18531×
        if r.heads.is_empty() {
18540×
            return Ok(0);
18551×
        }
1856
        // Base: the remote's checkpoint of exactly these heads.
18571×
        let cp_bundle = remote.checkpoint(&r.heads)?;
18581×
        let mut cp_ref = None;
18593×
        for (ty, body) in &cp_bundle.objects {
18603×
            let put = self.store.put(*ty, body)?;
18613×
            if *ty == ObjectType::Checkpoint {
18621×
                cp_ref = Some(put);
18632×
            }
1864
        }
18651×
        let Some(cp_ref) = cp_ref else {
18660×
            return fail(format!("{remote_name} sent no checkpoint"));
1867
        };
18681×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1869
        // History window.
18701×
        let wanted = remote.shallow(&r.heads, depth)?;
18711×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
18721×
        let imported = self.import_bundle_shallow(&bundle, false)?;
18731×
        if self.config.max_blob.is_some() {
18740×
            self.register_missing_blobs(&imported, remote_name)?;
18751×
        }
18761×
        self.refresh_boundary(&imported)?;
18771×
        if let Some(sa) = &r.attestation {
18780×
            let ar = self.store.put_attest(&sa.attest)?;
18790×
            for sig in &sa.sigs {
18800×
                self.store.put_signature(&ar, sig)?;
1881
            }
18820×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
18830×
                self.record_serial(remote_name, &r.name, serial)?;
18840×
            }
18851×
        }
18861×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
18871×
        let (op_ref, op) = self.head_op()?;
18881×
        let mut view = op.view.clone();
18891×
        view.remotes
18901×
            .entry(remote_name.to_string())
18911×
            .or_default()
18921×
            .insert(r.name.clone(), state);
18931×
        self.record_op(
18941×
            &[op_ref],
18951×
            &format!("oxy fetch {remote_name} --depth {depth}"),
18961×
            view,
18970×
        )?;
18981×
        Ok(imported.len())
18991×
    }
1900
1901
    /// Fetch, then take the union of the local bookmark's state with the
1902
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1903115×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1904115×
        let _wc = self.lock_working_copy()?;
1905115×
        let skipped = self.fetch(remote_name)?.skipped;
1906111×
        let (op_ref, op) = self.head_op()?;
1907111×
        let current = self.config.bookmark.clone();
1908111×
        let mut local_current = self.heads_of(&op.view, &current)?;
1909111×
        local_current.sort();
1910111×
        let mut view = op.view.clone();
1911111×
        let mut current_heads = local_current.clone();
1912111×
        let mut changed = false;
1913111×
        let mut others = Vec::new();
1914111×
        let tracked = op
1915111×
            .view
1916111×
            .remotes
1917111×
            .get(remote_name)
1918111×
            .cloned()
1919111×
            .unwrap_or_default();
1920116×
        for (name, remote_state) in tracked {
1921
            // Every local bookmark tracks the remote's of the same name;
1922
            // the current one may be new here.
1923116×
            let local_state = op.view.bookmarks.get(&name).copied();
1924116×
            if local_state.is_none() && name != current {
19251×
                continue;
1926115×
            }
1927115×
            if local_state == Some(remote_state) {
192810×
                continue;
1929105×
            }
1930105×
            let local = self.heads_of(&op.view, &name)?;
1931105×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1932147×
            if remote_heads.iter().all(|h| local.contains(h)) {
19330×
                continue;
1934105×
            }
1935105×
            let mut all = local.clone();
1936105×
            all.extend(remote_heads);
1937105×
            let st = self.load_state_history(&all)?;
1938105×
            let mut heads = st.maximal(&all);
1939105×
            heads.sort();
1940105×
            let mut sorted_local = local;
1941105×
            sorted_local.sort();
1942105×
            if heads == sorted_local {
19431×
                continue;
1944104×
            }
1945104×
            view.bookmarks.insert(
1946104×
                name.clone(),
1947104×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1948
            );
1949104×
            if name == current {
1950102×
                changed = true;
1951102×
                current_heads = heads;
1952102×
            } else {
19532×
                others.push(name);
19542×
            }
1955
        }
1956111×
        if changed || !others.is_empty() {
1957103×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
19588×
        }
1959
        // The working copy follows its bookmark whenever nothing would be
1960
        // lost, also when this pull brought nothing new but it had been
1961
        // left behind (oxygen#89).
1962111×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1963
        Ok(PullReport {
1964111×
            heads: if changed {
1965102×
                current_heads
1966
            } else {
19679×
                local_current
1968
            },
1969111×
            changed,
1970111×
            checked_out,
1971111×
            others,
1972111×
            skipped,
1973
        })
1974115×
    }
1975
1976
    /// How many changes the working copy's bookmark has that its base
1977
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1978
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1979
    /// the bookmark or holds changes the bookmark lacks. History is read
1980
    /// only when the base and the bookmark's heads differ (oxygen#89).
19817×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
19827×
        let (_, wc) = self.working_copy()?;
19837×
        let mut base = wc.deps.clone();
19847×
        base.sort();
19857×
        let mut heads = self.bookmark_heads()?;
19867×
        heads.sort();
19877×
        if base == heads || heads.is_empty() {
19886×
            return Ok(None);
19891×
        }
19901×
        let state = self.load_state_history(&heads)?;
19911×
        if !base.iter().all(|h| state.contains(h)) {
19920×
            return Ok(None);
19931×
        }
19941×
        let had = if base.is_empty() {
19950×
            0
1996
        } else {
19971×
            self.load_state_history(&base)?.len()
1998
        };
19991×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
20007×
    }
2001
2002
    /// Bring the working copy to `heads`, the state of its bookmark
2003
    /// `bookmark`, when nothing would be lost: its base is part of that
2004
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2005
    /// with uncommitted work, the work comes along when the new changes
2006
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2007
    /// it followed only from exactly the bookmark's old heads, so a working
2008
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2009
    /// or a pull from another workspace) never caught up, and nothing said
2010
    /// so (oxygen#74, #89). Returns whether it moved.
2011111×
    pub fn follow_bookmark(
2012111×
        &self,
2013111×
        heads: &[ChangeHash],
2014111×
        bookmark: &str,
2015111×
        command: &str,
2016111×
    ) -> Result<bool> {
2017111×
        let snap = self.snapshot(command)?;
2018111×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2019111×
        let mut base = snap.base.maximal(&snap.wc.deps);
2020111×
        base.sort();
2021111×
        let mut target = heads.to_vec();
2022111×
        target.sort();
2023111×
        if base == target {
20248×
            return Ok(false);
2025103×
        }
2026103×
        let state = self.load_state_history(heads)?;
2027189×
        if !base.iter().all(|h| state.contains(h)) {
2028
            // The working copy holds changes the bookmark lacks: not ours to move.
20290×
            return Ok(false);
2030103×
        }
2031103×
        if clean {
2032103×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
2033103×
            Ok(true)
2034
        } else {
20350×
            Ok(self
20360×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
20370×
                .is_ok())
2038
        }
2039111×
    }
2040
2041
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2042
    /// changes and attesting the reference when a key is available.
2043
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2044
    /// state, attested when we have an identity. The local bookmark, if
2045
    /// any, is kept; only the remote-tracking entry goes.
20465×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
20475×
        let remote = self.open_named_remote(remote_name)?;
20485×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
20495×
        let resp = remote.refs()?;
20507×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
20511×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2052
        };
20534×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
20540×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
20554×
        }
20564×
        let attestation = match self.secret_key()? {
20572×
            Some(_) => Some(self.sign_attest(&Attest {
20582×
                repo: self.id()?,
20592×
                hlc: Hlc::now(),
20602×
                body: AttestBody::Ref {
20612×
                    name: bookmark.to_string(),
20622×
                    old_state: r.state,
20632×
                    new_state: ObjectRef::ZERO,
20642×
                    serial: r.last_serial.unwrap_or(0) + 1,
20652×
                },
20660×
            })?),
20672×
            None => None,
2068
        };
20694×
        let results = remote.push(
20704×
            Bundle::default(),
20714×
            vec![RefUpdate {
20724×
                name: bookmark.to_string(),
20734×
                old_state: r.state,
20744×
                new_state: ObjectRef::ZERO,
20754×
                force: true,
20764×
                attestation,
20774×
            }],
20784×
            None,
20794×
            vec![],
20800×
        )?;
20814×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
20822×
            let (op_ref, op) = self.head_op()?;
20832×
            let mut view = op.view.clone();
20842×
            if let Some(m) = view.remotes.get_mut(remote_name) {
20852×
                m.remove(bookmark);
20862×
            }
20872×
            self.record_op(
20882×
                &[op_ref],
20892×
                &format!("oxy push {remote_name} --delete {bookmark}"),
20902×
                view,
20910×
            )?;
20922×
        }
20934×
        Ok(results)
20945×
    }
2095
2096
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2097
    /// repository's config (its URL, token, CA and store settings), its
2098
    /// tracking bookmarks in the view, and a store remote's mirror under
2099
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
21003×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
21013×
        if !self.config.remotes.contains_key(name) {
21021×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
21032×
        }
21042×
        let prefix = format!("remote.{name}.");
21052×
        let keys: Vec<String> = self
21062×
            .config
21072×
            .repo_layer()
21082×
            .keys()
21094×
            .filter(|k| k.starts_with(&prefix))
21102×
            .cloned()
21112×
            .collect();
21123×
        for k in keys {
21133×
            self.config.set(&k, "")?;
2114
        }
21152×
        self.config.remotes.remove(name);
21162×
        self.save_config()?;
21172×
        let (op_ref, op) = self.head_op()?;
21182×
        if op.view.remotes.contains_key(name) {
21191×
            let mut view = op.view.clone();
21201×
            view.remotes.remove(name);
21211×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
21221×
        }
21232×
        let mirror = self.oxy.join("remotes").join(name);
21242×
        if mirror.is_dir() {
21250×
            fs::remove_dir_all(&mirror)?;
21262×
        }
21272×
        Ok(())
21283×
    }
2129
2130
    /// `changes`, in dependency order, cut into batches of about
2131
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2132
    /// There is always one, perhaps empty.
2133305×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2134305×
        let blob_len = |r: &ObjectRef| -> u64 {
213529×
            self.store
213629×
                .get_typed(r, ObjectType::Blob)
213729×
                .ok()
213829×
                .and_then(|b| Blob::decode(&b).ok())
213929×
                .map_or(0, |b| b.length)
214029×
        };
2141305×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2142417×
        for h in changes {
2143417×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2144417×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2145417×
            let mut weight = raw.len() as u64;
2146541×
            for t in &texts {
2147541×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
214826×
                    weight += blob_len(r);
2149515×
                }
2150
            }
2151680×
            for e in &c.edits {
21523×
                if let Edit::Replace { new: Some(b), .. } = e {
21533×
                    weight += blob_len(b);
2154677×
                }
2155
            }
2156417×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
21575×
                out.push(std::mem::take(&mut batch));
21585×
                bytes = 0;
2159412×
            }
2160417×
            batch.push(*h);
2161417×
            bytes += weight;
2162
        }
2163305×
        out.push(batch);
2164305×
        Ok(out)
2165305×
    }
2166
2167374×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2168374×
        let bookmark = self.config.bookmark.clone();
2169374×
        self.push_bookmark(remote_name, &bookmark, force)
2170374×
    }
2171
2172
    /// `push` for a named bookmark (`oxy push -b NAME`).
2173387×
    pub fn push_bookmark(
2174387×
        &self,
2175387×
        remote_name: &str,
2176387×
        bookmark: &str,
2177387×
        force: bool,
2178387×
    ) -> Result<Vec<RefResult>> {
2179387×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2180387×
    }
2181
2182
    /// `push_bookmark`, saying how a long push is going: one line per
2183
    /// batch sent (oxygen#95).
2184395×
    pub fn push_bookmark_with(
2185395×
        &self,
2186395×
        remote_name: &str,
2187395×
        bookmark: &str,
2188395×
        force: bool,
2189395×
        progress: crate::store::Progress,
2190395×
    ) -> Result<Vec<RefResult>> {
2191395×
        let (op_ref, op) = self.head_op()?;
2192395×
        if !op.view.bookmarks.contains_key(bookmark) {
21930×
            return fail(format!("no bookmark {bookmark}"));
2194395×
        }
2195395×
        let bookmark = bookmark.to_string();
2196395×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2197
        // pre-push hook: may veto before the remote is contacted.
2198395×
        self.run_hook(
2199395×
            "pre-push",
2200395×
            &format!(
2201
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2202395×
                json_str(remote_name),
2203395×
                json_str(&bookmark),
2204794×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2205
            ),
22061×
        )?;
2207394×
        let remote = self.open_named_remote(remote_name)?;
2208394×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2209391×
        let resp = remote.refs()?;
2210391×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2211391×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2212391×
        let policy_to_send = match (&local_policy, &resp.policy) {
221333×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
221412×
            (Some(l), None) => Some(l.clone()),
221518×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
22161×
                return fail(format!(
2217
                    "{remote_name} has a newer policy (serial {}); fetch first",
2218
                    r.policy.serial
2219
                ));
2220
            }
2221363×
            _ => None,
2222
        };
2223390×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2224390×
        if remote_has_policy && self.secret_key()?.is_none() {
22251×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2226389×
        }
2227389×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2228389×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2229389×
            .tag_refs()?
2230389×
            .into_iter()
2231389×
            .filter(|t| !remote_tags.contains(&t.name))
2232389×
            .collect();
2233389×
        let refs = resp.refs;
2234389×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2235389×
        let (remote_state, remote_heads, last_serial) =
2236390×
            match refs.iter().find(|r| r.name == bookmark) {
2237367×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
223822×
                None => (empty, vec![], None),
2239
            };
2240389×
        let new_state = self
2241389×
            .store
2242389×
            .put_state(&StateObject::new(local_heads.clone()))?;
2243
        // A push that carries a policy re-attests the bookmark even when its
2244
        // state is unchanged, so the current attestation is always by a key
2245
        // the current policy authorizes (a revoked key's attestation would
2246
        // otherwise be refused by every later fetch).
2247389×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
224810×
            return Ok(vec![RefResult {
224910×
                name: bookmark,
225010×
                ok: true,
225110×
                reason: "already up to date".into(),
225210×
            }]);
2253379×
        }
2254406×
        for h in &remote_heads {
2255406×
            if !self.store.has(h) {
225673×
                return fail(format!(
2257
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
225873×
                    h.short(12)
2259
                ));
2260333×
            }
2261
        }
2262306×
        if !force {
2263306×
            let closure = self.closure_in_store(&local_heads)?;
2264306×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
22650×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2266306×
            }
22670×
        }
2268306×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2269306×
        let key = self.secret_key()?.map(|(k, _)| k);
2270306×
        if let Some(key) = key {
2271
            // Seal this author's changes that carry no valid authenticator,
2272
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2273
            // are stored, so each batch's bundle carries those it needs.
227497×
            let mut unsigned = Vec::new();
227597×
            for h in &to_send {
227687×
                let c = self.store.get_change_meta(h)?;
227787×
                if self.seals_for_author(&c.author, &key)
227882×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
227948×
                {
228048×
                    unsigned.push(*h);
228148×
                }
2282
            }
228397×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
228445×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2285
            }
2286209×
        }
2287
        // A long history goes in batches, in dependency order, so neither
2288
        // side holds it whole and no request passes the remote's limit:
2289
        // all but the last carry objects alone; the last moves the bookmark
2290
        // (oxygen#95).
2291305×
        let batches = self.push_batches(&to_send)?;
2292305×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2293305×
        for (i, batch) in earlier.iter().enumerate() {
22945×
            progress(&format!(
22955×
                "part {} of {}: {} changes",
22965×
                i + 1,
22975×
                batches.len(),
22985×
                batch.len()
22995×
            ));
23005×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
23015×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
23025×
                Some(r) if r.ok => {}
23030×
                Some(r) => {
23040×
                    return fail(format!(
2305
                        "{remote_name} refused part {} of the push: {}",
23060×
                        i + 1,
2307
                        r.reason
2308
                    ))
2309
                }
2310
                None => {
23110×
                    return fail(format!(
2312
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2313
                    ))
2314
                }
2315
            }
2316
        }
2317305×
        if batches.len() > 1 {
23181×
            progress(&format!(
23191×
                "part {} of {}: {} changes",
23201×
                batches.len(),
23211×
                batches.len(),
23221×
                last.len()
23231×
            ));
2324304×
        }
2325305×
        let mut bundle = self.bundle_for(last)?;
2326305×
        bundle.objects.push((
2327305×
            ObjectType::State,
2328305×
            StateObject::new(local_heads.clone()).encode(),
2329305×
        ));
2330305×
        let attestation = match key {
233196×
            Some(_) => Some(self.sign_attest(&Attest {
233296×
                repo: self.id()?,
233396×
                hlc: Hlc::now(),
233496×
                body: AttestBody::Ref {
233596×
                    name: bookmark.clone(),
233696×
                    old_state: remote_state,
233796×
                    new_state,
233896×
                    serial: next_serial(last_serial),
233996×
                },
23401×
            })?),
2341209×
            None => None,
2342
        };
2343
        // Whoever signed the move, and whom a delegate acts for, travel with
2344
        // it: a receiver that has never seen a change by this delegate could
2345
        // not otherwise check its signature (oxygenhub#129).
2346304×
        if attestation.is_some() {
2347190×
            for k in [self.signing_key(), self.config.author_key]
234895×
                .into_iter()
234995×
                .flatten()
2350
            {
2351190×
                if let Ok(id) = self.identity(&k) {
2352190×
                    let body = id.encode();
2353190×
                    if !bundle
2354190×
                        .objects
2355190×
                        .iter()
2356229×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
235722×
                    {
235822×
                        bundle.objects.push((ObjectType::Identity, body));
2359168×
                    }
23600×
                }
2361
            }
2362
            // A short-lived signing key's certificate goes with it (§14.7).
236395×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
236495×
            self.attach_certificates_for(&mut bundle, &signers)?;
2365209×
        }
2366304×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
236795×
            AttestBody::Ref { serial, .. } => Some(serial),
23680×
            _ => None,
236995×
        });
2370304×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2371
        // Tag states must be present on the remote: bundle their changes too.
2372304×
        for t in &tags_to_send {
23736×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
23746×
            let extra: Vec<ChangeHash> =
23756×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
23766×
            if !extra.is_empty() {
23770×
                let more = self.bundle_for(&extra)?;
23780×
                bundle.changes.extend(more.changes);
23790×
                bundle.hashes.extend(more.hashes);
23800×
                bundle.attests.extend(more.attests);
23810×
                bundle.objects.extend(more.objects);
23826×
            }
23836×
            bundle.objects.push((
23846×
                ObjectType::State,
23856×
                StateObject::new(t.heads.clone()).encode(),
23866×
            ));
2387
        }
2388304×
        if let Some(l) = &policy_to_send {
238927×
            let remote_serial = resp_policy_serial;
239027×
            bundle.policies = self
239127×
                .policy_history()?
239227×
                .into_iter()
239356×
                .filter(|sp| {
239456×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
239529×
                        && sp.policy.serial < l.policy.serial
239656×
                })
239727×
                .collect();
2398277×
        }
2399304×
        let results = remote.push(
2400304×
            bundle,
2401304×
            vec![RefUpdate {
2402304×
                name: bookmark.clone(),
2403304×
                old_state: remote_state,
2404304×
                new_state,
2405304×
                force,
2406304×
                attestation,
2407304×
            }],
2408304×
            policy_to_send,
2409304×
            tags_to_send,
24108×
        )?;
241127×
        if let (Some(serial), true) = (
2412296×
            sent_serial,
2413302×
            results.iter().any(|r| r.ok && r.name == "policy"),
2414
        ) {
241527×
            self.record_policy_serial(remote_name, serial)?;
2416269×
        }
2417323×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2418272×
            let mut view = op.view.clone();
2419272×
            view.remotes
2420272×
                .entry(remote_name.to_string())
2421272×
                .or_default()
2422272×
                .insert(bookmark.clone(), new_state);
2423272×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2424269×
            if let Some(s) = serial {
242574×
                self.record_serial(remote_name, &bookmark, s)?;
2426195×
            }
242724×
        }
2428291×
        Ok(results)
2429395×
    }
2430
2431
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2432
    /// bookmark set to the remote's, working copy checked out.
2433249×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2434249×
        Self::clone_with(url, dest, None, &[])
2435249×
    }
2436
2437
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2438
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2439
    /// unless a size is given, so out-of-scope binaries are never fetched).
2440252×
    pub fn clone_with(
2441252×
        url: &str,
2442252×
        dest: &Path,
2443252×
        max_blob: Option<u64>,
2444252×
        sparse: &[String],
2445252×
    ) -> Result<Repo> {
2446252×
        Self::clone_full(url, dest, max_blob, sparse, None)
2447252×
    }
2448
2449
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2450
    /// changes within `depth` steps of them; the rest is the boundary.
24511×
    pub fn clone_shallow(
24521×
        url: &str,
24531×
        dest: &Path,
24541×
        depth: u32,
24551×
        max_blob: Option<u64>,
24561×
        sparse: &[String],
24571×
    ) -> Result<Repo> {
24581×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
24591×
    }
2460
2461253×
    fn clone_full(
2462253×
        url: &str,
2463253×
        dest: &Path,
2464253×
        max_blob: Option<u64>,
2465253×
        sparse: &[String],
2466253×
        depth: Option<u32>,
2467253×
    ) -> Result<Repo> {
2468253×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2469253×
    }
2470
2471
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2472
    /// `depth`), also returning the bookmarks the fetch left out because
2473
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2474
    /// for the caller to warn about. The bookmark checked out is never one
2475
    /// of them: that fails the clone.
2476259×
    pub fn clone_reporting(
2477259×
        url: &str,
2478259×
        dest: &Path,
2479259×
        max_blob: Option<u64>,
2480259×
        sparse: &[String],
2481259×
        depth: Option<u32>,
2482259×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2483259×
        let options = crate::credentials::Credentials::user().options_for(url);
2484259×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2485259×
    }
2486
2487
    /// Clone a subrepo with the credentials the parent would use for its
2488
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2489
    /// subrepo: it finds the same ones again through its parent.
249010×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
249110×
        let options = self.credentials_for(url);
249210×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
249310×
    }
2494
2495
    /// The name of a remote of this repository on the same hub (scheme,
2496
    /// host and port) as `url`.
249723×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
249827×
        let origin = |u: &str| -> Option<String> {
249927×
            let (scheme, rest) = u.split_once("://")?;
25008×
            if !matches!(scheme, "http" | "https") {
25010×
                return None;
25028×
            }
25038×
            let host = rest.split('/').next()?;
25048×
            Some(format!(
25058×
                "{}://{}",
25068×
                scheme.to_ascii_lowercase(),
25078×
                host.to_ascii_lowercase()
25088×
            ))
250927×
        };
251023×
        let want = origin(url)?;
25114×
        self.config
25124×
            .remotes
25134×
            .iter()
25144×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
25154×
            .map(|(name, _)| name.clone())
251623×
    }
2517
2518
    /// The token and CA to reach `url` with: those of a remote of this
2519
    /// repository on the same hub (scheme, host and port), else the
2520
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2521
    /// and enclosing checkouts', as a clone would use them.
252223×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
252323×
        match self.remote_on_same_hub(url) {
25241×
            Some(name) => RemoteOptions {
25251×
                repo_id: None,
25261×
                cache_dir: None,
25271×
                ..self.remote_options(&name)
25281×
            },
2529
            None => {
253022×
                let mut options = RemoteOptions::default();
253122×
                self.fill_credentials(url, &mut options);
253222×
                options
2533
            }
2534
        }
253523×
    }
2536
2537269×
    fn clone_using(
2538269×
        url: &str,
2539269×
        dest: &Path,
2540269×
        max_blob: Option<u64>,
2541269×
        sparse: &[String],
2542269×
        depth: Option<u32>,
2543269×
        options: &RemoteOptions,
2544269×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2545269×
        let remote = open_remote(url, options)?;
2546269×
        let id = remote.repo_id()?;
2547265×
        if id == crate::protocol::UNBOUND_ID {
25482×
            return fail(format!(
2549
                "{url} is empty and unbound: push a repository to it first"
2550
            ));
2551263×
        }
2552263×
        let mut repo = Repo::init_with_id(dest, id)?;
2553263×
        repo.config
2554263×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2555263×
        if let Some(m) = max_blob {
25562×
            repo.config.set("filter.max-blob", &m.to_string())?;
2557261×
        } else if !sparse.is_empty() {
25581×
            repo.config.set("filter.max-blob", "0")?;
2559260×
        }
2560263×
        if !sparse.is_empty() {
25611×
            repo.config.set("filter.paths", &sparse.join(","))?;
2562262×
        }
2563263×
        repo.save_config()?;
2564263×
        let skipped = if let Some(depth) = depth {
25651×
            repo.fetch_shallow("origin", depth)?;
25661×
            Vec::new()
2567
        } else {
2568262×
            repo.fetch("origin")?.skipped
2569
        };
2570261×
        let (op_ref, op) = repo.head_op()?;
2571
        // The remote's default bookmark, else ours (main), else its only
2572
        // one; a bookmark the fetch skipped counts, so the clone fails
2573
        // rather than check out another (oxygenhub#266).
2574261×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2575261×
        for (name, _) in &skipped {
25762×
            theirs.insert(name.clone(), ObjectRef::ZERO);
25772×
        }
2578
        // Asked of the remote as now configured, so a store-backed one
2579
        // answers from the mirror the fetch just filled.
2580261×
        let advertised = repo
2581261×
            .open_named_remote("origin")
2582261×
            .ok()
2583261×
            .and_then(|r| r.refs().ok())
2584261×
            .and_then(|r| r.default_bookmark);
2585261×
        let bookmark = advertised
2586261×
            .filter(|b| theirs.contains_key(b))
2587261×
            .or_else(|| {
25887×
                theirs
25897×
                    .contains_key(&repo.config.bookmark)
25907×
                    .then(|| repo.config.bookmark.clone())
25917×
            })
2592261×
            .or_else(|| {
25930×
                (theirs.len() == 1)
25940×
                    .then(|| theirs.keys().next().cloned())
25950×
                    .flatten()
25960×
            })
2597261×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2598261×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
25990×
            return fail(format!("cannot check out {bookmark}: {why}"));
2600261×
        }
2601261×
        let initial = repo.config.bookmark.clone();
2602261×
        if bookmark != repo.config.bookmark {
26031×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
26041×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
26051×
            repo.config.bookmark = bookmark.clone();
2606260×
        }
2607261×
        if let Some(state) = theirs.get(&bookmark).copied() {
2608261×
            let heads = repo.store.get_state(&state)?.heads;
2609261×
            let mut view = op.view.clone();
2610
            // The empty bookmark `init` made goes when another is checked out.
2611261×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
26121×
                view.bookmarks.remove(&initial);
2613260×
            }
2614261×
            view.bookmarks.insert(bookmark, state);
2615261×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2616261×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
26170×
        }
2618261×
        Ok((repo, skipped))
2619269×
    }
2620
}
2621
2622
/// The serial of a reference's next attestation: one more than the last the
2623
/// remote reports, or, for a bookmark the remote does not have, the clock in
2624
/// milliseconds, so a bookmark created again after a deletion goes past the
2625
/// deletion's serial the remote keeps.
262696×
fn next_serial(last: Option<u64>) -> u64 {
262796×
    match last {
262858×
        Some(l) => l + 1,
262938×
        None => Hlc::now().wall_ms.max(1),
2630
    }
263196×
}