OXYGENHUB

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

1899 of 2107 lines run, 311 of 406 functions · run #365 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::tags::TagCheck;
4
use super::*;
5
6
/// What a push did, for hosts (hub spec §6.12).
7
#[derive(Clone, Debug, Default)]
8
pub struct PushReport {
9
    pub results: Vec<RefResult>,
10
    /// Accepted reference updates, in request order.
11
    pub updated: Vec<RefUpdated>,
12
    /// Changes this push stored that were not already present.
13
    pub imported: Vec<ChangeHash>,
14
}
15
16
#[derive(Clone, Debug)]
17
pub struct RefUpdated {
18
    pub name: String,
19
    pub old_state: ObjectRef,
20
    pub new_state: ObjectRef,
21
    pub heads: Vec<ChangeHash>,
22
}
23
24
/// What a fetch brought in.
25
#[derive(Debug, Clone, PartialEq, Eq, Default)]
26
pub struct FetchReport {
27
    /// Bookmark name, its heads, and how many changes were new.
28
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
29
    /// Tags adopted from the remote.
30
    pub new_tags: usize,
31
    /// The remote has never presented a policy, so nothing was verified
32
    /// against one (spec §14.5: warn loudly).
33
    pub unverified: bool,
34
    /// What checking the host's transparency log found short of a fork
35
    /// (spec §14.8): attestations not logged yet, a log that could not be
36
    /// read. A fork fails the fetch instead.
37
    pub log_notes: Vec<String>,
38
    /// Bookmarks left as they were because their attestation could not be
39
    /// verified (its signer unknown here, or its signature bad), each with
40
    /// why (oxygenhub#266). The current bookmark is never skipped: its
41
    /// fetch fails instead.
42
    pub skipped: Vec<(String, String)>,
43
}
44
45
#[derive(Debug, Clone, PartialEq, Eq)]
46
pub struct PullReport {
47
    /// The current bookmark's heads after the pull.
48
    pub heads: Vec<ChangeHash>,
49
    /// Whether the current bookmark changed.
50
    pub changed: bool,
51
    pub checked_out: bool,
52
    /// Other bookmarks the pull moved: each local bookmark tracks the
53
    /// remote's of the same name.
54
    pub others: Vec<String>,
55
    /// What the fetch left as it was ([`FetchReport::skipped`]).
56
    pub skipped: Vec<(String, String)>,
57
}
58
59
/// The result a push of objects alone reports (a batch of a long history):
60
/// not a reference.
61
pub const OBJECTS_RESULT: &str = "objects";
62
63
impl Repo {
64
    // ------------------------------------------------------------ serving (spec §16)
65
661804×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
671804×
        self.oxy.join("attest").join(name_file(bookmark))
681804×
    }
69
70
    /// The latest reference attestation stored for a bookmark.
711396×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
721396×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
73334×
            Ok(h) => {
74334×
                let r = ObjectRef::from_hex(h.trim())
75334×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
76
                Ok(Some((
77334×
                    r,
78
                    SignedAttest {
79334×
                        attest: self.store.get_attest(&r)?,
80334×
                        sigs: self.store.signatures(&r)?,
81
                    },
82
                )))
83
            }
841062×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
850×
            Err(e) => Err(e.into()),
86
        }
871396×
    }
88
89107×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
90107×
        fs::create_dir_all(self.oxy.join("attest"))?;
91107×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
92107×
    }
93
941109×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
951109×
        let view = self.view()?;
961109×
        let mut out = Vec::new();
971162×
        for (name, state) in &view.bookmarks {
981162×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
991162×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
100220×
                AttestBody::Ref { serial, .. } => Some(serial),
1010×
                _ => None,
102220×
            });
1031162×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1041162×
            let accepted = match &attestation {
105209×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
106953×
                None => None,
107
            };
1081162×
            out.push(RemoteRef {
1091162×
                name: name.clone(),
1101162×
                state: *state,
1111162×
                heads: self.store.get_state(state)?.heads,
1121162×
                attestation,
1131162×
                last_serial,
1141162×
                accepted,
1151162×
                logged: None,
1161162×
                integration: vec![],
117
            });
118
        }
1191109×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1201109×
        let history = self
1211109×
            .policy_history()?
1221109×
            .into_iter()
1231109×
            .filter(|sp| {
124211×
                policy
125211×
                    .as_ref()
126211×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
127211×
            })
1281109×
            .collect();
129
        Ok(RefsResponse {
1301109×
            refs: out,
1311109×
            policy,
1321109×
            tags: self.tag_refs()?,
1331109×
            history,
1341109×
            default_bookmark: Some(self.config.bookmark.clone()),
1351109×
            log: None,
1361109×
            witnesses: vec![],
137
        })
1381109×
    }
139
140
    /// Every change reachable from `heads` that is in the store.
1411512×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1421512×
        let mut seen = BTreeSet::new();
1431512×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1445088×
        while let Some(h) = stack.pop() {
1453576×
            if seen.contains(&h) || !self.store.has(&h) {
1461054×
                continue;
1472522×
            }
1482522×
            seen.insert(h);
1492522×
            stack.extend(self.store.get_change_meta(&h)?.deps);
150
        }
1511512×
        Ok(seen)
1521512×
    }
153
154
    /// The changes within `depth` dependency steps of `heads` (spec §17),
155
    /// nearest first; depth 1 is the heads themselves.
1563×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1573×
        let mut out = Vec::new();
1583×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1593×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1603×
        for _ in 0..depth.max(1) {
1618×
            let mut next = Vec::new();
16212×
            for h in layer {
16312×
                if !seen.insert(h) || !self.store.has(&h) {
1642×
                    continue;
16510×
                }
16610×
                let c = self.store.get_change(&h)?;
16710×
                next.extend(c.deps.iter().copied());
16810×
                out.push(h);
169
            }
1708×
            if next.is_empty() {
1711×
                break;
1727×
            }
1737×
            layer = next;
174
        }
1753×
        out.reverse();
1763×
        Ok(out)
1773×
    }
178
1792138×
    fn shallow_path(&self) -> PathBuf {
1802138×
        self.oxy.join("shallow")
1812138×
    }
182
183
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1842135×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1852135×
        fs::read_to_string(self.shallow_path())
1862135×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1872135×
            .unwrap_or_default()
1882135×
    }
189
190190×
    pub fn is_shallow(&self) -> bool {
191190×
        !self.boundary().is_empty()
192190×
    }
193
1943×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1953×
        if boundary.is_empty() {
1961×
            let _ = fs::remove_file(self.shallow_path());
1971×
            return Ok(());
1982×
        }
1992×
        let text: String = boundary
2002×
            .iter()
2012×
            .map(|h| format!("{}\n", h.to_hex()))
2022×
            .collect();
2032×
        write_atomic(&self.shallow_path(), text.as_bytes())
2043×
    }
205
206
    /// Recompute the boundary from what is stored: every dependency of a
207
    /// stored change that is not itself stored.
2083×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2093×
        let mut boundary = self.boundary();
2103×
        boundary.retain(|h| !self.store.has(h));
21110×
        for h in imported {
21213×
            for d in self.store.get_change_meta(h)?.deps {
21313×
                if !self.store.has(&d) {
2142×
                    boundary.insert(d);
21511×
                }
216
            }
217
        }
2183×
        self.write_boundary(&boundary)
2193×
    }
220
221
    /// Fetch `depth` more levels of history below the shallow boundary.
2222×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2232×
        let boundary = self.boundary();
2242×
        if boundary.is_empty() {
2250×
            return Ok(0);
2262×
        }
2272×
        let remote = self.open_named_remote(remote_name)?;
2282×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2292×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2302×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2312×
        if self.config.max_blob.is_some() {
2320×
            self.register_missing_blobs(&imported, remote_name)?;
2332×
        }
2342×
        self.refresh_boundary(&imported)?;
2352×
        Ok(imported.len())
2362×
    }
237
238
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
239877×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
240877×
        let have = self.closure_in_store(have)?;
241
        // In a shallow repository the walk stops at the boundary, whose
242
        // changes the remote is assumed to hold.
243877×
        let boundary = self.boundary();
244877×
        let mut out = Vec::new();
245877×
        let mut done: BTreeSet<ChangeHash> = have.clone();
246877×
        done.extend(boundary.iter().copied());
247
        // Iterative post-order DFS.
2481363×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2493536×
        while let Some((h, expanded)) = stack.pop() {
2502659×
            if done.contains(&h) {
251469×
                continue;
2522190×
            }
2532190×
            if !self.store.has(&h) {
2540×
                return fail(format!("change {} is not in this repository", h.short(12)));
2552190×
            }
2562190×
            if expanded {
2571095×
                done.insert(h);
2581095×
                out.push(h);
2591095×
                continue;
2601095×
            }
2611095×
            stack.push((h, true));
2621095×
            for d in self.store.get_change_meta(&h)?.deps {
263718×
                if !done.contains(&d) {
264201×
                    stack.push((d, false));
265517×
                }
266
            }
267
        }
268877×
        Ok(out)
269877×
    }
270
271
    /// Bundle changes (in the given dependency order) with their signatures,
272
    /// seals, identities, blobs, chunks.
273333×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
274333×
        self.bundle_of(changes, None, false, false)
275333×
    }
276
277
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2784×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2794×
        let mut out = Vec::new();
2804×
        for r in refs {
2814×
            let (ty, body) = match self.store.get(r) {
2824×
                Ok(x) => x,
2830×
                Err(StoreError::NotFound(_)) => continue,
2840×
                Err(e) => return Err(e.into()),
285
            };
2864×
            if ty == ObjectType::Blob {
2875×
                for c in Blob::decode(&body)?.chunks {
2885×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2895×
                        out.push((cty, cb));
2905×
                    }
291
                }
2920×
            }
2934×
            out.push((ty, body));
294
        }
2954×
        Ok(out)
2964×
    }
297
298
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
299
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
300
    ///
301
    /// This is what a server answers a fetch with, so it also carries what
302
    /// verifies the attestations it serves beside it (see
303
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
30455×
    pub fn bundle_for_filtered(
30555×
        &self,
30655×
        changes: &[ChangeHash],
30755×
        max_blob: Option<u64>,
30855×
    ) -> Result<Bundle> {
30955×
        self.bundle_of(changes, max_blob, false, true)
31055×
    }
311
312
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
313
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
314
    /// with their text blobs and chunks among the objects, so neither side
315
    /// decodes or encodes their text.
316373×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
317373×
        self.bundle_of(changes, max_blob, true, true)
318373×
    }
319
320
    /// The keys that signed the attestations this repository serves with
321
    /// its references: each bookmark's latest and each tag's. A fetch
322
    /// bundle carries their identities and certificates (spec §16.2), so a
323
    /// client can check an attestation whose signer signed none of the
324
    /// changes it receives, a delegate or a short-lived key that only
325
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
326
    /// list per reference, computed once per operation head and kept
327
    /// (every bookmark move and tag is an operation): a client sends one
328
    /// fetch per bookmark, and on a bucket store each signature list is a
329
    /// LIST request, so recomputing per fetch cost metalgear2 (145
330
    /// bookmarks) 14 s a fetch.
331428×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
332
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
333
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
334428×
        let key = (self.oxy.clone(), self.head_op()?.0);
335428×
        if let Some(keys) = SERVED
336428×
            .lock()
337428×
            .unwrap_or_else(|p| p.into_inner())
338428×
            .as_ref()
339428×
            .and_then(|m| m.get(&key))
340
        {
341137×
            return Ok(keys.clone());
342291×
        }
343291×
        let keys = self.attest_signers_now()?;
344291×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
345291×
        let map = served.get_or_insert_with(Default::default);
346
        // One entry per repository: an older operation head is never asked
347
        // for again once a newer one is current.
3485996×
        map.retain(|(oxy, _), _| *oxy != key.0);
349291×
        if map.len() >= 1024 {
3500×
            map.clear();
351291×
        }
352291×
        map.insert(key, keys.clone());
353291×
        Ok(keys)
354428×
    }
355
356291×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
357291×
        let view = self.view()?;
358291×
        let pointers = view
359291×
            .bookmarks
360291×
            .keys()
361301×
            .map(|b| self.ref_attest_path(b))
362291×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
363291×
        let mut keys = BTreeSet::new();
364320×
        for p in pointers {
365320×
            let Ok(text) = fs::read_to_string(&p) else {
366262×
                continue;
367
            };
36858×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3690×
                continue;
370
            };
37158×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
372
        }
373291×
        Ok(keys)
374291×
    }
375
376
    /// `serving`: a fetch's answer, which carries the identities and
377
    /// certificates of [`Repo::served_attest_signers`] too.
378761×
    fn bundle_of(
379761×
        &self,
380761×
        changes: &[ChangeHash],
381761×
        max_blob: Option<u64>,
382761×
        raw: bool,
383761×
        serving: bool,
384761×
    ) -> Result<Bundle> {
385761×
        let mut bundle = Bundle::default();
386761×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
387761×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3881264×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3891264×
            if !r.is_zero() && self.store.has(r) {
390375×
                objects.insert(*r);
391889×
            }
3921264×
        };
3931012×
        for h in changes {
394
            // Raw: the stored bytes, and a skeleton for the rest.
3951012×
            let (c, encoded) = if raw {
396548×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
397548×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3985022×
                for t in texts {
3995022×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
4003×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4013×
                        objects.insert(r);
4023×
                        objects.extend(blob.chunks);
4035019×
                    }
404
                }
405548×
                (skel, Some(bytes))
406
            } else {
407464×
                (self.store.get_change(h)?, None)
408
            };
4091012×
            let sigs = self.store.signatures(h)?;
4101012×
            add_object(&c.author, &mut objects);
4111012×
            for s in &sigs {
41237×
                add_object(&s.key, &mut objects);
41337×
            }
4146020×
            for e in &c.edits {
4156020×
                if let Edit::Replace { old, new, .. } = e {
41614×
                    for b in [old, new].into_iter().flatten() {
41714×
                        if self.store.has(b) {
41814×
                            if let Ok(blob) =
41914×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
420
                            {
42114×
                                if max_blob.is_some_and(|m| blob.length > m) {
4224×
                                    continue;
42310×
                                }
42410×
                                objects.insert(*b);
42510×
                                objects.extend(blob.chunks.iter().copied());
4260×
                            }
4270×
                        }
428
                    }
4296008×
                }
430
            }
4311012×
            for s in self.store.seals_for(h)? {
432107×
                seals.insert(s);
433107×
            }
4341012×
            match encoded {
435548×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
436464×
                None => {
437464×
                    bundle.changes.push((c, sigs));
438464×
                    bundle.hashes.push(*h);
439464×
                }
440
            }
441
        }
442761×
        for r in seals {
443102×
            let attest = self.store.get_attest(&r)?;
444102×
            let sigs = self.store.signatures(&r)?;
445102×
            for s in &sigs {
446102×
                add_object(&s.key, &mut objects);
447102×
            }
448102×
            bundle.attests.push(SignedAttest { attest, sigs });
449
        }
450761×
        let signers: Vec<KeyId> = if serving {
451428×
            let signers = self.served_attest_signers()?;
452428×
            for k in &signers {
453113×
                add_object(k, &mut objects);
454113×
            }
455428×
            signers.into_iter().collect()
456
        } else {
457333×
            Vec::new()
458
        };
459761×
        for r in objects {
460221×
            let (ty, body) = self.store.get(&r)?;
461221×
            bundle.objects.push((ty, body));
462
        }
463761×
        self.attach_certificates_for(&mut bundle, &signers)?;
464761×
        Ok(bundle)
465761×
    }
466
467
    /// Add the certificates of short-lived keys that signed what `bundle`
468
    /// carries, and their issuers' identities, so a receiver can tell who
469
    /// they stand for (spec §14.7). `also` names more signers (a reference
470
    /// attestation sent beside the bundle).
471882×
    pub(crate) fn attach_certificates_for(
472882×
        &self,
473882×
        bundle: &mut Bundle,
474882×
        also: &[KeyId],
475882×
    ) -> Result<()> {
476882×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
477882×
        keys.extend(
478882×
            bundle
479882×
                .changes
480882×
                .iter()
481882×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
482
        );
483882×
        keys.extend(
484882×
            bundle
485882×
                .raw_changes
486882×
                .iter()
487882×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
488
        );
489882×
        keys.extend(
490882×
            bundle
491882×
                .attests
492882×
                .iter()
493882×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
494
        );
495882×
        for k in keys {
496340×
            let Some(r) = self.store.certificate_of(&k)? else {
497291×
                continue;
498
            };
49949×
            let cert = self.store.get_certificate(&r)?;
50049×
            if bundle
50149×
                .certificates
50249×
                .iter()
50349×
                .any(|c| c.cert.hash() == cert.cert.hash())
504
            {
50512×
                continue;
50637×
            }
50774×
            for id in [&k, &cert.cert.issuer] {
50874×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
50974×
                    if !bundle
51074×
                        .objects
51174×
                        .iter()
512139×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
51335×
                    {
51435×
                        bundle.objects.push((ObjectType::Identity, body));
51539×
                    }
5160×
                }
517
            }
51837×
            bundle.certificates.push(cert);
519
        }
520882×
        Ok(())
521882×
    }
522
523
    /// Keep the certificates a bundle brings once each verifies with the
524
    /// identity of the issuer it names; one that does not refuses the bundle.
525802×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
526802×
        for c in certs {
52736×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5280×
                RepoError::Msg(format!(
5290×
                    "a certificate names issuer {}, whose identity did not come with it",
5300×
                    c.cert.issuer.short(12)
5310×
                ))
5320×
            })?;
53336×
            c.verify(&issuer)
53436×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
53536×
            self.store.put_identity(&c.cert.key)?;
53636×
            self.store.put_certificate(c)?;
537
        }
538802×
        Ok(())
539802×
    }
540
541
    /// A signer authorized for `reference` by what an issuer certified it
542
    /// as (spec §14.7): a short-lived key with a kept certificate that
543
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
544
    /// signer did not choose) and names a subject the policy grants.
54557×
    pub(crate) fn certified_authorized(
54657×
        &self,
54757×
        p: &crate::policy::Policy,
54857×
        signer: &KeyId,
54957×
        reference: &str,
55057×
        scope: Scope,
55157×
        at_ms: u64,
55257×
    ) -> bool {
55357×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5545×
            return false;
555
        };
55652×
        let Ok(c) = self.store.get_certificate(&r) else {
5570×
            return false;
558
        };
55952×
        let Some(issuer) = p
56052×
            .identity(&c.cert.issuer)
56152×
            .cloned()
56252×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
563
        else {
5640×
            return false;
565
        };
56652×
        c.verify(&issuer).is_ok()
56752×
            && c.cert.key_id() == *signer
56852×
            && c.cert.covers(scope, at_ms)
56942×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
57057×
    }
571
572
    /// Store a bundle's contents. With `strict`, every change must
573
    /// authenticate (signature or seal by its author or a delegate).
574799×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
575799×
        self.import_bundle_inner(bundle, strict, false)
576799×
    }
577
578
    /// Like `import_bundle`, accepting changes whose dependencies are absent
579
    /// (they join the shallow boundary).
5803×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5813×
        self.import_bundle_inner(bundle, strict, true)
5823×
    }
583
584802×
    fn import_bundle_inner(
585802×
        &self,
586802×
        bundle: &Bundle,
587802×
        strict: bool,
588802×
        shallow: bool,
589802×
    ) -> Result<Vec<ChangeHash>> {
590802×
        let batch = self.store.begin_batch()?;
591802×
        let result = self.import_bundle_batched(bundle, strict, shallow);
592802×
        batch.finish()?;
593800×
        result
594802×
    }
595
596802×
    fn import_bundle_batched(
597802×
        &self,
598802×
        bundle: &Bundle,
599802×
        strict: bool,
600802×
        shallow: bool,
601802×
    ) -> Result<Vec<ChangeHash>> {
602802×
        for (ty, _) in &bundle.objects {
6030×
            if !matches!(
604679×
                ty,
605
                ObjectType::Chunk
606
                    | ObjectType::Blob
607
                    | ObjectType::Identity
608
                    | ObjectType::State
609
                    | ObjectType::Checkpoint
610
            ) {
6110×
                return fail(format!("bundle may not carry {} objects", ty.name()));
612679×
            }
613
        }
614
        // All at once: in a large batch they are compressed on every core.
615802×
        let objects: Vec<(ObjectType, &[u8])> = bundle
616802×
            .objects
617802×
            .iter()
618802×
            .map(|(ty, body)| (*ty, body.as_slice()))
619802×
            .collect();
620802×
        self.store.put_many(&objects)?;
621802×
        self.adopt_certificates(&bundle.certificates)?;
622802×
        for sa in &bundle.attests {
623105×
            let r = self.store.put_attest(&sa.attest)?;
624105×
            for sig in &sa.sigs {
625105×
                self.store.put_signature(&r, sig)?;
626
            }
627105×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
628110×
                for h in hashes {
629110×
                    self.store.index_seal(h, &r)?;
630
                }
6310×
            }
632
        }
633
        // Each change's hash: from the bundle when its maker knew it, else
634
        // worked out once (for a change adding a whole tree, hashing is
635
        // chunking all its text).
636802×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
637793×
            bundle.hashes.clone()
638
        } else {
6399×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
640
        };
641802×
        let raw_hashes: Vec<ChangeHash> = bundle
642802×
            .raw_changes
643802×
            .iter()
644802×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
645802×
            .collect();
646802×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
647802×
        let boundary = self.boundary();
648802×
        let mut imported = Vec::new();
649
        // Changes as stored: checked, then stored as they are, their text
650
        // blobs having come with the objects.
651802×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
652549×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
653549×
            for d in &skel.deps {
654391×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
655
                {
6560×
                    return fail(format!(
657
                        "change {} depends on {}, which is neither stored nor in the bundle",
6580×
                        h.short(12),
6590×
                        d.short(12)
660
                    ));
661391×
                }
662
            }
6635023×
            for t in texts {
6645023×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6654×
                    if !self.store.has(&r) {
6661×
                        return fail(format!(
667
                            "change {} came without its text blob {}",
6681×
                            h.short(12),
6691×
                            r.short(12)
670
                        ));
6713×
                    }
6725019×
                }
673
            }
674548×
            self.store.put(ObjectType::Change, bytes)?;
675548×
            for sig in sigs {
67613×
                self.store.put_signature(&h, sig)?;
677
            }
678548×
            imported.push(h);
679
        }
680801×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
681491×
            for d in &c.deps {
682281×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
683
                {
6843×
                    return fail(format!(
685
                        "change {} depends on {}, which is neither stored nor in the bundle",
6863×
                        h.short(12),
6873×
                        d.short(12)
688
                    ));
689278×
                }
690
            }
691488×
            let stored = self.store.put_change(c)?;
692488×
            if stored != h {
6930×
                return fail(format!(
694
                    "change {} is not the change the bundle names",
6950×
                    h.short(12)
696
                ));
697488×
            }
698488×
            for sig in sigs {
69933×
                self.store.put_signature(&h, sig)?;
700
            }
701488×
            imported.push(h);
702
        }
703798×
        if strict {
70462×
            for h in &imported {
70538×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7064×
                    return fail(format!(
707
                        "change {} is not authenticated by its author",
7084×
                        h.short(12)
709
                    ));
71034×
                }
711
            }
712736×
        }
713794×
        Ok(imported)
714802×
    }
715
716
    /// Verify a reference attestation against an update it claims to describe.
717
    /// `allow_equal` lets a client re-read the attestation it already has; a
718
    /// server receiving a push requires a strictly greater serial.
719
    /// A reference attestation signed by a delegate of an identity the
720
    /// rule lists is authorized as that identity (spec §14.5): the identity
721
    /// named the delegate with the `refs` scope, still in force at `at_ms`
722
    /// (the attestation's wall time), and the policy names the identity.
723
    /// Revoked keys authorize nothing either way.
72471×
    pub(crate) fn delegate_authorized(
72571×
        &self,
72671×
        p: &crate::policy::Policy,
72771×
        signer: &KeyId,
72871×
        reference: &str,
72971×
        at_ms: u64,
73071×
    ) -> bool {
73171×
        if p.is_revoked(signer) {
7321×
            return false;
73370×
        }
73470×
        let Some(rule) = p.rule_for(reference) else {
7350×
            return false;
736
        };
73771×
        rule.keys.iter().any(|k| {
73871×
            !p.is_revoked(k)
73971×
                && p.identity(k)
74071×
                    .cloned()
74171×
                    .or_else(|| self.store.get_identity(k).ok())
74271×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
74371×
        })
74471×
    }
745
746
    /// A lasting attestation (a tag) signed by a key the policy has since
747
    /// rotated away from (spec §14.2) is authorized as the key that
748
    /// succeeded it: a key the rule lists reaches the signer through
749
    /// `previous` links, and the attestation is dated (`at_ms`) before the
750
    /// signer's successor was made, so a superseded key makes nothing new.
751
    /// Revoked keys authorize nothing.
75226×
    pub(crate) fn predecessor_authorized(
75326×
        &self,
75426×
        p: &crate::policy::Policy,
75526×
        signer: &KeyId,
75626×
        reference: &str,
75726×
        at_ms: u64,
75826×
    ) -> bool {
75926×
        if p.is_revoked(signer) {
7600×
            return false;
76126×
        }
76226×
        let Some(rule) = p.rule_for(reference) else {
7630×
            return false;
764
        };
76527×
        let identity = |k: &KeyId| {
76627×
            p.identity(k)
76727×
                .cloned()
76827×
                .or_else(|| self.store.get_identity(k).ok())
76927×
        };
77026×
        rule.keys.iter().any(|k| {
77126×
            if p.is_revoked(k) {
7720×
                return false;
77326×
            }
77426×
            let mut cur = identity(k);
77526×
            for _ in 0..32 {
77627×
                let Some(id) = cur else {
7770×
                    return false;
778
                };
7791×
                match id.previous {
7806×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7811×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
78221×
                    _ => return false,
783
                }
784
            }
7850×
            false
78626×
        })
78726×
    }
788
789104×
    fn check_ref_attest(
790104×
        &self,
791104×
        sa: &SignedAttest,
792104×
        name: &str,
793104×
        old_state: &ObjectRef,
794104×
        new_state: &ObjectRef,
795104×
        last_serial: Option<u64>,
796104×
        allow_equal: bool,
797104×
    ) -> std::result::Result<u64, String> {
798102×
        let serial =
799104×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
800102×
        self.verify_attest_signature(sa)?;
801102×
        Ok(serial)
802104×
    }
803
804
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
805
    /// attestation describes this update of this repository with a serial
806
    /// past the last seen.
807174×
    fn check_ref_attest_body(
808174×
        &self,
809174×
        sa: &SignedAttest,
810174×
        name: &str,
811174×
        old_state: &ObjectRef,
812174×
        new_state: &ObjectRef,
813174×
        last_serial: Option<u64>,
814174×
        allow_equal: bool,
815174×
    ) -> std::result::Result<u64, String> {
816
        let AttestBody::Ref {
817174×
            name: n,
818174×
            old_state: o,
819174×
            new_state: nw,
820174×
            serial,
821174×
        } = &sa.attest.body
822
        else {
8230×
            return Err("attestation is not a ref attestation".into());
824
        };
825174×
        if n != name || o != old_state || nw != new_state {
8261×
            return Err("attestation does not describe this update".into());
827173×
        }
828173×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8290×
            return Err("attestation is for a different repository".into());
830173×
        }
831173×
        if let Some(last) = last_serial {
83291×
            if *serial < last || (*serial == last && !allow_equal) {
8331×
                return Err(format!(
8341×
                    "attestation serial {serial} is not greater than the last seen {last}"
8351×
                ));
83690×
            }
83782×
        }
838172×
        Ok(*serial)
839174×
    }
840
841
    /// An attestation's first signature verifies with its signer's
842
    /// identity, which must be stored here.
843172×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
844172×
        let r = sa.attest.hash();
845172×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
846172×
        let id = self
847172×
            .store
848172×
            .get_identity(&sig.key)
849172×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
850166×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
851172×
    }
852
853
    /// Accept a push (spec §16.4). Without a trust policy every repository
854
    /// is unverified, so unsigned changes and unattested updates are accepted;
855
    /// attestations that are present must still be valid. With a policy,
856
    /// every change and update is checked against it. A newer policy in the
857
    /// push is applied first when it is signed by the current roots.
858306×
    pub fn receive_push(
859306×
        &self,
860306×
        bundle: Bundle,
861306×
        updates: Vec<RefUpdate>,
862306×
        policy: Option<SignedPolicy>,
863306×
        tags: Vec<crate::protocol::TagRef>,
864306×
    ) -> Result<Vec<RefResult>> {
865306×
        Ok(self
866306×
            .receive_push_report(bundle, updates, policy, tags)?
867
            .results)
868306×
    }
869
870
    /// `receive_push` with what a host wants to log: each accepted
871
    /// reference's old and new state and heads, and the changes this push
872
    /// stored (hub spec §6.12).
873350×
    pub fn receive_push_report(
874350×
        &self,
875350×
        bundle: Bundle,
876350×
        updates: Vec<RefUpdate>,
877350×
        policy: Option<SignedPolicy>,
878350×
        tags: Vec<crate::protocol::TagRef>,
879350×
    ) -> Result<PushReport> {
880
        // Updates are checked against the head as it is now, not as this
881
        // handle first read it (oxygenhub#249): another push may have
882
        // landed since.
883350×
        self.refresh()?;
884350×
        let mut report = PushReport::default();
885350×
        let results = &mut report.results;
886350×
        if let Some(sp) = policy {
88735×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
88833×
                Ok(()) => {
88933×
                    results.push(RefResult {
89033×
                        name: "policy".into(),
89133×
                        ok: true,
89233×
                        reason: format!("serial {}", sp.policy.serial),
89333×
                    });
89433×
                }
8952×
                Err(e) => {
8962×
                    results.push(RefResult {
8972×
                        name: "policy".into(),
8982×
                        ok: false,
8992×
                        reason: e,
9002×
                    });
9012×
                    for u in updates {
9020×
                        results.push(RefResult {
9030×
                            name: u.name,
9040×
                            ok: false,
9050×
                            reason: "policy update was rejected".into(),
9060×
                        });
9070×
                    }
9082×
                    return Ok(report);
909
                }
910
            }
911315×
        }
912348×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
913
        // A push of objects alone (one batch of a long history, oxygen#95)
914
        // names no reference: its outcome is reported as `objects`.
915348×
        let objects_only = updates.is_empty() && tags.is_empty();
916348×
        match self.import_bundle(&bundle, policy.is_some()) {
917342×
            Ok(imported) => {
918342×
                if objects_only {
9197×
                    results.push(RefResult {
9207×
                        name: OBJECTS_RESULT.into(),
9217×
                        ok: true,
9227×
                        reason: format!("{} changes stored", imported.len()),
9237×
                    });
924335×
                }
925342×
                report.imported = imported;
926
            }
9276×
            Err(e) => {
9286×
                if objects_only {
9290×
                    results.push(RefResult {
9300×
                        name: OBJECTS_RESULT.into(),
9310×
                        ok: false,
9320×
                        reason: e.to_string(),
9330×
                    });
9346×
                }
9356×
                for u in updates {
9366×
                    results.push(RefResult {
9376×
                        name: u.name,
9386×
                        ok: false,
9396×
                        reason: e.to_string(),
9406×
                    });
9416×
                }
9426×
                return Ok(report);
943
            }
944
        }
945342×
        let (op_ref, op) = self.head_op()?;
946342×
        let mut view = op.view.clone();
947342×
        let mut names = Vec::new();
948342×
        for u in updates {
949333×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
950333×
            let (ok, reason) = match outcome {
951305×
                Ok(()) => (true, String::new()),
95228×
                Err(e) => (false, e),
953
            };
954333×
            if ok {
955305×
                names.push(u.name.clone());
956305×
                let heads = self
957305×
                    .store
958305×
                    .get_state(&u.new_state)
959305×
                    .map(|s| s.heads)
960305×
                    .unwrap_or_default();
961305×
                report.updated.push(RefUpdated {
962305×
                    name: u.name.clone(),
963305×
                    old_state: u.old_state,
964305×
                    new_state: u.new_state,
965305×
                    heads,
966305×
                });
96728×
            }
968333×
            results.push(RefResult {
969333×
                name: u.name,
970333×
                ok,
971333×
                reason,
972333×
            });
973
        }
974342×
        for t in &tags {
97516×
            let name = format!("tags/{}", t.name);
97616×
            let new = !view.tags.contains_key(&t.name);
97716×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
978
                Ok(()) => {
979
                    // A tag new here is an update too, so a hub can start
980
                    // its pipeline's tag jobs (oxygenflow#24); one it
981
                    // already had, sent again, is not.
98212×
                    if new {
98311×
                        report.updated.push(RefUpdated {
98411×
                            name: name.clone(),
98511×
                            old_state: ObjectRef::ZERO,
98611×
                            new_state: t.state,
98711×
                            heads: t.heads.clone(),
98811×
                        });
98911×
                    }
99012×
                    names.push(name.clone());
99112×
                    results.push(RefResult {
99212×
                        name,
99312×
                        ok: true,
99412×
                        reason: String::new(),
99512×
                    });
996
                }
9974×
                Err(e) => results.push(RefResult {
9984×
                    name,
9994×
                    ok: false,
10004×
                    reason: e.reason,
10014×
                }),
1002
            }
1003
        }
1004342×
        if !names.is_empty() {
1005306×
            self.record_op(
1006306×
                &[op_ref],
1007306×
                &format!("push received: {}", names.join(" ")),
1008306×
                view,
10093×
            )?;
101036×
        }
1011339×
        Ok(report)
1012350×
    }
1013
1014
    /// Check an update's attestation against the latest one for its
1015
    /// reference and store it as the new latest. Failures say what was
1016
    /// being done, for which reference, so a refused push can be diagnosed
1017
    /// from its reason alone.
1018104×
    fn record_update_attest(
1019104×
        &self,
1020104×
        u: &RefUpdate,
1021104×
        sa: &SignedAttest,
1022104×
    ) -> std::result::Result<(), String> {
1023104×
        let name = &u.name;
1024104×
        let last = self
1025104×
            .latest_ref_attest(name)
1026104×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1027104×
            .and_then(|(_, a)| match a.attest.body {
102864×
                AttestBody::Ref { serial, .. } => Some(serial),
10290×
                _ => None,
103064×
            });
1031104×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1032102×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1033102×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1034101×
        for sig in &sa.sigs {
1035101×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1036
        }
1037101×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1038
        // Signed by a short-lived key: a host records when it accepted it.
103998×
        let certified = sa
104098×
            .sigs
104198×
            .first()
104298×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
104398×
        if certified {
10446×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
104592×
        }
104698×
        Ok(())
1047104×
    }
1048
1049
    /// Record that this host accepted attestation `r` now, signed with its
1050
    /// acceptor key (spec §14.7); nothing without one.
105111×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
105211×
        let Some(acceptor) = &self.acceptor else {
10537×
            return Ok(());
1054
        };
10554×
        let (id, sk) = (&acceptor.0, &acceptor.1);
10564×
        let attest = Attest {
10574×
            repo: self.id()?,
10584×
            hlc: Hlc::now(),
10594×
            body: AttestBody::Accepted { attest: *r },
1060
        };
10614×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
10624×
        self.store.put_identity(id)?;
10634×
        let a = self.store.put_attest(&attest)?;
10644×
        self.store.put_signature(&a, &sig)?;
10654×
        self.store.index_add_pub("accepted", r, &a)?;
10664×
        Ok(())
106711×
    }
1068
1069
    /// The host's acceptance of attestation `r`, if one was recorded.
1070217×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1071217×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1072196×
            return Ok(None);
1073
        };
1074
        Ok(Some(SignedAttest {
107521×
            attest: self.store.get_attest(&a)?,
107621×
            sigs: self.store.signatures(&a)?,
1077
        }))
1078217×
    }
1079
1080
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1081
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1082
    /// signer's certificate and accepts `sa`; else the attestation's own
1083
    /// time, which the signer chose.
108431×
    pub(crate) fn certified_time(
108531×
        &self,
108631×
        signer: &KeyId,
108731×
        sa: &SignedAttest,
108831×
        accepted: Option<&SignedAttest>,
108931×
    ) -> u64 {
109031×
        self.issuer_acceptance(signer, sa, accepted)
109131×
            .unwrap_or(sa.attest.hlc.wall_ms)
109231×
    }
1093
1094
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1095
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
109691×
    pub(crate) fn issuer_acceptance(
109791×
        &self,
109891×
        signer: &KeyId,
109991×
        sa: &SignedAttest,
110091×
        accepted: Option<&SignedAttest>,
110191×
    ) -> Option<u64> {
110291×
        let acc = accepted?;
110346×
        let c = self.store.certificate_of(signer).ok().flatten()?;
110446×
        let cert = self.store.get_certificate(&c).ok()?;
110546×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11060×
            return None;
1107
        };
110846×
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
110943×
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
111043×
        (*attest == sa.attest.hash()
111142×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
111243×
        .then_some(acc.attest.hlc.wall_ms)
111391×
    }
1114
1115
    /// Keep an acceptance this repository was given for attestation `r`
1116
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1117
    /// what it accepts.
11189×
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
11199×
        let a = self.store.put_attest(&acc.attest)?;
112011×
        for sig in &acc.sigs {
112111×
            self.store.put_signature(&a, sig)?;
1122
        }
11239×
        self.store.index_add_pub("accepted", r, &a)?;
11249×
        Ok(())
11259×
    }
1126
1127
    /// A fetched bookmark's attestation by a signer the policy does not
1128
    /// list itself: a delegate or a short-lived key, whose authority
1129
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1130
    /// attestation's integrated time when the host's log gives one; else
1131
    /// as before, at the host's acceptance for a certified signer, when it
1132
    /// countersigned one, or at the attestation's own time, and said so
1133
    /// when the host keeps a log. Failing at the integrated time but not
1134
    /// as before is a note while logs are new; a large gap between the
1135
    /// claimed and the integrated time is a note.
1136
    #[allow(clippy::too_many_arguments)]
113727×
    pub(crate) fn authorize_in_time(
113827×
        &self,
113927×
        p: &crate::policy::Policy,
114027×
        remote_name: &str,
114127×
        r: &crate::protocol::RemoteRef,
114227×
        sa: &SignedAttest,
114327×
        signer: &KeyId,
114427×
        log: &super::transparency::LogCheck,
114527×
        notes: &mut Vec<String>,
114627×
    ) -> Result<()> {
1147
        use super::transparency::{gap_note, judge, Timed};
114827×
        let own = sa.attest.hlc.wall_ms;
114927×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
115027×
        let time = log.time_of(&r.name);
115129×
        let check = |t_delegate: u64, t_cert: u64| {
115229×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
115327×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
115429×
        };
115527×
        let before = if at != own {
11567×
            "the host's acceptance"
1157
        } else {
115820×
            "the time it claims"
1159
        };
116027×
        let what = format!("{remote_name}/{}", r.name);
116127×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1162
            Timed::Refused => {
11631×
                return fail(format!(
1164
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
11651×
                    signer.short(12)
1166
                ))
1167
            }
11683×
            Timed::Integrated => {}
11691×
            Timed::Disagrees => notes.push(format!(
1170
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
11711×
                signer.short(12),
11721×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1173
            )),
11741×
            Timed::Fallback if log.kept => notes.push(format!(
1175
                "{what}: {} checked at {before}, not at a witnessed time: {}",
11761×
                signer.short(12),
11771×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1178
            )),
117921×
            Timed::Fallback => {}
1180
        }
118126×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
11822×
            notes.push(format!("{what}'s attestation {n}"));
118324×
        }
118426×
        Ok(())
118527×
    }
1186
1187
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1188
    /// at `old_state`, is never the bookmark a non-bare repository has
1189
    /// checked out (a bare one's default is its host's to protect, see
1190
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1191
    /// an attestation by a key that may update it.
1192
    /// The deletion's attestation stays the bookmark's latest, so an older
1193
    /// one cannot be replayed to bring it back.
11943×
    fn apply_deletion(
11953×
        &self,
11963×
        view: &mut View,
11973×
        u: &RefUpdate,
11983×
        policy: Option<&crate::policy::Policy>,
11993×
    ) -> std::result::Result<(), String> {
12003×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
12010×
            return Err(format!("no bookmark {:?} to delete", u.name));
1202
        };
12033×
        if current != u.old_state {
12040×
            return Err("stale: the remote bookmark has moved; pull first".into());
12053×
        }
12063×
        if !self.is_bare() && u.name == self.config.bookmark {
12071×
            return Err(format!(
12081×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
12091×
                u.name
12101×
            ));
12112×
        }
12122×
        if let Some(p) = policy {
12130×
            let Some(sa) = &u.attestation else {
12140×
                return Err(format!(
12150×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12160×
                    u.name
12170×
                ));
1218
            };
12190×
            let signer = sa
12200×
                .sigs
12210×
                .first()
12220×
                .map(|s| s.key)
12230×
                .ok_or("attestation carries no signature")?;
1224
            // Received now: the receiver's own clock is the trusted time.
12250×
            let now = Hlc::now().wall_ms;
12260×
            if !p.authorizes(&signer, &u.name)
12270×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12280×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1229
            {
12300×
                return Err(format!(
12310×
                    "key {} may not delete {:?} under this repository's policy",
12320×
                    signer.short(12),
12330×
                    u.name
12340×
                ));
12350×
            }
12362×
        }
12372×
        if let Some(sa) = &u.attestation {
12381×
            self.record_update_attest(u, sa)?;
12391×
        }
12402×
        view.bookmarks.remove(&u.name);
12412×
        Ok(())
12423×
    }
1243
1244333×
    fn apply_update(
1245333×
        &self,
1246333×
        view: &mut View,
1247333×
        u: &RefUpdate,
1248333×
        policy: Option<&crate::policy::Policy>,
1249333×
    ) -> std::result::Result<(), String> {
1250333×
        if u.name == "policy" {
12510×
            return Err(
12520×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
12530×
            );
1254333×
        }
1255333×
        let empty = self
1256333×
            .store
1257333×
            .put_state(&StateObject::new(vec![]))
1258333×
            .map_err(|e| e.to_string())?;
1259333×
        if u.new_state.is_zero() {
12603×
            return self.apply_deletion(view, u, policy);
1261330×
        }
1262330×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1263330×
        if current != u.old_state {
12648×
            return Err("stale: the remote bookmark has moved; pull first".into());
1265322×
        }
1266322×
        let new_state = self
1267322×
            .store
1268322×
            .get_state(&u.new_state)
1269322×
            .map_err(|_| "new state object is missing".to_string())?;
1270618×
        for h in &new_state.heads {
1271618×
            if !self.store.has(h) {
12721×
                return Err(format!("head {} is missing", h.short(12)));
1273617×
            }
1274
        }
1275321×
        if !u.force {
1276320×
            let old_heads = self
1277320×
                .store
1278320×
                .get_state(&current)
1279320×
                .map_err(|e| e.to_string())?
1280
                .heads;
1281320×
            let closure = self
1282320×
                .closure_in_store(&new_state.heads)
1283320×
                .map_err(|e| e.to_string())?;
1284335×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
12851×
                return Err(format!(
12861×
                    "not a fast-forward: current head {} would be dropped (use --force)",
12871×
                    h.short(12)
12881×
                ));
1289319×
            }
12901×
        }
1291320×
        if let Some(p) = policy {
129257×
            let Some(sa) = &u.attestation else {
12931×
                return Err(format!(
12941×
                    "{:?} requires a signed reference attestation under this repository's policy",
12951×
                    u.name
12961×
                ));
1297
            };
129856×
            let signer = sa
129956×
                .sigs
130056×
                .first()
130156×
                .map(|s| s.key)
130256×
                .ok_or("attestation carries no signature")?;
1303
            // Received now: the receiver's own clock is the trusted time.
130456×
            let now = Hlc::now().wall_ms;
130556×
            if !p.authorizes(&signer, &u.name)
130619×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
130716×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1308
            {
130910×
                return Err(format!(
131010×
                    "key {} may not update {:?} under this repository's policy",
131110×
                    signer.short(12),
131210×
                    u.name
131310×
                ));
131446×
            }
131546×
            let old_heads = self
131646×
                .store
131746×
                .get_state(&current)
131846×
                .map_err(|e| e.to_string())?
1319
                .heads;
132046×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1321263×
        }
1322309×
        if let Some(sa) = &u.attestation {
1323103×
            self.record_update_attest(u, sa)?;
1324206×
        }
1325303×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1326303×
        Ok(())
1327333×
    }
1328
1329
    // ------------------------------------------------------------ client side
1330
13311476×
    fn remote_url(&self, name: &str) -> Result<String> {
13321476×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13333×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13343×
            RepoError::Msg(match names.as_slice() {
13353×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
13361×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1337
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
13381×
                    names.join(", "),
13391×
                    names[0],
13401×
                    names[0]
1341
                ),
13420×
                _ => format!(
1343
                    "no remote named {name:?}; this repository has {}",
13440×
                    names.join(", ")
1345
                ),
1346
            })
13473×
        })
13481476×
    }
1349
1350
    /// Refuse a remote that is another repository. An **unbound** remote
1351
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1352
    /// for pushes, which bind it to this repository's id (spec §16.1).
1353804×
    fn check_remote_id(
1354804×
        &self,
1355804×
        remote: &dyn crate::protocol::Remote,
1356804×
        remote_name: &str,
1357804×
        allow_unbound: bool,
1358804×
    ) -> Result<()> {
1359804×
        let theirs = remote.repo_id()?;
1360803×
        if theirs == self.id()? {
1361776×
            return Ok(());
136227×
        }
136327×
        if theirs == crate::protocol::UNBOUND_ID {
136424×
            if allow_unbound {
136523×
                return Ok(());
13661×
            }
13671×
            return fail(format!(
1368
                "remote {remote_name:?} is empty and unbound: push to it first"
1369
            ));
13703×
        }
13713×
        fail(format!(
1372
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1373
        ))
1374804×
    }
1375
1376
    /// Credentials and trust for a remote: `remote.<name>.token` and
1377
    /// `remote.<name>.ca`, else the defaults for its URL
1378
    /// ([`Repo::fill_credentials`]).
13791098×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
13801098×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
13811098×
        let mut options = RemoteOptions {
13821098×
            repo_id: self.id().ok(),
13831098×
            token: self.config.remote_tokens.get(name).cloned(),
13841098×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
13851098×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
13861098×
            ..RemoteOptions::default()
13871098×
        };
13881098×
        self.fill_credentials(&url, &mut options);
13891098×
        options
13901098×
    }
1391
1392
    /// The user's credential store (`credentials.toml` beside the user
1393
    /// configuration file).
13941119×
    pub fn credentials(&self) -> crate::credentials::Credentials {
13951119×
        crate::credentials::Credentials::at(
13961119×
            self.user_config
13971119×
                .parent()
13981119×
                .map(Path::to_path_buf)
13991119×
                .unwrap_or_else(default_home),
1400
        )
14011119×
    }
1402
1403
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1404
    /// then the user's credential store for its hub, then a remote on the
1405
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1406
    /// When the token is not this remote's own or the environment's, the
1407
    /// other tokens enclosing checkouts hold for the hub are kept to try
1408
    /// if it is refused: a stale stored login must not hide a parent's
1409
    /// good token (oxygen#112).
14101120×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14111120×
        if options.token.is_some() && options.ca.is_some() {
14121×
            return;
14131119×
        }
14141119×
        let explicit =
14151119×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14161119×
        let stored = self.credentials().options_for(url);
14171119×
        options.token = options.token.take().or(stored.token);
14181119×
        options.ca = options.ca.take().or(stored.ca);
14191119×
        let enclosing = self.enclosing_credentials(url);
14201119×
        if options.token.is_none() {
14211109×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
142210×
        }
14231119×
        if options.ca.is_none() {
14241104×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
142515×
        }
14261119×
        if !explicit {
14271112×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
14285×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
14292×
                    options.fallback_tokens.push(t);
14303×
                }
1431
            }
14327×
        }
14331120×
    }
1434
1435
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1436
    /// checkouts, nearest first.
14371119×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
14381119×
        let mut out = Vec::new();
14391119×
        let Some(hub) = crate::credentials::hub_of(url) else {
1440965×
            return out;
1441
        };
1442154×
        let mut at = self.root.parent();
1443624×
        while let Some(dir) = at {
1444470×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14450×
                break;
1446
            };
1447470×
            for (key, remote_url) in &cfg {
144815×
                let Some(name) = key
144915×
                    .strip_prefix("remote.")
145015×
                    .and_then(|k| k.strip_suffix(".url"))
1451
                else {
14527×
                    continue;
1453
                };
14548×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
14551×
                    continue;
14567×
                }
14577×
                out.push((
14587×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
14597×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
14607×
                ));
1461
            }
1462470×
            at = dir.parent();
1463
        }
1464154×
        out
14651119×
    }
1466
1467
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1468
    /// no changes and no reference updates, which the receiver stores.
14690×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
14700×
        let remote = self.open_named_remote(remote_name)?;
14710×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
14720×
        let mut bundle = Bundle::default();
14730×
        for r in seals {
14740×
            let attest = self.store.get_attest(r)?;
14750×
            let sigs = self.store.signatures(r)?;
14760×
            bundle
14770×
                .attests
14780×
                .push(crate::protocol::SignedAttest { attest, sigs });
1479
        }
14800×
        let results = remote.push(bundle, vec![], None, vec![])?;
14810×
        if let Some(r) = results.iter().find(|r| !r.ok) {
14820×
            return fail(format!("{}: {}", r.name, r.reason));
14830×
        }
14840×
        Ok(())
14850×
    }
1486
1487
    /// The remote whose URL starts with `base` (a hub), if configured.
14884×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
14894×
        let base = base.trim_end_matches('/');
14904×
        self.config
14914×
            .remotes
14924×
            .iter()
14934×
            .find(|(_, url)| url.trim_end_matches('/') == base)
14944×
            .map(|(name, _)| name.clone())
14954×
    }
1496
1497
    /// Open a remote by name or, failing that, by URL with the default
1498
    /// credentials (see [`Repo::credentials_for`]).
14990×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15000×
        if let Some(name) = self.remote_for_url(url) {
15010×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15020×
        }
15030×
        let options = RemoteOptions {
15040×
            repo_id: self.id().ok(),
15050×
            ..self.credentials_for(url)
15060×
        };
15070×
        Ok((url.to_string(), open_remote(url, &options)?))
15080×
    }
1509
1510
    /// Credentials for a URL: those of the configured remote with that
1511
    /// URL, else the environment's.
15124×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
15134×
        match self.remote_for_url(url) {
15144×
            Some(name) => self.remote_options(&name),
15150×
            None => RemoteOptions {
15160×
                repo_id: self.id().ok(),
15170×
                ..self.credentials_for(url)
15180×
            },
1519
        }
15204×
    }
1521
15221081×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15231081×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15241081×
    }
1525
1526212×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1527212×
        self.oxy
1528212×
            .join("remotes")
1529212×
            .join(remote)
1530212×
            .join(format!("{bookmark}.serial"))
1531212×
    }
1532
153370×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
153470×
        fs::read_to_string(self.serial_path(remote, bookmark))
153570×
            .ok()
153670×
            .and_then(|s| s.trim().parse().ok())
153770×
    }
1538
1539142×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1540142×
        let p = self.serial_path(remote, bookmark);
1541142×
        fs::create_dir_all(p.parent().unwrap())?;
1542142×
        write_atomic(&p, serial.to_string().as_bytes())
1543142×
    }
1544
1545463×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1546463×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1547463×
    }
1548
1549
    /// The highest policy serial `remote` has ever presented.
1550395×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1551395×
        fs::read_to_string(self.policy_serial_path(remote))
1552395×
            .ok()
1553395×
            .and_then(|s| s.trim().parse().ok())
1554395×
    }
1555
155668×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
155768×
        let p = self.policy_serial_path(remote);
155868×
        fs::create_dir_all(p.parent().unwrap())?;
155968×
        write_atomic(&p, serial.to_string().as_bytes())
156068×
    }
1561
156227×
    fn lazy_dir(&self) -> PathBuf {
156327×
        self.oxy.join("lazy")
156427×
    }
1565
1566
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
15674×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
15684×
        fs::create_dir_all(self.lazy_dir())?;
15694×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
15704×
    }
1571
1572
    /// Which remote promised an absent blob, if any.
157315×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
157415×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
157515×
            .ok()
157615×
            .map(|s| s.trim().to_string())
157715×
    }
1578
1579
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
15804×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
15814×
        let Some(remote_name) = self.lazy_remote(blob) else {
15820×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1583
        };
15844×
        let remote = self.open_named_remote(&remote_name)?;
15854×
        let objects = remote.objects(&[*blob])?;
15869×
        for (ty, body) in objects {
15879×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
15889×
                self.store.put(ty, &body)?;
15890×
            }
1590
        }
15914×
        if !self.store.has(blob) {
15920×
            return fail(format!(
1593
                "{remote_name} did not send blob {}",
15940×
                blob.short(12)
1595
            ));
15964×
        }
15974×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
15984×
        Ok(())
15994×
    }
1600
1601
    /// After importing from `remote`, record every blob the changes reference
1602
    /// that the store lacks as lazily available from that remote.
16034×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
16044×
        let mut n = 0;
16054×
        for h in changes {
16064×
            let c = self.store.get_change(h)?;
160713×
            for e in &c.edits {
160813×
                if let Edit::Replace { old, new, .. } = e {
16096×
                    for b in [old, new].into_iter().flatten() {
16106×
                        if !self.store.has(b) {
16114×
                            self.register_lazy(b, remote)?;
16124×
                            n += 1;
16132×
                        }
1614
                    }
16157×
                }
1616
            }
1617
        }
16184×
        Ok(n)
16194×
    }
1620
1621
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1622395×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1623395×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1624536×
        for st in view
1625395×
            .bookmarks
1626395×
            .values()
1627395×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1628
        {
1629536×
            if let Ok(s) = self.store.get_state(st) {
1630536×
                have.extend(s.heads);
1631536×
            }
1632
        }
1633395×
        have.extend(view.workspaces.values().copied());
1634395×
        Ok(have.into_iter().collect())
1635395×
    }
1636
1637
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1638401×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1639401×
        let remote = self.open_named_remote(remote_name)?;
1640398×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1641396×
        let resp = remote.refs()?;
1642
        // The host's transparency log (spec §14.8): a fork fails here.
1643395×
        let log = self.check_log(
1644395×
            &self.remote_url(remote_name)?,
1645395×
            self.config.remote_cas.get(remote_name).map(Path::new),
1646395×
            &resp,
16470×
        )?;
1648395×
        let mut log_notes = log.notes.clone();
1649
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1650
        // and signed by roots we trust, or on first contact. A remote that
1651
        // once presented a policy may never present none or an older one:
1652
        // that is a downgrade. A remote that never presented one is
1653
        // unverified, and this fetch is checked only as far as possible.
1654395×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1655395×
        let seen = self.remote_policy_serial(remote_name);
1656395×
        let mut unverified = false;
1657395×
        match &resp.policy {
165835×
            Some(sp) => {
165935×
                if seen.is_some_and(|s| sp.policy.serial < s) {
16600×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
166135×
                }
166213×
                match &local_policy {
166313×
                    Some(l) if sp.policy.serial < l.serial => {}
166413×
                    Some(l) if sp.policy.serial == l.serial => {
16659×
                        if sp.policy.hash() != l.hash() {
16660×
                            return fail(format!(
1667
                                "{remote_name} presents a different policy with the same serial {}",
1668
                                l.serial
1669
                            ));
16709×
                        }
1671
                    }
1672
                    _ => {
167326×
                        self.adopt_policy_chain(
167426×
                            &resp.history,
167526×
                            sp,
167626×
                            &format!("oxy fetch {remote_name}"),
1677
                        )
167826×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1679
                    }
1680
                }
168135×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1682
            }
1683
            None => {
1684360×
                if seen.is_some() {
16850×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1686360×
                }
1687360×
                unverified = true;
1688
            }
1689
        }
1690395×
        let policy = if unverified {
1691360×
            None
1692
        } else {
169335×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1694
        };
1695395×
        let (op_ref, op) = self.head_op()?;
1696395×
        let mut view = op.view.clone();
1697395×
        let have = self.known_heads(&view)?;
1698395×
        let mut report = Vec::new();
1699395×
        let mut skipped = Vec::new();
1700395×
        let max_blob = self.config.max_blob;
1701421×
        for r in resp.refs {
1702421×
            let needed = {
1703421×
                let _t = crate::timing::phase("fetch: negotiate");
1704421×
                remote.negotiate(&have, &r.heads)?
1705
            };
1706421×
            let bundle = {
1707421×
                let _t = crate::timing::phase("fetch: bundle");
1708421×
                remote.fetch(&needed, max_blob)?
1709
            };
1710
            // Changes are not individually re-verified here: the bookmark's
1711
            // attestation (checked below) binds its whole state, and the
1712
            // receiver of the push verified the added changes at that time.
1713421×
            let imported = {
1714421×
                let _t = crate::timing::phase("fetch: import");
1715421×
                self.import_bundle(&bundle, false)?
1716
            };
1717421×
            if max_blob.is_some() {
17184×
                self.register_missing_blobs(&imported, remote_name)?;
1719417×
            }
1720573×
            for h in &r.heads {
1721573×
                if !self.store.has(h) {
17220×
                    return fail(format!("remote did not send head {}", h.short(12)));
1723573×
                }
1724
            }
1725421×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1726421×
            if state != r.state {
17270×
                return fail(format!(
1728
                    "remote state {} does not match its heads",
17290×
                    r.state.short(12)
1730
                ));
1731421×
            }
1732421×
            if let Some(p) = &policy {
173338×
                let Some(sa) = &r.attestation else {
17340×
                    return fail(format!(
1735
                        "{remote_name}/{} has no attestation, which its policy requires",
1736
                        r.name
1737
                    ));
1738
                };
173938×
                let signer = sa
174038×
                    .sigs
174138×
                    .first()
174238×
                    .map(|s| s.key)
174338×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
174438×
                if !p.authorizes(&signer, &r.name) {
174520×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
174618×
                }
1747383×
            }
1748421×
            if let Some(sa) = &r.attestation {
1749
                let AttestBody::Ref {
175070×
                    old_state,
175170×
                    new_state,
1752
                    ..
175370×
                } = &sa.attest.body
1754
                else {
17550×
                    return fail("remote sent a non-ref attestation for a bookmark");
1756
                };
175770×
                let (old_state, new_state) = (*old_state, *new_state);
175870×
                let serial = self
175970×
                    .check_ref_attest_body(
176070×
                        sa,
176170×
                        &r.name,
176270×
                        &old_state,
176370×
                        &new_state,
176470×
                        self.last_seen_serial(remote_name, &r.name),
1765
                        true,
1766
                    )
176770×
                    .map_err(|e| {
17680×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
17690×
                    })?;
177070×
                if new_state != r.state {
17710×
                    return fail(format!(
1772
                        "attestation for {}/{} does not cover its current state",
1773
                        remote_name, r.name
1774
                    ));
177570×
                }
1776
                // A signature this client cannot verify (its signer unknown
1777
                // here, as from a host that did not send the identity, or
1778
                // bad) fails that bookmark alone: it stays as it was and
1779
                // the rest are fetched (oxygenhub#266). The current
1780
                // bookmark, which a pull would take, still fails the fetch.
1781
                // A policy's requirements were checked above and still fail.
178270×
                if let Err(e) = self.verify_attest_signature(sa) {
178312×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
178412×
                    if r.name == self.config.bookmark {
17853×
                        return fail(why);
17869×
                    }
17879×
                    skipped.push((r.name, why));
17889×
                    continue;
178958×
                }
179058×
                let ar = self.store.put_attest(&sa.attest)?;
179158×
                for sig in &sa.sigs {
179258×
                    self.store.put_signature(&ar, sig)?;
1793
                }
179458×
                self.record_serial(remote_name, &r.name, serial)?;
1795351×
            }
1796409×
            view.remotes
1797409×
                .entry(remote_name.to_string())
1798409×
                .or_default()
1799409×
                .insert(r.name.clone(), state);
1800409×
            report.push((r.name, r.heads, imported.len()));
1801
        }
1802392×
        let mut new_tags = 0;
1803392×
        for t in &resp.tags {
180426×
            if view.tags.contains_key(&t.name) {
18056×
                continue;
180620×
            }
1807
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
180820×
            let missing: Vec<ChangeHash> = t
180920×
                .heads
181020×
                .iter()
181120×
                .filter(|h| !self.store.has(h))
181220×
                .copied()
181320×
                .collect();
181420×
            if !missing.is_empty() {
18150×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
18160×
                let bundle = remote.fetch(&needed, max_blob)?;
18170×
                self.import_bundle(&bundle, false)?;
181820×
            }
181920×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
182020×
            let mut check = TagCheck::Fetched {
182120×
                remote: remote_name,
182220×
                log: &log,
182320×
                notes: &mut log_notes,
182420×
            };
182520×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
182618×
                Ok(()) => new_tags += 1,
1827
                // Nothing says when a short-lived key signed it: the tag is
1828
                // left out, said so, and the rest is fetched (oxygen#129).
18292×
                Err(e) if e.untimed => {
18302×
                    skipped.push((format!("tags/{}", t.name), e.reason));
18312×
                }
18320×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1833
            }
1834
        }
1835392×
        if view != op.view {
1836376×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
183716×
        }
1838392×
        let _ = self.run_hook(
1839392×
            "post-fetch",
1840392×
            &format!(
1841
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1842392×
                json_str(remote_name),
1843406×
                json_array(report.iter().map(|(n, heads, _)| format!(
1844
                    "{{\"name\":{},\"heads\":{}}}",
1845406×
                    json_str(n),
1846558×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1847
                )))
1848
            ),
1849
        );
1850392×
        Ok(FetchReport {
1851392×
            refs: report,
1852392×
            unverified,
1853392×
            new_tags,
1854392×
            log_notes,
1855392×
            skipped,
1856392×
        })
1857401×
    }
1858
1859
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1860
    /// the changes within `depth` steps of its heads, and the boundary below.
18611×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
18621×
        let remote = self.open_named_remote(remote_name)?;
18631×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
18641×
        let resp = remote.refs()?;
18651×
        let bookmark = self.config.bookmark.clone();
18661×
        if let Some(sp) = &resp.policy {
18670×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
18680×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
18690×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
18701×
        }
18711×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
18720×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1873
        };
18741×
        if r.heads.is_empty() {
18750×
            return Ok(0);
18761×
        }
1877
        // Base: the remote's checkpoint of exactly these heads.
18781×
        let cp_bundle = remote.checkpoint(&r.heads)?;
18791×
        let mut cp_ref = None;
18803×
        for (ty, body) in &cp_bundle.objects {
18813×
            let put = self.store.put(*ty, body)?;
18823×
            if *ty == ObjectType::Checkpoint {
18831×
                cp_ref = Some(put);
18842×
            }
1885
        }
18861×
        let Some(cp_ref) = cp_ref else {
18870×
            return fail(format!("{remote_name} sent no checkpoint"));
1888
        };
18891×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1890
        // History window.
18911×
        let wanted = remote.shallow(&r.heads, depth)?;
18921×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
18931×
        let imported = self.import_bundle_shallow(&bundle, false)?;
18941×
        if self.config.max_blob.is_some() {
18950×
            self.register_missing_blobs(&imported, remote_name)?;
18961×
        }
18971×
        self.refresh_boundary(&imported)?;
18981×
        if let Some(sa) = &r.attestation {
18990×
            let ar = self.store.put_attest(&sa.attest)?;
19000×
            for sig in &sa.sigs {
19010×
                self.store.put_signature(&ar, sig)?;
1902
            }
19030×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
19040×
                self.record_serial(remote_name, &r.name, serial)?;
19050×
            }
19061×
        }
19071×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
19081×
        let (op_ref, op) = self.head_op()?;
19091×
        let mut view = op.view.clone();
19101×
        view.remotes
19111×
            .entry(remote_name.to_string())
19121×
            .or_default()
19131×
            .insert(r.name.clone(), state);
19141×
        self.record_op(
19151×
            &[op_ref],
19161×
            &format!("oxy fetch {remote_name} --depth {depth}"),
19171×
            view,
19180×
        )?;
19191×
        Ok(imported.len())
19201×
    }
1921
1922
    /// Fetch, then take the union of the local bookmark's state with the
1923
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1924112×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1925112×
        let _wc = self.lock_working_copy()?;
1926112×
        let skipped = self.fetch(remote_name)?.skipped;
1927108×
        let (op_ref, op) = self.head_op()?;
1928108×
        let current = self.config.bookmark.clone();
1929108×
        let mut local_current = self.heads_of(&op.view, &current)?;
1930108×
        local_current.sort();
1931108×
        let mut view = op.view.clone();
1932108×
        let mut current_heads = local_current.clone();
1933108×
        let mut changed = false;
1934108×
        let mut others = Vec::new();
1935108×
        let tracked = op
1936108×
            .view
1937108×
            .remotes
1938108×
            .get(remote_name)
1939108×
            .cloned()
1940108×
            .unwrap_or_default();
1941113×
        for (name, remote_state) in tracked {
1942
            // Every local bookmark tracks the remote's of the same name;
1943
            // the current one may be new here.
1944113×
            let local_state = op.view.bookmarks.get(&name).copied();
1945113×
            if local_state.is_none() && name != current {
19461×
                continue;
1947112×
            }
1948112×
            if local_state == Some(remote_state) {
194910×
                continue;
1950102×
            }
1951102×
            let local = self.heads_of(&op.view, &name)?;
1952102×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1953136×
            if remote_heads.iter().all(|h| local.contains(h)) {
19540×
                continue;
1955102×
            }
1956102×
            let mut all = local.clone();
1957102×
            all.extend(remote_heads);
1958102×
            let st = self.load_state_history(&all)?;
1959102×
            let mut heads = st.maximal(&all);
1960102×
            heads.sort();
1961102×
            let mut sorted_local = local;
1962102×
            sorted_local.sort();
1963102×
            if heads == sorted_local {
19641×
                continue;
1965101×
            }
1966101×
            view.bookmarks.insert(
1967101×
                name.clone(),
1968101×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1969
            );
1970101×
            if name == current {
197199×
                changed = true;
197299×
                current_heads = heads;
197399×
            } else {
19742×
                others.push(name);
19752×
            }
1976
        }
1977108×
        if changed || !others.is_empty() {
1978100×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
19798×
        }
1980
        // The working copy follows its bookmark whenever nothing would be
1981
        // lost, also when this pull brought nothing new but it had been
1982
        // left behind (oxygen#89).
1983108×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1984
        Ok(PullReport {
1985108×
            heads: if changed {
198699×
                current_heads
1987
            } else {
19889×
                local_current
1989
            },
1990108×
            changed,
1991108×
            checked_out,
1992108×
            others,
1993108×
            skipped,
1994
        })
1995112×
    }
1996
1997
    /// How many changes the working copy's bookmark has that its base
1998
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1999
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2000
    /// the bookmark or holds changes the bookmark lacks. History is read
2001
    /// only when the base and the bookmark's heads differ (oxygen#89).
20027×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
20037×
        let (_, wc) = self.working_copy()?;
20047×
        let mut base = wc.deps.clone();
20057×
        base.sort();
20067×
        let mut heads = self.bookmark_heads()?;
20077×
        heads.sort();
20087×
        if base == heads || heads.is_empty() {
20096×
            return Ok(None);
20101×
        }
20111×
        let state = self.load_state_history(&heads)?;
20121×
        if !base.iter().all(|h| state.contains(h)) {
20130×
            return Ok(None);
20141×
        }
20151×
        let had = if base.is_empty() {
20160×
            0
2017
        } else {
20181×
            self.load_state_history(&base)?.len()
2019
        };
20201×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
20217×
    }
2022
2023
    /// Bring the working copy to `heads`, the state of its bookmark
2024
    /// `bookmark`, when nothing would be lost: its base is part of that
2025
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2026
    /// with uncommitted work, the work comes along when the new changes
2027
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2028
    /// it followed only from exactly the bookmark's old heads, so a working
2029
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2030
    /// or a pull from another workspace) never caught up, and nothing said
2031
    /// so (oxygen#74, #89). Returns whether it moved.
2032108×
    pub fn follow_bookmark(
2033108×
        &self,
2034108×
        heads: &[ChangeHash],
2035108×
        bookmark: &str,
2036108×
        command: &str,
2037108×
    ) -> Result<bool> {
2038108×
        let snap = self.snapshot(command)?;
2039108×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2040108×
        let mut base = snap.base.maximal(&snap.wc.deps);
2041108×
        base.sort();
2042108×
        let mut target = heads.to_vec();
2043108×
        target.sort();
2044108×
        if base == target {
20458×
            return Ok(false);
2046100×
        }
2047100×
        let state = self.load_state_history(heads)?;
2048185×
        if !base.iter().all(|h| state.contains(h)) {
2049
            // The working copy holds changes the bookmark lacks: not ours to move.
20500×
            return Ok(false);
2051100×
        }
2052100×
        if clean {
2053100×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
2054100×
            Ok(true)
2055
        } else {
20560×
            Ok(self
20570×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
20580×
                .is_ok())
2059
        }
2060108×
    }
2061
2062
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2063
    /// changes and attesting the reference when a key is available.
2064
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2065
    /// state, attested when we have an identity. The local bookmark, if
2066
    /// any, is kept; only the remote-tracking entry goes.
20675×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
20685×
        let remote = self.open_named_remote(remote_name)?;
20695×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
20705×
        let resp = remote.refs()?;
20717×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
20721×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2073
        };
20744×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
20750×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
20764×
        }
20774×
        let attestation = match self.secret_key()? {
20782×
            Some(_) => Some(self.sign_attest(&Attest {
20792×
                repo: self.id()?,
20802×
                hlc: Hlc::now(),
20812×
                body: AttestBody::Ref {
20822×
                    name: bookmark.to_string(),
20832×
                    old_state: r.state,
20842×
                    new_state: ObjectRef::ZERO,
20852×
                    serial: r.last_serial.unwrap_or(0) + 1,
20862×
                },
20870×
            })?),
20882×
            None => None,
2089
        };
20904×
        let results = remote.push(
20914×
            Bundle::default(),
20924×
            vec![RefUpdate {
20934×
                name: bookmark.to_string(),
20944×
                old_state: r.state,
20954×
                new_state: ObjectRef::ZERO,
20964×
                force: true,
20974×
                attestation,
20984×
            }],
20994×
            None,
21004×
            vec![],
21010×
        )?;
21024×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
21032×
            let (op_ref, op) = self.head_op()?;
21042×
            let mut view = op.view.clone();
21052×
            if let Some(m) = view.remotes.get_mut(remote_name) {
21062×
                m.remove(bookmark);
21072×
            }
21082×
            self.record_op(
21092×
                &[op_ref],
21102×
                &format!("oxy push {remote_name} --delete {bookmark}"),
21112×
                view,
21120×
            )?;
21132×
        }
21144×
        Ok(results)
21155×
    }
2116
2117
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2118
    /// repository's config (its URL, token, CA and store settings), its
2119
    /// tracking bookmarks in the view, and a store remote's mirror under
2120
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
21213×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
21223×
        if !self.config.remotes.contains_key(name) {
21231×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
21242×
        }
21252×
        let prefix = format!("remote.{name}.");
21262×
        let keys: Vec<String> = self
21272×
            .config
21282×
            .repo_layer()
21292×
            .keys()
21304×
            .filter(|k| k.starts_with(&prefix))
21312×
            .cloned()
21322×
            .collect();
21333×
        for k in keys {
21343×
            self.config.set(&k, "")?;
2135
        }
21362×
        self.config.remotes.remove(name);
21372×
        self.save_config()?;
21382×
        let (op_ref, op) = self.head_op()?;
21392×
        if op.view.remotes.contains_key(name) {
21401×
            let mut view = op.view.clone();
21411×
            view.remotes.remove(name);
21421×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
21431×
        }
21442×
        let mirror = self.oxy.join("remotes").join(name);
21452×
        if mirror.is_dir() {
21460×
            fs::remove_dir_all(&mirror)?;
21472×
        }
21482×
        Ok(())
21493×
    }
2150
2151
    /// `changes`, in dependency order, cut into batches of about
2152
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2153
    /// There is always one, perhaps empty.
2154314×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2155314×
        let blob_len = |r: &ObjectRef| -> u64 {
215629×
            self.store
215729×
                .get_typed(r, ObjectType::Blob)
215829×
                .ok()
215929×
                .and_then(|b| Blob::decode(&b).ok())
216029×
                .map_or(0, |b| b.length)
216129×
        };
2162314×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2163409×
        for h in changes {
2164409×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2165409×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2166409×
            let mut weight = raw.len() as u64;
2167519×
            for t in &texts {
2168519×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
216926×
                    weight += blob_len(r);
2170493×
                }
2171
            }
2172665×
            for e in &c.edits {
21733×
                if let Edit::Replace { new: Some(b), .. } = e {
21743×
                    weight += blob_len(b);
2175662×
                }
2176
            }
2177409×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
21785×
                out.push(std::mem::take(&mut batch));
21795×
                bytes = 0;
2180404×
            }
2181409×
            batch.push(*h);
2182409×
            bytes += weight;
2183
        }
2184314×
        out.push(batch);
2185314×
        Ok(out)
2186314×
    }
2187
2188380×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2189380×
        let bookmark = self.config.bookmark.clone();
2190380×
        self.push_bookmark(remote_name, &bookmark, force)
2191380×
    }
2192
2193
    /// `push` for a named bookmark (`oxy push -b NAME`).
2194393×
    pub fn push_bookmark(
2195393×
        &self,
2196393×
        remote_name: &str,
2197393×
        bookmark: &str,
2198393×
        force: bool,
2199393×
    ) -> Result<Vec<RefResult>> {
2200393×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2201393×
    }
2202
2203
    /// `push_bookmark`, saying how a long push is going: one line per
2204
    /// batch sent (oxygen#95).
2205401×
    pub fn push_bookmark_with(
2206401×
        &self,
2207401×
        remote_name: &str,
2208401×
        bookmark: &str,
2209401×
        force: bool,
2210401×
        progress: crate::store::Progress,
2211401×
    ) -> Result<Vec<RefResult>> {
2212401×
        let (op_ref, op) = self.head_op()?;
2213401×
        if !op.view.bookmarks.contains_key(bookmark) {
22140×
            return fail(format!("no bookmark {bookmark}"));
2215401×
        }
2216401×
        let bookmark = bookmark.to_string();
2217401×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2218
        // pre-push hook: may veto before the remote is contacted.
2219401×
        self.run_hook(
2220401×
            "pre-push",
2221401×
            &format!(
2222
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2223401×
                json_str(remote_name),
2224401×
                json_str(&bookmark),
2225791×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2226
            ),
22271×
        )?;
2228400×
        let remote = self.open_named_remote(remote_name)?;
2229400×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2230397×
        let resp = remote.refs()?;
2231397×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2232397×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2233397×
        let policy_to_send = match (&local_policy, &resp.policy) {
223443×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
223515×
            (Some(l), None) => Some(l.clone()),
223625×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
22371×
                return fail(format!(
2238
                    "{remote_name} has a newer policy (serial {}); fetch first",
2239
                    r.policy.serial
2240
                ));
2241
            }
2242363×
            _ => None,
2243
        };
2244396×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2245396×
        if remote_has_policy && self.secret_key()?.is_none() {
22461×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2247395×
        }
2248395×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2249395×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2250395×
            .tag_refs()?
2251395×
            .into_iter()
2252395×
            .filter(|t| !remote_tags.contains(&t.name))
2253395×
            .collect();
2254395×
        let refs = resp.refs;
2255395×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2256395×
        let (remote_state, remote_heads, last_serial) =
2257396×
            match refs.iter().find(|r| r.name == bookmark) {
2258373×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
225922×
                None => (empty, vec![], None),
2260
            };
2261395×
        let new_state = self
2262395×
            .store
2263395×
            .put_state(&StateObject::new(local_heads.clone()))?;
2264
        // A push that carries a policy re-attests the bookmark even when its
2265
        // state is unchanged, so the current attestation is always by a key
2266
        // the current policy authorizes (a revoked key's attestation would
2267
        // otherwise be refused by every later fetch).
2268395×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
22698×
            return Ok(vec![RefResult {
22708×
                name: bookmark,
22718×
                ok: true,
22728×
                reason: "already up to date".into(),
22738×
            }]);
2274387×
        }
2275424×
        for h in &remote_heads {
2276424×
            if !self.store.has(h) {
227772×
                return fail(format!(
2278
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
227972×
                    h.short(12)
2280
                ));
2281352×
            }
2282
        }
2283315×
        if !force {
2284315×
            let closure = self.closure_in_store(&local_heads)?;
2285331×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
22860×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2287315×
            }
22880×
        }
2289315×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2290315×
        let key = self.secret_key()?.map(|(k, _)| k);
2291315×
        if let Some(key) = key {
2292
            // Seal this author's changes that carry no valid authenticator,
2293
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2294
            // are stored, so each batch's bundle carries those it needs.
2295110×
            let mut unsigned = Vec::new();
2296110×
            for h in &to_send {
229791×
                let c = self.store.get_change_meta(h)?;
229891×
                if self.seals_for_author(&c.author, &key)
229986×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
230052×
                {
230152×
                    unsigned.push(*h);
230252×
                }
2303
            }
2304110×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
230549×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2306
            }
2307205×
        }
2308
        // A long history goes in batches, in dependency order, so neither
2309
        // side holds it whole and no request passes the remote's limit:
2310
        // all but the last carry objects alone; the last moves the bookmark
2311
        // (oxygen#95).
2312314×
        let batches = self.push_batches(&to_send)?;
2313314×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2314314×
        for (i, batch) in earlier.iter().enumerate() {
23155×
            progress(&format!(
23165×
                "part {} of {}: {} changes",
23175×
                i + 1,
23185×
                batches.len(),
23195×
                batch.len()
23205×
            ));
23215×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
23225×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
23235×
                Some(r) if r.ok => {}
23240×
                Some(r) => {
23250×
                    return fail(format!(
2326
                        "{remote_name} refused part {} of the push: {}",
23270×
                        i + 1,
2328
                        r.reason
2329
                    ))
2330
                }
2331
                None => {
23320×
                    return fail(format!(
2333
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2334
                    ))
2335
                }
2336
            }
2337
        }
2338314×
        if batches.len() > 1 {
23391×
            progress(&format!(
23401×
                "part {} of {}: {} changes",
23411×
                batches.len(),
23421×
                batches.len(),
23431×
                last.len()
23441×
            ));
2345313×
        }
2346314×
        let mut bundle = self.bundle_for(last)?;
2347314×
        bundle.objects.push((
2348314×
            ObjectType::State,
2349314×
            StateObject::new(local_heads.clone()).encode(),
2350314×
        ));
2351314×
        let attestation = match key {
2352109×
            Some(_) => Some(self.sign_attest(&Attest {
2353109×
                repo: self.id()?,
2354109×
                hlc: Hlc::now(),
2355109×
                body: AttestBody::Ref {
2356109×
                    name: bookmark.clone(),
2357109×
                    old_state: remote_state,
2358109×
                    new_state,
2359109×
                    serial: next_serial(last_serial),
2360109×
                },
23611×
            })?),
2362205×
            None => None,
2363
        };
2364
        // Whoever signed the move, and whom a delegate acts for, travel with
2365
        // it: a receiver that has never seen a change by this delegate could
2366
        // not otherwise check its signature (oxygenhub#129).
2367313×
        if attestation.is_some() {
2368216×
            for k in [self.signing_key(), self.config.author_key]
2369108×
                .into_iter()
2370108×
                .flatten()
2371
            {
2372216×
                if let Ok(id) = self.identity(&k) {
2373216×
                    let body = id.encode();
2374216×
                    if !bundle
2375216×
                        .objects
2376216×
                        .iter()
2377260×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
237831×
                    {
237931×
                        bundle.objects.push((ObjectType::Identity, body));
2380185×
                    }
23810×
                }
2382
            }
2383
            // A short-lived signing key's certificate goes with it (§14.7).
2384108×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2385108×
            self.attach_certificates_for(&mut bundle, &signers)?;
2386205×
        }
2387313×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2388108×
            AttestBody::Ref { serial, .. } => Some(serial),
23890×
            _ => None,
2390108×
        });
2391313×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2392
        // Tag states must be present on the remote: bundle their changes too.
2393313×
        for t in &tags_to_send {
239414×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
239514×
            let extra: Vec<ChangeHash> =
239614×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
239714×
            if !extra.is_empty() {
23980×
                let more = self.bundle_for(&extra)?;
23990×
                bundle.changes.extend(more.changes);
24000×
                bundle.hashes.extend(more.hashes);
24010×
                bundle.attests.extend(more.attests);
24020×
                bundle.objects.extend(more.objects);
240314×
            }
240414×
            bundle.objects.push((
240514×
                ObjectType::State,
240614×
                StateObject::new(t.heads.clone()).encode(),
240714×
            ));
2408
        }
2409
        // A tag's signer travels with it, as the bookmark's does: a tag made
2410
        // by `oxy tag create` under a short-lived key was signed by a key the
2411
        // receiver has never seen, so its identity and certificate go too.
2412313×
        let tag_signers: Vec<KeyId> = tags_to_send
2413313×
            .iter()
2414313×
            .filter_map(|t| t.attestation.as_ref())
2415313×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2416313×
            .collect();
2417313×
        for k in &tag_signers {
241813×
            if let Ok(id) = self.identity(k) {
241913×
                let body = id.encode();
242013×
                if !bundle
242113×
                    .objects
242213×
                    .iter()
242326×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
24242×
                {
24252×
                    bundle.objects.push((ObjectType::Identity, body));
242611×
                }
24270×
            }
2428
        }
2429313×
        if !tag_signers.is_empty() {
243013×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2431300×
        }
2432313×
        if let Some(l) = &policy_to_send {
243333×
            let remote_serial = resp_policy_serial;
243433×
            bundle.policies = self
243533×
                .policy_history()?
243633×
                .into_iter()
243765×
                .filter(|sp| {
243865×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
243935×
                        && sp.policy.serial < l.policy.serial
244065×
                })
244133×
                .collect();
2442280×
        }
2443313×
        let results = remote.push(
2444313×
            bundle,
2445313×
            vec![RefUpdate {
2446313×
                name: bookmark.clone(),
2447313×
                old_state: remote_state,
2448313×
                new_state,
2449313×
                force,
2450313×
                attestation,
2451313×
            }],
2452313×
            policy_to_send,
2453313×
            tags_to_send,
24548×
        )?;
245533×
        if let (Some(serial), true) = (
2456305×
            sent_serial,
2457318×
            results.iter().any(|r| r.ok && r.name == "policy"),
2458
        ) {
245933×
            self.record_policy_serial(remote_name, serial)?;
2460272×
        }
2461341×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2462280×
            let mut view = op.view.clone();
2463280×
            view.remotes
2464280×
                .entry(remote_name.to_string())
2465280×
                .or_default()
2466280×
                .insert(bookmark.clone(), new_state);
2467280×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2468277×
            if let Some(s) = serial {
246984×
                self.record_serial(remote_name, &bookmark, s)?;
2470193×
            }
247125×
        }
2472300×
        Ok(results)
2473401×
    }
2474
2475
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2476
    /// bookmark set to the remote's, working copy checked out.
2477256×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2478256×
        Self::clone_with(url, dest, None, &[])
2479256×
    }
2480
2481
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2482
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2483
    /// unless a size is given, so out-of-scope binaries are never fetched).
2484259×
    pub fn clone_with(
2485259×
        url: &str,
2486259×
        dest: &Path,
2487259×
        max_blob: Option<u64>,
2488259×
        sparse: &[String],
2489259×
    ) -> Result<Repo> {
2490259×
        Self::clone_full(url, dest, max_blob, sparse, None)
2491259×
    }
2492
2493
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2494
    /// changes within `depth` steps of them; the rest is the boundary.
24951×
    pub fn clone_shallow(
24961×
        url: &str,
24971×
        dest: &Path,
24981×
        depth: u32,
24991×
        max_blob: Option<u64>,
25001×
        sparse: &[String],
25011×
    ) -> Result<Repo> {
25021×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
25031×
    }
2504
2505260×
    fn clone_full(
2506260×
        url: &str,
2507260×
        dest: &Path,
2508260×
        max_blob: Option<u64>,
2509260×
        sparse: &[String],
2510260×
        depth: Option<u32>,
2511260×
    ) -> Result<Repo> {
2512260×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2513260×
    }
2514
2515
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2516
    /// `depth`), also returning the bookmarks the fetch left out because
2517
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2518
    /// for the caller to warn about. The bookmark checked out is never one
2519
    /// of them: that fails the clone.
2520266×
    pub fn clone_reporting(
2521266×
        url: &str,
2522266×
        dest: &Path,
2523266×
        max_blob: Option<u64>,
2524266×
        sparse: &[String],
2525266×
        depth: Option<u32>,
2526266×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2527266×
        let options = crate::credentials::Credentials::user().options_for(url);
2528266×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2529266×
    }
2530
2531
    /// Clone a subrepo with the credentials the parent would use for its
2532
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2533
    /// subrepo: it finds the same ones again through its parent.
253410×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
253510×
        let options = self.credentials_for(url);
253610×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
253710×
    }
2538
2539
    /// The name of a remote of this repository on the same hub (scheme,
2540
    /// host and port) as `url`.
254123×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
254227×
        let origin = |u: &str| -> Option<String> {
254327×
            let (scheme, rest) = u.split_once("://")?;
25448×
            if !matches!(scheme, "http" | "https") {
25450×
                return None;
25468×
            }
25478×
            let host = rest.split('/').next()?;
25488×
            Some(format!(
25498×
                "{}://{}",
25508×
                scheme.to_ascii_lowercase(),
25518×
                host.to_ascii_lowercase()
25528×
            ))
255327×
        };
255423×
        let want = origin(url)?;
25554×
        self.config
25564×
            .remotes
25574×
            .iter()
25584×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
25594×
            .map(|(name, _)| name.clone())
256023×
    }
2561
2562
    /// The token and CA to reach `url` with: those of a remote of this
2563
    /// repository on the same hub (scheme, host and port), else the
2564
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2565
    /// and enclosing checkouts', as a clone would use them.
256623×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
256723×
        match self.remote_on_same_hub(url) {
25681×
            Some(name) => RemoteOptions {
25691×
                repo_id: None,
25701×
                cache_dir: None,
25711×
                ..self.remote_options(&name)
25721×
            },
2573
            None => {
257422×
                let mut options = RemoteOptions::default();
257522×
                self.fill_credentials(url, &mut options);
257622×
                options
2577
            }
2578
        }
257923×
    }
2580
2581276×
    fn clone_using(
2582276×
        url: &str,
2583276×
        dest: &Path,
2584276×
        max_blob: Option<u64>,
2585276×
        sparse: &[String],
2586276×
        depth: Option<u32>,
2587276×
        options: &RemoteOptions,
2588276×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2589276×
        let remote = open_remote(url, options)?;
2590276×
        let id = remote.repo_id()?;
2591272×
        if id == crate::protocol::UNBOUND_ID {
25922×
            return fail(format!(
2593
                "{url} is empty and unbound: push a repository to it first"
2594
            ));
2595270×
        }
2596270×
        let mut repo = Repo::init_with_id(dest, id)?;
2597270×
        repo.config
2598270×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2599270×
        if let Some(m) = max_blob {
26002×
            repo.config.set("filter.max-blob", &m.to_string())?;
2601268×
        } else if !sparse.is_empty() {
26021×
            repo.config.set("filter.max-blob", "0")?;
2603267×
        }
2604270×
        if !sparse.is_empty() {
26051×
            repo.config.set("filter.paths", &sparse.join(","))?;
2606269×
        }
2607270×
        repo.save_config()?;
2608270×
        let skipped = if let Some(depth) = depth {
26091×
            repo.fetch_shallow("origin", depth)?;
26101×
            Vec::new()
2611
        } else {
2612269×
            repo.fetch("origin")?.skipped
2613
        };
2614268×
        let (op_ref, op) = repo.head_op()?;
2615
        // The remote's default bookmark, else ours (main), else its only
2616
        // one; a bookmark the fetch skipped counts, so the clone fails
2617
        // rather than check out another (oxygenhub#266).
2618268×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2619268×
        for (name, _) in &skipped {
26203×
            theirs.insert(name.clone(), ObjectRef::ZERO);
26213×
        }
2622
        // Asked of the remote as now configured, so a store-backed one
2623
        // answers from the mirror the fetch just filled.
2624268×
        let advertised = repo
2625268×
            .open_named_remote("origin")
2626268×
            .ok()
2627268×
            .and_then(|r| r.refs().ok())
2628268×
            .and_then(|r| r.default_bookmark);
2629268×
        let bookmark = advertised
2630268×
            .filter(|b| theirs.contains_key(b))
2631268×
            .or_else(|| {
26327×
                theirs
26337×
                    .contains_key(&repo.config.bookmark)
26347×
                    .then(|| repo.config.bookmark.clone())
26357×
            })
2636268×
            .or_else(|| {
26370×
                (theirs.len() == 1)
26380×
                    .then(|| theirs.keys().next().cloned())
26390×
                    .flatten()
26400×
            })
2641268×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2642268×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
26430×
            return fail(format!("cannot check out {bookmark}: {why}"));
2644268×
        }
2645268×
        let initial = repo.config.bookmark.clone();
2646268×
        if bookmark != repo.config.bookmark {
26471×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
26481×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
26491×
            repo.config.bookmark = bookmark.clone();
2650267×
        }
2651268×
        if let Some(state) = theirs.get(&bookmark).copied() {
2652268×
            let heads = repo.store.get_state(&state)?.heads;
2653268×
            let mut view = op.view.clone();
2654
            // The empty bookmark `init` made goes when another is checked out.
2655268×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
26561×
                view.bookmarks.remove(&initial);
2657267×
            }
2658268×
            view.bookmarks.insert(bookmark, state);
2659268×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2660268×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
26610×
        }
2662268×
        Ok((repo, skipped))
2663276×
    }
2664
}
2665
2666
/// The serial of a reference's next attestation: one more than the last the
2667
/// remote reports, or, for a bookmark the remote does not have, the clock in
2668
/// milliseconds, so a bookmark created again after a deletion goes past the
2669
/// deletion's serial the remote keeps.
2670109×
fn next_serial(last: Option<u64>) -> u64 {
2671109×
    match last {
267268×
        Some(l) => l + 1,
267341×
        None => Hlc::now().wall_ms.max(1),
2674
    }
2675109×
}