OXYGENHUB

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

2157 of 2409 lines run, 337 of 454 functions · run #398 on subrepo-pin-state · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::tags::TagCheck;
4
use super::*;
5
6
/// What a push did, for hosts (hub spec §6.12).
7
#[derive(Clone, Debug, Default)]
8
pub struct PushReport {
9
    pub results: Vec<RefResult>,
10
    /// Accepted reference updates, in request order.
11
    pub updated: Vec<RefUpdated>,
12
    /// Changes this push stored that were not already present.
13
    pub imported: Vec<ChangeHash>,
14
}
15
16
#[derive(Clone, Debug)]
17
pub struct RefUpdated {
18
    pub name: String,
19
    pub old_state: ObjectRef,
20
    pub new_state: ObjectRef,
21
    pub heads: Vec<ChangeHash>,
22
}
23
24
/// What a fetch brought in.
25
#[derive(Debug, Clone, PartialEq, Eq, Default)]
26
pub struct FetchReport {
27
    /// Bookmark name, its heads, and how many changes were new.
28
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
29
    /// Tags adopted from the remote.
30
    pub new_tags: usize,
31
    /// Tags the remote withdrew, and so withdrawn here (oxygenhub#301).
32
    pub withdrawn_tags: Vec<String>,
33
    /// The remote has never presented a policy, so nothing was verified
34
    /// against one (spec §14.5: warn loudly).
35
    pub unverified: bool,
36
    /// What checking the host's transparency log found short of a fork
37
    /// (spec §14.8): attestations not logged yet, a log that could not be
38
    /// read. A fork fails the fetch instead.
39
    pub log_notes: Vec<String>,
40
    /// Bookmarks left as they were because their attestation could not be
41
    /// verified (its signer unknown here, or its signature bad), each with
42
    /// why (oxygenhub#266). The current bookmark is never skipped: its
43
    /// fetch fails instead.
44
    pub skipped: Vec<(String, String)>,
45
}
46
47
#[derive(Debug, Clone, PartialEq, Eq)]
48
pub struct PullReport {
49
    /// The current bookmark's heads after the pull.
50
    pub heads: Vec<ChangeHash>,
51
    /// Whether the current bookmark changed.
52
    pub changed: bool,
53
    pub checked_out: bool,
54
    /// Other bookmarks the pull moved: each local bookmark tracks the
55
    /// remote's of the same name.
56
    pub others: Vec<String>,
57
    /// What the fetch left as it was ([`FetchReport::skipped`]).
58
    pub skipped: Vec<(String, String)>,
59
}
60
61
/// The result a push of objects alone reports (a batch of a long history):
62
/// not a reference.
63
pub const OBJECTS_RESULT: &str = "objects";
64
65
/// Graph blobs asked for in one `objects` request when a shallow clone
66
/// fetches its checkpoint in parts (#137): their chunk lists and chunks,
67
/// a few MiB a request rather than one answer of gigabytes.
68
const CHECKPOINT_PART: usize = 2048;
69
70
impl Repo {
71
    // ------------------------------------------------------------ serving (spec §16)
72
731856×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
741856×
        self.oxy.join("attest").join(name_file(bookmark))
751856×
    }
76
77
    /// The latest reference attestation stored for a bookmark.
781432×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
791432×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
80345×
            Ok(h) => {
81345×
                let r = ObjectRef::from_hex(h.trim())
82345×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
83
                Ok(Some((
84345×
                    r,
85
                    SignedAttest {
86345×
                        attest: self.store.get_attest(&r)?,
87345×
                        sigs: self.store.signatures(&r)?,
88
                    },
89
                )))
90
            }
911087×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
920×
            Err(e) => Err(e.into()),
93
        }
941432×
    }
95
96109×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
97109×
        fs::create_dir_all(self.oxy.join("attest"))?;
98109×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
99109×
    }
100
1011139×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
1021139×
        let view = self.view()?;
1031139×
        let mut out = Vec::new();
1041194×
        for (name, state) in &view.bookmarks {
1051194×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
1061194×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
107230×
                AttestBody::Ref { serial, .. } => Some(serial),
1080×
                _ => None,
109230×
            });
1101194×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1111194×
            let accepted = match &attestation {
112219×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
113975×
                None => None,
114
            };
1151194×
            out.push(RemoteRef {
1161194×
                name: name.clone(),
1171194×
                state: *state,
1181194×
                heads: self.store.get_state(state)?.heads,
1191194×
                attestation,
1201194×
                last_serial,
1211194×
                accepted,
1221194×
                logged: None,
1231194×
                integration: vec![],
124
            });
125
        }
1261139×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1271139×
        let history = self
1281139×
            .policy_history()?
1291139×
            .into_iter()
1301139×
            .filter(|sp| {
131221×
                policy
132221×
                    .as_ref()
133221×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
134221×
            })
1351139×
            .collect();
136
        Ok(RefsResponse {
1371139×
            refs: out,
1381139×
            policy,
1391139×
            tags: self.tag_refs()?,
1401139×
            history,
1411139×
            default_bookmark: Some(self.config.bookmark.clone()),
1421139×
            log: None,
1431139×
            witnesses: vec![],
1441139×
            withdrawn: self.withdrawn_refs()?,
145
        })
1461139×
    }
147
148
    /// Every change reachable from `heads` that is in the store.
1491559×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1501559×
        let mut seen = BTreeSet::new();
1511559×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1525107×
        while let Some(h) = stack.pop() {
1533548×
            if seen.contains(&h) || !self.store.has(&h) {
1541013×
                continue;
1552535×
            }
1562535×
            seen.insert(h);
1572535×
            stack.extend(self.store.get_change_meta(&h)?.deps);
158
        }
1591559×
        Ok(seen)
1601559×
    }
161
162
    /// The changes within `depth` dependency steps of `heads` (spec §17),
163
    /// nearest first; depth 1 is the heads themselves.
1643×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1653×
        let mut out = Vec::new();
1663×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1673×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1683×
        for _ in 0..depth.max(1) {
1698×
            let mut next = Vec::new();
17012×
            for h in layer {
17112×
                if !seen.insert(h) || !self.store.has(&h) {
1722×
                    continue;
17310×
                }
17410×
                let c = self.store.get_change(&h)?;
17510×
                next.extend(c.deps.iter().copied());
17610×
                out.push(h);
177
            }
1788×
            if next.is_empty() {
1791×
                break;
1807×
            }
1817×
            layer = next;
182
        }
1833×
        out.reverse();
1843×
        Ok(out)
1853×
    }
186
1873933×
    fn shallow_path(&self) -> PathBuf {
1883933×
        self.oxy.join("shallow")
1893933×
    }
190
191
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1923924×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1933924×
        fs::read_to_string(self.shallow_path())
1943924×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1953924×
            .unwrap_or_default()
1963924×
    }
197
1981524×
    pub fn is_shallow(&self) -> bool {
1991524×
        !self.boundary().is_empty()
2001524×
    }
201
2029×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
2039×
        if boundary.is_empty() {
2041×
            let _ = fs::remove_file(self.shallow_path());
2051×
            return Ok(());
2068×
        }
2078×
        let text: String = boundary
2088×
            .iter()
2099×
            .map(|h| format!("{}\n", h.to_hex()))
2108×
            .collect();
2118×
        write_atomic(&self.shallow_path(), text.as_bytes())
2129×
    }
213
214
    /// Recompute the boundary from what is stored: every dependency of a
215
    /// stored change that is not itself stored.
2167×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2177×
        let mut boundary = self.boundary();
2187×
        boundary.retain(|h| !self.store.has(h));
21912×
        for h in imported {
22015×
            for d in self.store.get_change_meta(h)?.deps {
22115×
                if !self.store.has(&d) {
2223×
                    boundary.insert(d);
22312×
                }
224
            }
225
        }
2267×
        self.write_boundary(&boundary)
2277×
    }
228
229
    /// Fetch `depth` more levels of history below the shallow boundary.
2302×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2312×
        let boundary = self.boundary();
2322×
        if boundary.is_empty() {
2330×
            return Ok(0);
2342×
        }
2352×
        let remote = self.open_named_remote(remote_name)?;
2362×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2372×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2382×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2392×
        if self.config.max_blob.is_some() {
2400×
            self.register_missing_blobs(&imported, remote_name)?;
2412×
        }
2422×
        self.refresh_boundary(&imported)?;
2432×
        Ok(imported.len())
2442×
    }
245
246
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
247902×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
248902×
        let have = self.closure_in_store(have)?;
249
        // In a shallow repository the walk stops at the boundary, whose
250
        // changes the remote is assumed to hold.
251902×
        let boundary = self.boundary();
252902×
        let mut out = Vec::new();
253902×
        let mut done: BTreeSet<ChangeHash> = have.clone();
254902×
        done.extend(boundary.iter().copied());
255
        // Iterative post-order DFS.
256902×
        let shallow = self.is_shallow();
2571362×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2583548×
        while let Some((h, expanded)) = stack.pop() {
2592646×
            if done.contains(&h) {
260493×
                continue;
2612153×
            }
2622153×
            if !self.store.has(&h) {
263
                // A shallow repository holds only part of its history; a
264
                // change it lacks is below what it cloned (in a depth-0
265
                // clone, any change of the checkpoint), which the remote
266
                // is assumed to hold, as it is for the boundary (#137).
2671×
                if shallow {
2681×
                    done.insert(h);
2691×
                    continue;
2700×
                }
2710×
                return fail(format!("change {} is not in this repository", h.short(12)));
2722152×
            }
2732152×
            if expanded {
2741076×
                done.insert(h);
2751076×
                out.push(h);
2761076×
                continue;
2771076×
            }
2781076×
            stack.push((h, true));
2791076×
            for d in self.store.get_change_meta(&h)?.deps {
280698×
                if !done.contains(&d) {
281208×
                    stack.push((d, false));
282490×
                }
283
            }
284
        }
285902×
        Ok(out)
286902×
    }
287
288
    /// Bundle changes (in the given dependency order) with their signatures,
289
    /// seals, identities, blobs, chunks.
290347×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
291347×
        self.bundle_of(changes, None, false, false)
292347×
    }
293
294
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2956×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
296
        // In two reads in pack order (#137): a checkpoint's graph blobs come
297
        // this way in parts, tens of thousands for a big state.
2986×
        let mut found = Vec::with_capacity(refs.len());
2996×
        for got in self.store.get_many(refs) {
3000×
            match got {
3016×
                Ok(x) => found.push(x),
3020×
                Err(StoreError::NotFound(_)) => {}
3030×
                Err(e) => return Err(e.into()),
304
            }
305
        }
3066×
        let mut chunks = Vec::new();
3076×
        for (ty, body) in &found {
3086×
            if *ty == ObjectType::Blob {
3096×
                chunks.extend(Blob::decode(body)?.chunks);
3100×
            }
311
        }
3126×
        let mut out = Vec::with_capacity(found.len() + chunks.len());
3137×
        for got in self.store.get_many(&chunks) {
3140×
            match got {
3157×
                Ok(x) => out.push(x),
3160×
                Err(StoreError::NotFound(_)) => {}
3170×
                Err(e) => return Err(e.into()),
318
            }
319
        }
3206×
        out.extend(found);
3216×
        Ok(out)
3226×
    }
323
324
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
325
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
326
    ///
327
    /// This is what a server answers a fetch with, so it also carries what
328
    /// verifies the attestations it serves beside it (see
329
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
33056×
    pub fn bundle_for_filtered(
33156×
        &self,
33256×
        changes: &[ChangeHash],
33356×
        max_blob: Option<u64>,
33456×
    ) -> Result<Bundle> {
33556×
        self.bundle_of(changes, max_blob, false, true)
33656×
    }
337
338
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
339
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
340
    /// with their text blobs and chunks among the objects, so neither side
341
    /// decodes or encodes their text.
342380×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
343380×
        self.bundle_of(changes, max_blob, true, true)
344380×
    }
345
346
    /// The keys that signed the attestations this repository serves with
347
    /// its references: each bookmark's latest and each tag's. A fetch
348
    /// bundle carries their identities and certificates (spec §16.2), so a
349
    /// client can check an attestation whose signer signed none of the
350
    /// changes it receives, a delegate or a short-lived key that only
351
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
352
    /// list per reference, computed once per operation head and kept
353
    /// (every bookmark move and tag is an operation): a client sends one
354
    /// fetch per bookmark, and on a bucket store each signature list is a
355
    /// LIST request, so recomputing per fetch cost metalgear2 (145
356
    /// bookmarks) 14 s a fetch.
357436×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
358
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
359
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
360436×
        let key = (self.oxy.clone(), self.head_op()?.0);
361436×
        if let Some(keys) = SERVED
362436×
            .lock()
363436×
            .unwrap_or_else(|p| p.into_inner())
364436×
            .as_ref()
365436×
            .and_then(|m| m.get(&key))
366
        {
367132×
            return Ok(keys.clone());
368304×
        }
369304×
        let keys = self.attest_signers_now()?;
370304×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
371304×
        let map = served.get_or_insert_with(Default::default);
372
        // One entry per repository: an older operation head is never asked
373
        // for again once a newer one is current.
3742562×
        map.retain(|(oxy, _), _| *oxy != key.0);
375304×
        if map.len() >= 1024 {
3760×
            map.clear();
377304×
        }
378304×
        map.insert(key, keys.clone());
379304×
        Ok(keys)
380436×
    }
381
382304×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
383304×
        let view = self.view()?;
384304×
        let pointers = view
385304×
            .bookmarks
386304×
            .keys()
387315×
            .map(|b| self.ref_attest_path(b))
388304×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
389304×
        let mut keys = BTreeSet::new();
390337×
        for p in pointers {
391337×
            let Ok(text) = fs::read_to_string(&p) else {
392274×
                continue;
393
            };
39463×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3950×
                continue;
396
            };
39763×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
398
        }
399304×
        Ok(keys)
400304×
    }
401
402
    /// `serving`: a fetch's answer, which carries the identities and
403
    /// certificates of [`Repo::served_attest_signers`] too.
404783×
    fn bundle_of(
405783×
        &self,
406783×
        changes: &[ChangeHash],
407783×
        max_blob: Option<u64>,
408783×
        raw: bool,
409783×
        serving: bool,
410783×
    ) -> Result<Bundle> {
411783×
        let mut bundle = Bundle::default();
412783×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
413783×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
4141240×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
4151240×
            if !r.is_zero() && self.store.has(r) {
416364×
                objects.insert(*r);
417876×
            }
4181240×
        };
419992×
        for h in changes {
420
            // Raw: the stored bytes, and a skeleton for the rest.
421992×
            let (c, encoded) = if raw {
422527×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
423527×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
4244966×
                for t in texts {
4254966×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
4263×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4273×
                        objects.insert(r);
4283×
                        objects.extend(blob.chunks);
4294963×
                    }
430
                }
431527×
                (skel, Some(bytes))
432
            } else {
433465×
                (self.store.get_change(h)?, None)
434
            };
435992×
            let sigs = self.store.signatures(h)?;
436992×
            add_object(&c.author, &mut objects);
437992×
            for s in &sigs {
43832×
                add_object(&s.key, &mut objects);
43932×
            }
440
            // A replacement's new content only: its old content is the new
441
            // content of a change it depends on, which the receiver holds or
442
            // which this bundle carries (oxygen#136: removing ~1,100 binary
443
            // files sent them all again).
4445930×
            for e in &c.edits {
44532×
                if let Edit::Replace { new: Some(b), .. } = e {
44632×
                    if self.store.has(b) {
44732×
                        if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
448
                        {
44932×
                            if max_blob.is_some_and(|m| blob.length > m) {
4504×
                                continue;
45128×
                            }
45228×
                            objects.insert(*b);
45328×
                            objects.extend(blob.chunks.iter().copied());
4540×
                        }
4550×
                    }
4565898×
                }
457
            }
458992×
            for s in self.store.seals_for(h)? {
459105×
                seals.insert(s);
460105×
            }
461992×
            match encoded {
462527×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
463465×
                None => {
464465×
                    bundle.changes.push((c, sigs));
465465×
                    bundle.hashes.push(*h);
466465×
                }
467
            }
468
        }
469783×
        for r in seals {
470100×
            let attest = self.store.get_attest(&r)?;
471100×
            let sigs = self.store.signatures(&r)?;
472100×
            for s in &sigs {
473100×
                add_object(&s.key, &mut objects);
474100×
            }
475100×
            bundle.attests.push(SignedAttest { attest, sigs });
476
        }
477783×
        let signers: Vec<KeyId> = if serving {
478436×
            let signers = self.served_attest_signers()?;
479436×
            for k in &signers {
480116×
                add_object(k, &mut objects);
481116×
            }
482436×
            signers.into_iter().collect()
483
        } else {
484347×
            Vec::new()
485
        };
486783×
        for r in objects {
487334×
            let (ty, body) = self.store.get(&r)?;
488334×
            bundle.objects.push((ty, body));
489
        }
490783×
        self.attach_certificates_for(&mut bundle, &signers)?;
491783×
        Ok(bundle)
492783×
    }
493
494
    /// Add the certificates of short-lived keys that signed what `bundle`
495
    /// carries, and their issuers' identities, so a receiver can tell who
496
    /// they stand for (spec §14.7). `also` names more signers (a reference
497
    /// attestation sent beside the bundle).
498910×
    pub(crate) fn attach_certificates_for(
499910×
        &self,
500910×
        bundle: &mut Bundle,
501910×
        also: &[KeyId],
502910×
    ) -> Result<()> {
503910×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
504910×
        keys.extend(
505910×
            bundle
506910×
                .changes
507910×
                .iter()
508910×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
509
        );
510910×
        keys.extend(
511910×
            bundle
512910×
                .raw_changes
513910×
                .iter()
514910×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
515
        );
516910×
        keys.extend(
517910×
            bundle
518910×
                .attests
519910×
                .iter()
520910×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
521
        );
522910×
        for k in keys {
523338×
            let Some(r) = self.store.certificate_of(&k)? else {
524289×
                continue;
525
            };
52649×
            let cert = self.store.get_certificate(&r)?;
52749×
            if bundle
52849×
                .certificates
52949×
                .iter()
53049×
                .any(|c| c.cert.hash() == cert.cert.hash())
531
            {
53212×
                continue;
53337×
            }
534
            // An agent's certificate brings its grant's signer too, so the
535
            // receiver can check the grant (oxygen#134).
53637×
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
53781×
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
53881×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
53980×
                    if !bundle
54080×
                        .objects
54180×
                        .iter()
542141×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
54335×
                    {
54435×
                        bundle.objects.push((ObjectType::Identity, body));
54545×
                    }
5461×
                }
547
            }
54837×
            bundle.certificates.push(cert);
549
        }
550910×
        Ok(())
551910×
    }
552
553
    /// Keep the certificates a bundle brings once each verifies with the
554
    /// identity of the issuer it names; one that does not refuses the bundle.
555829×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
556829×
        for c in certs {
55736×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5580×
                RepoError::Msg(format!(
5590×
                    "a certificate names issuer {}, whose identity did not come with it",
5600×
                    c.cert.issuer.short(12)
5610×
                ))
5620×
            })?;
56336×
            c.verify(&issuer)
56436×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
56536×
            self.store.put_identity(&c.cert.key)?;
56636×
            self.store.put_certificate(c)?;
567
        }
568829×
        Ok(())
569829×
    }
570
571
    /// A signer authorized for `reference` by what an issuer certified it
572
    /// as (spec §14.7): a short-lived key with a kept certificate that
573
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
574
    /// signer did not choose) and names a subject the policy grants.
57557×
    pub(crate) fn certified_authorized(
57657×
        &self,
57757×
        p: &crate::policy::Policy,
57857×
        signer: &KeyId,
57957×
        reference: &str,
58057×
        scope: Scope,
58157×
        at_ms: u64,
58257×
    ) -> bool {
58357×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5845×
            return false;
585
        };
58652×
        let Ok(c) = self.store.get_certificate(&r) else {
5870×
            return false;
588
        };
58952×
        let Some(issuer) = p
59052×
            .identity(&c.cert.issuer)
59152×
            .cloned()
59252×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
593
        else {
5940×
            return false;
595
        };
59652×
        c.verify(&issuer).is_ok()
59752×
            && c.cert.key_id() == *signer
59852×
            && c.cert.covers(scope, at_ms)
59942×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
60057×
    }
601
602
    /// Store a bundle's contents. With `strict`, every change must
603
    /// authenticate (signature or seal by its author or a delegate).
604824×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
605824×
        self.import_bundle_inner(bundle, strict, false)
606824×
    }
607
608
    /// Like `import_bundle`, accepting changes whose dependencies are absent
609
    /// (they join the shallow boundary).
6105×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
6115×
        self.import_bundle_inner(bundle, strict, true)
6125×
    }
613
614829×
    fn import_bundle_inner(
615829×
        &self,
616829×
        bundle: &Bundle,
617829×
        strict: bool,
618829×
        shallow: bool,
619829×
    ) -> Result<Vec<ChangeHash>> {
620829×
        let batch = self.store.begin_batch()?;
621829×
        let result = self.import_bundle_batched(bundle, strict, shallow);
622829×
        batch.finish()?;
623827×
        result
624829×
    }
625
626829×
    fn import_bundle_batched(
627829×
        &self,
628829×
        bundle: &Bundle,
629829×
        strict: bool,
630829×
        shallow: bool,
631829×
    ) -> Result<Vec<ChangeHash>> {
632829×
        for (ty, _) in &bundle.objects {
6330×
            if !matches!(
634807×
                ty,
635
                ObjectType::Chunk
636
                    | ObjectType::Blob
637
                    | ObjectType::Identity
638
                    | ObjectType::State
639
                    | ObjectType::Checkpoint
640
            ) {
6410×
                return fail(format!("bundle may not carry {} objects", ty.name()));
642807×
            }
643
        }
644
        // All at once: in a large batch they are compressed on every core.
645829×
        let objects: Vec<(ObjectType, &[u8])> = bundle
646829×
            .objects
647829×
            .iter()
648829×
            .map(|(ty, body)| (*ty, body.as_slice()))
649829×
            .collect();
650829×
        self.store.put_many(&objects)?;
651829×
        self.adopt_certificates(&bundle.certificates)?;
652829×
        for sa in &bundle.attests {
653103×
            let r = self.store.put_attest(&sa.attest)?;
654103×
            for sig in &sa.sigs {
655103×
                self.store.put_signature(&r, sig)?;
656
            }
657103×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
658108×
                for h in hashes {
659108×
                    self.store.index_seal(h, &r)?;
660
                }
6610×
            }
662
        }
663
        // Each change's hash: from the bundle when its maker knew it, else
664
        // worked out once (for a change adding a whole tree, hashing is
665
        // chunking all its text).
666829×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
667820×
            bundle.hashes.clone()
668
        } else {
6699×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
670
        };
671829×
        let raw_hashes: Vec<ChangeHash> = bundle
672829×
            .raw_changes
673829×
            .iter()
674829×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
675829×
            .collect();
676829×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
677829×
        let boundary = self.boundary();
678829×
        let mut imported = Vec::new();
679
        // Changes as stored: checked, then stored as they are, their text
680
        // blobs having come with the objects.
681829×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
682528×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
683528×
            for d in &skel.deps {
684362×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
685
                {
6860×
                    return fail(format!(
687
                        "change {} depends on {}, which is neither stored nor in the bundle",
6880×
                        h.short(12),
6890×
                        d.short(12)
690
                    ));
691362×
                }
692
            }
6934967×
            for t in texts {
6944967×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6954×
                    if !self.store.has(&r) {
6961×
                        return fail(format!(
697
                            "change {} came without its text blob {}",
6981×
                            h.short(12),
6991×
                            r.short(12)
700
                        ));
7013×
                    }
7024963×
                }
703
            }
704527×
            self.store.put(ObjectType::Change, bytes)?;
705527×
            for sig in sigs {
70613×
                self.store.put_signature(&h, sig)?;
707
            }
708527×
            imported.push(h);
709
        }
710828×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
711489×
            for d in &c.deps {
712290×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
713
                {
7143×
                    return fail(format!(
715
                        "change {} depends on {}, which is neither stored nor in the bundle",
7163×
                        h.short(12),
7173×
                        d.short(12)
718
                    ));
719287×
                }
720
            }
721486×
            let stored = self.store.put_change(c)?;
722486×
            if stored != h {
7230×
                return fail(format!(
724
                    "change {} is not the change the bundle names",
7250×
                    h.short(12)
726
                ));
727486×
            }
728486×
            for sig in sigs {
72928×
                self.store.put_signature(&h, sig)?;
730
            }
731486×
            imported.push(h);
732
        }
733825×
        if strict {
73467×
            for h in &imported {
73536×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7364×
                    return fail(format!(
737
                        "change {} is not authenticated by its author",
7384×
                        h.short(12)
739
                    ));
74032×
                }
741
            }
742758×
        }
743821×
        Ok(imported)
744829×
    }
745
746
    /// Verify a reference attestation against an update it claims to describe.
747
    /// `allow_equal` lets a client re-read the attestation it already has; a
748
    /// server receiving a push requires a strictly greater serial.
749
    /// A reference attestation signed by a delegate of an identity the
750
    /// rule lists is authorized as that identity (spec §14.5): the identity
751
    /// named the delegate with the `refs` scope, still in force at `at_ms`
752
    /// (the attestation's wall time), and the policy names the identity.
753
    /// Revoked keys authorize nothing either way.
75472×
    pub(crate) fn delegate_authorized(
75572×
        &self,
75672×
        p: &crate::policy::Policy,
75772×
        signer: &KeyId,
75872×
        reference: &str,
75972×
        at_ms: u64,
76072×
    ) -> bool {
76172×
        if p.is_revoked(signer) {
7621×
            return false;
76371×
        }
76471×
        let Some(rule) = p.rule_for(reference) else {
7650×
            return false;
766
        };
76772×
        rule.keys.iter().any(|k| {
76872×
            !p.is_revoked(k)
76972×
                && p.identity(k)
77072×
                    .cloned()
77172×
                    .or_else(|| self.store.get_identity(k).ok())
77272×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
77372×
        })
77472×
    }
775
776
    /// A lasting attestation (a tag) signed by a key the policy has since
777
    /// rotated away from (spec §14.2) is authorized as the key that
778
    /// succeeded it: a key the rule lists reaches the signer through
779
    /// `previous` links, and the attestation is dated (`at_ms`) before the
780
    /// signer's successor was made, so a superseded key makes nothing new.
781
    /// Revoked keys authorize nothing.
78227×
    pub(crate) fn predecessor_authorized(
78327×
        &self,
78427×
        p: &crate::policy::Policy,
78527×
        signer: &KeyId,
78627×
        reference: &str,
78727×
        at_ms: u64,
78827×
    ) -> bool {
78927×
        if p.is_revoked(signer) {
7900×
            return false;
79127×
        }
79227×
        let Some(rule) = p.rule_for(reference) else {
7930×
            return false;
794
        };
79528×
        let identity = |k: &KeyId| {
79628×
            p.identity(k)
79728×
                .cloned()
79828×
                .or_else(|| self.store.get_identity(k).ok())
79928×
        };
80027×
        rule.keys.iter().any(|k| {
80127×
            if p.is_revoked(k) {
8020×
                return false;
80327×
            }
80427×
            let mut cur = identity(k);
80527×
            for _ in 0..32 {
80628×
                let Some(id) = cur else {
8070×
                    return false;
808
                };
8091×
                match id.previous {
8106×
                    Some(prev) if prev == *signer => return at_ms < id.created,
8111×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
81222×
                    _ => return false,
813
                }
814
            }
8150×
            false
81627×
        })
81727×
    }
818
819106×
    fn check_ref_attest(
820106×
        &self,
821106×
        sa: &SignedAttest,
822106×
        name: &str,
823106×
        old_state: &ObjectRef,
824106×
        new_state: &ObjectRef,
825106×
        last_serial: Option<u64>,
826106×
        allow_equal: bool,
827106×
    ) -> std::result::Result<u64, String> {
828104×
        let serial =
829106×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
830104×
        self.verify_attest_signature(sa)?;
831104×
        Ok(serial)
832106×
    }
833
834
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
835
    /// attestation describes this update of this repository with a serial
836
    /// past the last seen.
837179×
    fn check_ref_attest_body(
838179×
        &self,
839179×
        sa: &SignedAttest,
840179×
        name: &str,
841179×
        old_state: &ObjectRef,
842179×
        new_state: &ObjectRef,
843179×
        last_serial: Option<u64>,
844179×
        allow_equal: bool,
845179×
    ) -> std::result::Result<u64, String> {
846
        let AttestBody::Ref {
847179×
            name: n,
848179×
            old_state: o,
849179×
            new_state: nw,
850179×
            serial,
851179×
        } = &sa.attest.body
852
        else {
8530×
            return Err("attestation is not a ref attestation".into());
854
        };
855179×
        if n != name || o != old_state || nw != new_state {
8561×
            return Err("attestation does not describe this update".into());
857178×
        }
858178×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8590×
            return Err("attestation is for a different repository".into());
860178×
        }
861178×
        if let Some(last) = last_serial {
86293×
            if *serial < last || (*serial == last && !allow_equal) {
8631×
                return Err(format!(
8641×
                    "attestation serial {serial} is not greater than the last seen {last}"
8651×
                ));
86692×
            }
86785×
        }
868177×
        Ok(*serial)
869179×
    }
870
871
    /// An attestation's first signature verifies with its signer's
872
    /// identity, which must be stored here.
873177×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
874177×
        let r = sa.attest.hash();
875177×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
876177×
        let id = self
877177×
            .store
878177×
            .get_identity(&sig.key)
879177×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
880171×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
881177×
    }
882
883
    /// Accept a push (spec §16.4). Without a trust policy every repository
884
    /// is unverified, so unsigned changes and unattested updates are accepted;
885
    /// attestations that are present must still be valid. With a policy,
886
    /// every change and update is checked against it. A newer policy in the
887
    /// push is applied first when it is signed by the current roots.
888320×
    pub fn receive_push(
889320×
        &self,
890320×
        bundle: Bundle,
891320×
        updates: Vec<RefUpdate>,
892320×
        policy: Option<SignedPolicy>,
893320×
        tags: Vec<crate::protocol::TagRef>,
894320×
    ) -> Result<Vec<RefResult>> {
895320×
        Ok(self
896320×
            .receive_push_report(bundle, updates, policy, tags)?
897
            .results)
898320×
    }
899
900
    /// `receive_push` with what a host wants to log: each accepted
901
    /// reference's old and new state and heads, and the changes this push
902
    /// stored (hub spec §6.12).
903369×
    pub fn receive_push_report(
904369×
        &self,
905369×
        bundle: Bundle,
906369×
        updates: Vec<RefUpdate>,
907369×
        policy: Option<SignedPolicy>,
908369×
        tags: Vec<crate::protocol::TagRef>,
909369×
    ) -> Result<PushReport> {
910
        // Updates are checked against the head as it is now, not as this
911
        // handle first read it (oxygenhub#249): another push may have
912
        // landed since.
913369×
        self.refresh()?;
914369×
        let mut report = PushReport::default();
915369×
        let results = &mut report.results;
916369×
        if let Some(sp) = policy {
91736×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
91834×
                Ok(()) => {
91934×
                    results.push(RefResult {
92034×
                        name: "policy".into(),
92134×
                        ok: true,
92234×
                        reason: format!("serial {}", sp.policy.serial),
92334×
                    });
92434×
                }
9252×
                Err(e) => {
9262×
                    results.push(RefResult {
9272×
                        name: "policy".into(),
9282×
                        ok: false,
9292×
                        reason: e,
9302×
                    });
9312×
                    for u in updates {
9320×
                        results.push(RefResult {
9330×
                            name: u.name,
9340×
                            ok: false,
9350×
                            reason: "policy update was rejected".into(),
9360×
                        });
9370×
                    }
9382×
                    return Ok(report);
939
                }
940
            }
941333×
        }
942367×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
943
        // A push of objects alone (one batch of a long history, oxygen#95)
944
        // names no reference: its outcome is reported as `objects`.
945367×
        let objects_only = updates.is_empty() && tags.is_empty();
946367×
        match self.import_bundle(&bundle, policy.is_some()) {
947361×
            Ok(imported) => {
948361×
                if objects_only {
94911×
                    results.push(RefResult {
95011×
                        name: OBJECTS_RESULT.into(),
95111×
                        ok: true,
95211×
                        reason: format!("{} changes stored", imported.len()),
95311×
                    });
954350×
                }
955361×
                report.imported = imported;
956
            }
9576×
            Err(e) => {
9586×
                if objects_only {
9590×
                    results.push(RefResult {
9600×
                        name: OBJECTS_RESULT.into(),
9610×
                        ok: false,
9620×
                        reason: e.to_string(),
9630×
                    });
9646×
                }
9656×
                for u in updates {
9666×
                    results.push(RefResult {
9676×
                        name: u.name,
9686×
                        ok: false,
9696×
                        reason: e.to_string(),
9706×
                    });
9716×
                }
9726×
                return Ok(report);
973
            }
974
        }
975361×
        let (op_ref, op) = self.head_op()?;
976361×
        let mut view = op.view.clone();
977361×
        let mut names = Vec::new();
978361×
        for u in updates {
979345×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
980345×
            let (ok, reason) = match outcome {
981315×
                Ok(()) => (true, String::new()),
98230×
                Err(e) => (false, e),
983
            };
984345×
            if ok {
985315×
                names.push(u.name.clone());
986315×
                let heads = self
987315×
                    .store
988315×
                    .get_state(&u.new_state)
989315×
                    .map(|s| s.heads)
990315×
                    .unwrap_or_default();
991315×
                report.updated.push(RefUpdated {
992315×
                    name: u.name.clone(),
993315×
                    old_state: u.old_state,
994315×
                    new_state: u.new_state,
995315×
                    heads,
996315×
                });
99730×
            }
998345×
            results.push(RefResult {
999345×
                name: u.name,
1000345×
                ok,
1001345×
                reason,
1002345×
            });
1003
        }
1004361×
        for t in &tags {
100522×
            let name = format!("tags/{}", t.name);
100622×
            if t.is_withdrawal() {
10073×
                match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut TagCheck::Received)
1008
                {
10092×
                    Ok(removed) => {
1010
                        // A withdrawal is an update to nothing, as a
1011
                        // bookmark's deletion is.
10122×
                        if removed {
10132×
                            report.updated.push(RefUpdated {
10142×
                                name: name.clone(),
10152×
                                old_state: t.state,
10162×
                                new_state: ObjectRef::ZERO,
10172×
                                heads: vec![],
10182×
                            });
10192×
                        }
10202×
                        names.push(name.clone());
10212×
                        results.push(RefResult {
10222×
                            name,
1023
                            ok: true,
10242×
                            reason: if removed {
10252×
                                "withdrawn"
1026
                            } else {
10270×
                                "already withdrawn"
1028
                            }
10292×
                            .into(),
1030
                        });
1031
                    }
10321×
                    Err(e) => results.push(RefResult {
10331×
                        name,
10341×
                        ok: false,
10351×
                        reason: e.reason,
10361×
                    }),
1037
                }
10383×
                continue;
103919×
            }
104019×
            let new = !view.tags.contains_key(&t.name);
104119×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
1042
                Ok(()) => {
1043
                    // A tag new here is an update too, so a hub can start
1044
                    // its pipeline's tag jobs (oxygenflow#24); one it
1045
                    // already had, sent again, is not.
104614×
                    if new {
104713×
                        report.updated.push(RefUpdated {
104813×
                            name: name.clone(),
104913×
                            old_state: ObjectRef::ZERO,
105013×
                            new_state: t.state,
105113×
                            heads: t.heads.clone(),
105213×
                        });
105313×
                    }
105414×
                    names.push(name.clone());
105514×
                    results.push(RefResult {
105614×
                        name,
105714×
                        ok: true,
105814×
                        reason: String::new(),
105914×
                    });
1060
                }
10615×
                Err(e) => results.push(RefResult {
10625×
                    name,
10635×
                    ok: false,
10645×
                    reason: e.reason,
10655×
                }),
1066
            }
1067
        }
1068361×
        if !names.is_empty() {
1069317×
            self.record_op(
1070317×
                &[op_ref],
1071317×
                &format!("push received: {}", names.join(" ")),
1072317×
                view,
10733×
            )?;
107444×
        }
1075358×
        Ok(report)
1076369×
    }
1077
1078
    /// Check an update's attestation against the latest one for its
1079
    /// reference and store it as the new latest. Failures say what was
1080
    /// being done, for which reference, so a refused push can be diagnosed
1081
    /// from its reason alone.
1082106×
    fn record_update_attest(
1083106×
        &self,
1084106×
        u: &RefUpdate,
1085106×
        sa: &SignedAttest,
1086106×
    ) -> std::result::Result<(), String> {
1087106×
        let name = &u.name;
1088106×
        let last = self
1089106×
            .latest_ref_attest(name)
1090106×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1091106×
            .and_then(|(_, a)| match a.attest.body {
109265×
                AttestBody::Ref { serial, .. } => Some(serial),
10930×
                _ => None,
109465×
            });
1095106×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1096104×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1097104×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1098103×
        for sig in &sa.sigs {
1099103×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1100
        }
1101103×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1102
        // Signed by a short-lived key: a host records when it accepted it.
1103100×
        let certified = sa
1104100×
            .sigs
1105100×
            .first()
1106100×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
1107100×
        if certified {
11086×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
110994×
        }
1110100×
        Ok(())
1111106×
    }
1112
1113
    /// Record that this host accepted attestation `r` now, signed with its
1114
    /// acceptor key (spec §14.7); nothing without one.
111511×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
111611×
        let Some(acceptor) = &self.acceptor else {
11177×
            return Ok(());
1118
        };
11194×
        let (id, sk) = (&acceptor.0, &acceptor.1);
11204×
        let attest = Attest {
11214×
            repo: self.id()?,
11224×
            hlc: Hlc::now(),
11234×
            body: AttestBody::Accepted { attest: *r },
1124
        };
11254×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
11264×
        self.store.put_identity(id)?;
11274×
        let a = self.store.put_attest(&attest)?;
11284×
        self.store.put_signature(&a, &sig)?;
11294×
        self.store.index_add_pub("accepted", r, &a)?;
11304×
        Ok(())
113111×
    }
1132
1133
    /// The host's acceptance of attestation `r`, if one was recorded.
1134227×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1135227×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1136206×
            return Ok(None);
1137
        };
1138
        Ok(Some(SignedAttest {
113921×
            attest: self.store.get_attest(&a)?,
114021×
            sigs: self.store.signatures(&a)?,
1141
        }))
1142227×
    }
1143
1144
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1145
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1146
    /// signer's certificate and accepts `sa`; else the attestation's own
1147
    /// time, which the signer chose.
114831×
    pub(crate) fn certified_time(
114931×
        &self,
115031×
        signer: &KeyId,
115131×
        sa: &SignedAttest,
115231×
        accepted: Option<&SignedAttest>,
115331×
    ) -> u64 {
115431×
        self.issuer_acceptance(signer, sa, accepted)
115531×
            .unwrap_or(sa.attest.hlc.wall_ms)
115631×
    }
1157
1158
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1159
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
1160101×
    pub(crate) fn issuer_acceptance(
1161101×
        &self,
1162101×
        signer: &KeyId,
1163101×
        sa: &SignedAttest,
1164101×
        accepted: Option<&SignedAttest>,
1165101×
    ) -> Option<u64> {
1166101×
        let acc = accepted?;
116746×
        let c = self.store.certificate_of(signer).ok().flatten()?;
116846×
        let cert = self.store.get_certificate(&c).ok()?;
116946×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11700×
            return None;
1171
        };
117246×
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
117343×
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
117443×
        (*attest == sa.attest.hash()
117542×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
117643×
        .then_some(acc.attest.hlc.wall_ms)
1177101×
    }
1178
1179
    /// Keep an acceptance this repository was given for attestation `r`
1180
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1181
    /// what it accepts.
11829×
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
11839×
        let a = self.store.put_attest(&acc.attest)?;
118411×
        for sig in &acc.sigs {
118511×
            self.store.put_signature(&a, sig)?;
1186
        }
11879×
        self.store.index_add_pub("accepted", r, &a)?;
11889×
        Ok(())
11899×
    }
1190
1191
    /// A fetched bookmark's attestation by a signer the policy does not
1192
    /// list itself: a delegate or a short-lived key, whose authority
1193
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1194
    /// attestation's integrated time when the host's log gives one; else
1195
    /// as before, at the host's acceptance for a certified signer, when it
1196
    /// countersigned one, or at the attestation's own time, and said so
1197
    /// when the host keeps a log. Failing at the integrated time but not
1198
    /// as before is a note while logs are new; a large gap between the
1199
    /// claimed and the integrated time is a note.
1200
    #[allow(clippy::too_many_arguments)]
120127×
    pub(crate) fn authorize_in_time(
120227×
        &self,
120327×
        p: &crate::policy::Policy,
120427×
        remote_name: &str,
120527×
        r: &crate::protocol::RemoteRef,
120627×
        sa: &SignedAttest,
120727×
        signer: &KeyId,
120827×
        log: &super::transparency::LogCheck,
120927×
        notes: &mut Vec<String>,
121027×
    ) -> Result<()> {
1211
        use super::transparency::{gap_note, judge, Timed};
121227×
        let own = sa.attest.hlc.wall_ms;
121327×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
121427×
        let time = log.time_of(&r.name);
121529×
        let check = |t_delegate: u64, t_cert: u64| {
121629×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
121727×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
121829×
        };
121927×
        let before = if at != own {
12207×
            "the host's acceptance"
1221
        } else {
122220×
            "the time it claims"
1223
        };
122427×
        let what = format!("{remote_name}/{}", r.name);
122527×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1226
            Timed::Refused => {
12271×
                return fail(format!(
1228
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
12291×
                    signer.short(12)
1230
                ))
1231
            }
12323×
            Timed::Integrated => {}
12331×
            Timed::Disagrees => notes.push(format!(
1234
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
12351×
                signer.short(12),
12361×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1237
            )),
12381×
            Timed::Fallback if log.kept => notes.push(format!(
1239
                "{what}: {} checked at {before}, not at a witnessed time: {}",
12401×
                signer.short(12),
12411×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1242
            )),
124321×
            Timed::Fallback => {}
1244
        }
124526×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
12462×
            notes.push(format!("{what}'s attestation {n}"));
124724×
        }
124826×
        Ok(())
124927×
    }
1250
1251
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1252
    /// at `old_state`, is never the bookmark a non-bare repository has
1253
    /// checked out (a bare one's default is its host's to protect, see
1254
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1255
    /// an attestation by a key that may update it.
1256
    /// The deletion's attestation stays the bookmark's latest, so an older
1257
    /// one cannot be replayed to bring it back.
12583×
    fn apply_deletion(
12593×
        &self,
12603×
        view: &mut View,
12613×
        u: &RefUpdate,
12623×
        policy: Option<&crate::policy::Policy>,
12633×
    ) -> std::result::Result<(), String> {
12643×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
12650×
            return Err(format!("no bookmark {:?} to delete", u.name));
1266
        };
12673×
        if current != u.old_state {
12680×
            return Err("stale: the remote bookmark has moved; pull first".into());
12693×
        }
12703×
        if !self.is_bare() && u.name == self.config.bookmark {
12711×
            return Err(format!(
12721×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
12731×
                u.name
12741×
            ));
12752×
        }
12762×
        if let Some(p) = policy {
12770×
            let Some(sa) = &u.attestation else {
12780×
                return Err(format!(
12790×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12800×
                    u.name
12810×
                ));
1282
            };
12830×
            let signer = sa
12840×
                .sigs
12850×
                .first()
12860×
                .map(|s| s.key)
12870×
                .ok_or("attestation carries no signature")?;
1288
            // Received now: the receiver's own clock is the trusted time.
12890×
            let now = Hlc::now().wall_ms;
12900×
            if !p.authorizes(&signer, &u.name)
12910×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12920×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1293
            {
12940×
                return Err(format!(
12950×
                    "key {} may not delete {:?} under this repository's policy",
12960×
                    signer.short(12),
12970×
                    u.name
12980×
                ));
12990×
            }
13002×
        }
13012×
        if let Some(sa) = &u.attestation {
13021×
            self.record_update_attest(u, sa)?;
13031×
        }
13042×
        view.bookmarks.remove(&u.name);
13052×
        Ok(())
13063×
    }
1307
1308345×
    fn apply_update(
1309345×
        &self,
1310345×
        view: &mut View,
1311345×
        u: &RefUpdate,
1312345×
        policy: Option<&crate::policy::Policy>,
1313345×
    ) -> std::result::Result<(), String> {
1314345×
        if u.name == "policy" {
13150×
            return Err(
13160×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
13170×
            );
1318345×
        }
1319345×
        let empty = self
1320345×
            .store
1321345×
            .put_state(&StateObject::new(vec![]))
1322345×
            .map_err(|e| e.to_string())?;
1323345×
        if u.new_state.is_zero() {
13243×
            return self.apply_deletion(view, u, policy);
1325342×
        }
1326342×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1327342×
        if current != u.old_state {
132810×
            return Err("stale: the remote bookmark has moved; pull first".into());
1329332×
        }
1330332×
        let new_state = self
1331332×
            .store
1332332×
            .get_state(&u.new_state)
1333332×
            .map_err(|_| "new state object is missing".to_string())?;
1334619×
        for h in &new_state.heads {
1335619×
            if !self.store.has(h) {
13361×
                return Err(format!("head {} is missing", h.short(12)));
1337618×
            }
1338
        }
1339331×
        if !u.force {
1340330×
            let old_heads = self
1341330×
                .store
1342330×
                .get_state(&current)
1343330×
                .map_err(|e| e.to_string())?
1344
                .heads;
1345330×
            let closure = self
1346330×
                .closure_in_store(&new_state.heads)
1347330×
                .map_err(|e| e.to_string())?;
1348330×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
13491×
                return Err(format!(
13501×
                    "not a fast-forward: current head {} would be dropped (use --force)",
13511×
                    h.short(12)
13521×
                ));
1353329×
            }
13541×
        }
1355330×
        if let Some(p) = policy {
135659×
            let Some(sa) = &u.attestation else {
13571×
                return Err(format!(
13581×
                    "{:?} requires a signed reference attestation under this repository's policy",
13591×
                    u.name
13601×
                ));
1361
            };
136258×
            let signer = sa
136358×
                .sigs
136458×
                .first()
136558×
                .map(|s| s.key)
136658×
                .ok_or("attestation carries no signature")?;
1367
            // Received now: the receiver's own clock is the trusted time.
136858×
            let now = Hlc::now().wall_ms;
136958×
            if !p.authorizes(&signer, &u.name)
137019×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
137116×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1372
            {
137310×
                return Err(format!(
137410×
                    "key {} may not update {:?} under this repository's policy",
137510×
                    signer.short(12),
137610×
                    u.name
137710×
                ));
137848×
            }
137948×
            let old_heads = self
138048×
                .store
138148×
                .get_state(&current)
138248×
                .map_err(|e| e.to_string())?
1383
                .heads;
138448×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1385271×
        }
1386319×
        if let Some(sa) = &u.attestation {
1387105×
            self.record_update_attest(u, sa)?;
1388214×
        }
1389313×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1390313×
        Ok(())
1391345×
    }
1392
1393
    // ------------------------------------------------------------ client side
1394
13951513×
    fn remote_url(&self, name: &str) -> Result<String> {
13961513×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13973×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13983×
            RepoError::Msg(match names.as_slice() {
13993×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
14001×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1401
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
14021×
                    names.join(", "),
14031×
                    names[0],
14041×
                    names[0]
1405
                ),
14060×
                _ => format!(
1407
                    "no remote named {name:?}; this repository has {}",
14080×
                    names.join(", ")
1409
                ),
1410
            })
14113×
        })
14121513×
    }
1413
1414
    /// Refuse a remote that is another repository. An **unbound** remote
1415
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1416
    /// for pushes, which bind it to this repository's id (spec §16.1).
1417820×
    fn check_remote_id(
1418820×
        &self,
1419820×
        remote: &dyn crate::protocol::Remote,
1420820×
        remote_name: &str,
1421820×
        allow_unbound: bool,
1422820×
    ) -> Result<()> {
1423820×
        let theirs = remote.repo_id()?;
1424819×
        if theirs == self.id()? {
1425789×
            return Ok(());
142630×
        }
142730×
        if theirs == crate::protocol::UNBOUND_ID {
142827×
            if allow_unbound {
142926×
                return Ok(());
14301×
            }
14311×
            return fail(format!(
1432
                "remote {remote_name:?} is empty and unbound: push to it first"
1433
            ));
14343×
        }
14353×
        fail(format!(
1436
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1437
        ))
1438820×
    }
1439
1440
    /// Credentials and trust for a remote: `remote.<name>.token` and
1441
    /// `remote.<name>.ca`, else the defaults for its URL
1442
    /// ([`Repo::fill_credentials`]).
14431128×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
14441128×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
14451128×
        let mut options = RemoteOptions {
14461128×
            repo_id: self.id().ok(),
14471128×
            token: self.config.remote_tokens.get(name).cloned(),
14481128×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
14491128×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
14501128×
            ..RemoteOptions::default()
14511128×
        };
14521128×
        self.fill_credentials(&url, &mut options);
14531128×
        options
14541128×
    }
1455
1456
    /// The user's credential store (`credentials.toml` beside the user
1457
    /// configuration file).
14581153×
    pub fn credentials(&self) -> crate::credentials::Credentials {
14591153×
        crate::credentials::Credentials::at(
14601153×
            self.user_config
14611153×
                .parent()
14621153×
                .map(Path::to_path_buf)
14631153×
                .unwrap_or_else(default_home),
1464
        )
14651153×
    }
1466
1467
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1468
    /// then the user's credential store for its hub, then a remote on the
1469
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1470
    /// When the token is not this remote's own or the environment's, the
1471
    /// other tokens enclosing checkouts hold for the hub are kept to try
1472
    /// if it is refused: a stale stored login must not hide a parent's
1473
    /// good token (oxygen#112).
14741154×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14751154×
        if options.token.is_some() && options.ca.is_some() {
14761×
            return;
14771153×
        }
14781153×
        let explicit =
14791153×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14801153×
        let stored = self.credentials().options_for(url);
14811153×
        options.token = options.token.take().or(stored.token);
14821153×
        options.ca = options.ca.take().or(stored.ca);
14831153×
        let enclosing = self.enclosing_credentials(url);
14841153×
        if options.token.is_none() {
14851143×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
148610×
        }
14871153×
        if options.ca.is_none() {
14881147×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
14896×
        }
14901153×
        if !explicit {
14911146×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
14925×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
14932×
                    options.fallback_tokens.push(t);
14943×
                }
1495
            }
14967×
        }
14971154×
    }
1498
1499
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1500
    /// checkouts, nearest first.
15011153×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
15021153×
        let mut out = Vec::new();
15031153×
        let Some(hub) = crate::credentials::hub_of(url) else {
1504994×
            return out;
1505
        };
1506159×
        let mut at = self.root.parent();
1507644×
        while let Some(dir) = at {
1508485×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
15090×
                break;
1510
            };
1511485×
            for (key, remote_url) in &cfg {
151215×
                let Some(name) = key
151315×
                    .strip_prefix("remote.")
151415×
                    .and_then(|k| k.strip_suffix(".url"))
1515
                else {
15167×
                    continue;
1517
                };
15188×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
15191×
                    continue;
15207×
                }
15217×
                out.push((
15227×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
15237×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
15247×
                ));
1525
            }
1526485×
            at = dir.parent();
1527
        }
1528159×
        out
15291153×
    }
1530
1531
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1532
    /// no changes and no reference updates, which the receiver stores.
15330×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
15340×
        let remote = self.open_named_remote(remote_name)?;
15350×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
15360×
        let mut bundle = Bundle::default();
15370×
        for r in seals {
15380×
            let attest = self.store.get_attest(r)?;
15390×
            let sigs = self.store.signatures(r)?;
15400×
            bundle
15410×
                .attests
15420×
                .push(crate::protocol::SignedAttest { attest, sigs });
1543
        }
15440×
        let results = remote.push(bundle, vec![], None, vec![])?;
15450×
        if let Some(r) = results.iter().find(|r| !r.ok) {
15460×
            return fail(format!("{}: {}", r.name, r.reason));
15470×
        }
15480×
        Ok(())
15490×
    }
1550
1551
    /// The remote whose URL starts with `base` (a hub), if configured.
15524×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
15534×
        let base = base.trim_end_matches('/');
15544×
        self.config
15554×
            .remotes
15564×
            .iter()
15574×
            .find(|(_, url)| url.trim_end_matches('/') == base)
15584×
            .map(|(name, _)| name.clone())
15594×
    }
1560
1561
    /// Open a remote by name or, failing that, by URL with the default
1562
    /// credentials (see [`Repo::credentials_for`]).
15630×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15640×
        if let Some(name) = self.remote_for_url(url) {
15650×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15660×
        }
15670×
        let options = RemoteOptions {
15680×
            repo_id: self.id().ok(),
15690×
            ..self.credentials_for(url)
15700×
        };
15710×
        Ok((url.to_string(), open_remote(url, &options)?))
15720×
    }
1573
1574
    /// Credentials for a URL: those of the configured remote with that
1575
    /// URL, else the environment's.
15764×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
15774×
        match self.remote_for_url(url) {
15784×
            Some(name) => self.remote_options(&name),
15790×
            None => RemoteOptions {
15800×
                repo_id: self.id().ok(),
15810×
                ..self.credentials_for(url)
15820×
            },
1583
        }
15844×
    }
1585
15861111×
    pub(crate) fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15871111×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15881111×
    }
1589
1590220×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1591220×
        self.oxy
1592220×
            .join("remotes")
1593220×
            .join(remote)
1594220×
            .join(format!("{bookmark}.serial"))
1595220×
    }
1596
159773×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
159873×
        fs::read_to_string(self.serial_path(remote, bookmark))
159973×
            .ok()
160073×
            .and_then(|s| s.trim().parse().ok())
160173×
    }
1602
1603147×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1604147×
        let p = self.serial_path(remote, bookmark);
1605147×
        fs::create_dir_all(p.parent().unwrap())?;
1606147×
        write_atomic(&p, serial.to_string().as_bytes())
1607147×
    }
1608
1609474×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1610474×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1611474×
    }
1612
1613
    /// The highest policy serial `remote` has ever presented.
1614402×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1615402×
        fs::read_to_string(self.policy_serial_path(remote))
1616402×
            .ok()
1617402×
            .and_then(|s| s.trim().parse().ok())
1618402×
    }
1619
162072×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
162172×
        let p = self.policy_serial_path(remote);
162272×
        fs::create_dir_all(p.parent().unwrap())?;
162372×
        write_atomic(&p, serial.to_string().as_bytes())
162472×
    }
1625
162632×
    fn lazy_dir(&self) -> PathBuf {
162732×
        self.oxy.join("lazy")
162832×
    }
1629
1630
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
16315×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
16325×
        fs::create_dir_all(self.lazy_dir())?;
16335×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
16345×
    }
1635
1636
    /// Which remote promised an absent blob, if any.
163717×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
163817×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
163917×
            .ok()
164017×
            .map(|s| s.trim().to_string())
164117×
    }
1642
1643
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
16445×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
16455×
        let Some(remote_name) = self.lazy_remote(blob) else {
16460×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1647
        };
16485×
        let remote = self.open_named_remote(&remote_name)?;
16495×
        let objects = remote.objects(&[*blob])?;
165011×
        for (ty, body) in objects {
165111×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
165211×
                self.store.put(ty, &body)?;
16530×
            }
1654
        }
16555×
        if !self.store.has(blob) {
16560×
            return fail(format!(
1657
                "{remote_name} did not send blob {}",
16580×
                blob.short(12)
1659
            ));
16605×
        }
16615×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
16625×
        Ok(())
16635×
    }
1664
1665
    /// After importing from `remote`, record every blob the changes reference
1666
    /// that the store lacks as lazily available from that remote.
16675×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
16685×
        let mut n = 0;
16695×
        for h in changes {
16704×
            let c = self.store.get_change(h)?;
167113×
            for e in &c.edits {
167213×
                if let Edit::Replace { old, new, .. } = e {
16736×
                    for b in [old, new].into_iter().flatten() {
16746×
                        if !self.store.has(b) {
16754×
                            self.register_lazy(b, remote)?;
16764×
                            n += 1;
16772×
                        }
1678
                    }
16797×
                }
1680
            }
1681
        }
16825×
        Ok(n)
16835×
    }
1684
1685
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1686402×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1687402×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1688540×
        for st in view
1689402×
            .bookmarks
1690402×
            .values()
1691402×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1692
        {
1693540×
            if let Ok(s) = self.store.get_state(st) {
1694540×
                have.extend(s.heads);
1695540×
            }
1696
        }
1697402×
        have.extend(view.workspaces.values().copied());
1698402×
        Ok(have.into_iter().collect())
1699402×
    }
1700
1701
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1702408×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1703408×
        let remote = self.open_named_remote(remote_name)?;
1704405×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1705403×
        let resp = remote.refs()?;
1706
        // The host's transparency log (spec §14.8): a fork fails here.
1707402×
        let log = self.check_log(
1708402×
            &self.remote_url(remote_name)?,
1709402×
            self.config.remote_cas.get(remote_name).map(Path::new),
1710402×
            &resp,
17110×
        )?;
1712402×
        let mut log_notes = log.notes.clone();
1713
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1714
        // and signed by roots we trust, or on first contact. A remote that
1715
        // once presented a policy may never present none or an older one:
1716
        // that is a downgrade. A remote that never presented one is
1717
        // unverified, and this fetch is checked only as far as possible.
1718402×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1719402×
        let seen = self.remote_policy_serial(remote_name);
1720402×
        let mut unverified = false;
1721402×
        match &resp.policy {
172238×
            Some(sp) => {
172338×
                if seen.is_some_and(|s| sp.policy.serial < s) {
17240×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
172538×
                }
172614×
                match &local_policy {
172714×
                    Some(l) if sp.policy.serial < l.serial => {}
172814×
                    Some(l) if sp.policy.serial == l.serial => {
172910×
                        if sp.policy.hash() != l.hash() {
17300×
                            return fail(format!(
1731
                                "{remote_name} presents a different policy with the same serial {}",
1732
                                l.serial
1733
                            ));
173410×
                        }
1735
                    }
1736
                    _ => {
173728×
                        self.adopt_policy_chain(
173828×
                            &resp.history,
173928×
                            sp,
174028×
                            &format!("oxy fetch {remote_name}"),
1741
                        )
174228×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1743
                    }
1744
                }
174538×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1746
            }
1747
            None => {
1748364×
                if seen.is_some() {
17490×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1750364×
                }
1751364×
                unverified = true;
1752
            }
1753
        }
1754402×
        let policy = if unverified {
1755364×
            None
1756
        } else {
175738×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1758
        };
1759402×
        let (op_ref, op) = self.head_op()?;
1760402×
        let mut view = op.view.clone();
1761402×
        let have = self.known_heads(&view)?;
1762402×
        let mut report = Vec::new();
1763402×
        let mut skipped = Vec::new();
1764402×
        let max_blob = self.config.max_blob;
1765429×
        for r in resp.refs {
1766429×
            let needed = {
1767429×
                let _t = crate::timing::phase("fetch: negotiate");
1768429×
                remote.negotiate(&have, &r.heads)?
1769
            };
1770429×
            let bundle = {
1771429×
                let _t = crate::timing::phase("fetch: bundle");
1772429×
                remote.fetch(&needed, max_blob)?
1773
            };
1774
            // Changes are not individually re-verified here: the bookmark's
1775
            // attestation (checked below) binds its whole state, and the
1776
            // receiver of the push verified the added changes at that time.
1777
            // A shallow repository takes changes whose dependencies it never
1778
            // held (below what it cloned), as its clone did (#137).
1779429×
            let shallow = self.is_shallow();
1780429×
            let imported = {
1781429×
                let _t = crate::timing::phase("fetch: import");
1782429×
                if shallow {
17832×
                    self.import_bundle_shallow(&bundle, false)?
1784
                } else {
1785427×
                    self.import_bundle(&bundle, false)?
1786
                }
1787
            };
1788429×
            if shallow {
17892×
                self.refresh_boundary(&imported)?;
1790427×
            }
1791429×
            if max_blob.is_some() {
17924×
                self.register_missing_blobs(&imported, remote_name)?;
1793425×
            }
1794429×
            let boundary = if shallow {
17952×
                self.boundary()
1796
            } else {
1797427×
                BTreeSet::new()
1798
            };
1799559×
            for h in &r.heads {
1800559×
                if !self.store.has(h) && !boundary.contains(h) {
18010×
                    return fail(format!("remote did not send head {}", h.short(12)));
1802559×
                }
1803
            }
1804429×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1805429×
            if state != r.state {
18060×
                return fail(format!(
1807
                    "remote state {} does not match its heads",
18080×
                    r.state.short(12)
1809
                ));
1810429×
            }
1811429×
            if let Some(p) = &policy {
181241×
                let Some(sa) = &r.attestation else {
18130×
                    return fail(format!(
1814
                        "{remote_name}/{} has no attestation, which its policy requires",
1815
                        r.name
1816
                    ));
1817
                };
181841×
                let signer = sa
181941×
                    .sigs
182041×
                    .first()
182141×
                    .map(|s| s.key)
182241×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
182341×
                if !p.authorizes(&signer, &r.name) {
182420×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
182521×
                }
1826388×
            }
1827429×
            if let Some(sa) = &r.attestation {
1828
                let AttestBody::Ref {
182973×
                    old_state,
183073×
                    new_state,
1831
                    ..
183273×
                } = &sa.attest.body
1833
                else {
18340×
                    return fail("remote sent a non-ref attestation for a bookmark");
1835
                };
183673×
                let (old_state, new_state) = (*old_state, *new_state);
183773×
                let serial = self
183873×
                    .check_ref_attest_body(
183973×
                        sa,
184073×
                        &r.name,
184173×
                        &old_state,
184273×
                        &new_state,
184373×
                        self.last_seen_serial(remote_name, &r.name),
1844
                        true,
1845
                    )
184673×
                    .map_err(|e| {
18470×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
18480×
                    })?;
184973×
                if new_state != r.state {
18500×
                    return fail(format!(
1851
                        "attestation for {}/{} does not cover its current state",
1852
                        remote_name, r.name
1853
                    ));
185473×
                }
1855
                // A signature this client cannot verify (its signer unknown
1856
                // here, as from a host that did not send the identity, or
1857
                // bad) fails that bookmark alone: it stays as it was and
1858
                // the rest are fetched (oxygenhub#266). The current
1859
                // bookmark, which a pull would take, still fails the fetch.
1860
                // A policy's requirements were checked above and still fail.
186173×
                if let Err(e) = self.verify_attest_signature(sa) {
186212×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
186312×
                    if r.name == self.config.bookmark {
18643×
                        return fail(why);
18659×
                    }
18669×
                    skipped.push((r.name, why));
18679×
                    continue;
186861×
                }
186961×
                let ar = self.store.put_attest(&sa.attest)?;
187061×
                for sig in &sa.sigs {
187161×
                    self.store.put_signature(&ar, sig)?;
1872
                }
187361×
                self.record_serial(remote_name, &r.name, serial)?;
1874356×
            }
1875417×
            view.remotes
1876417×
                .entry(remote_name.to_string())
1877417×
                .or_default()
1878417×
                .insert(r.name.clone(), state);
1879417×
            report.push((r.name, r.heads, imported.len()));
1880
        }
1881399×
        let mut new_tags = 0;
1882399×
        for t in &resp.tags {
188331×
            if view.tags.contains_key(&t.name) {
18847×
                continue;
188524×
            }
1886
            // Withdrawn here: the name is not used again.
188724×
            if self.tag_withdrawal(&t.name)?.is_some() {
18880×
                continue;
188924×
            }
1890
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
189124×
            let missing: Vec<ChangeHash> = t
189224×
                .heads
189324×
                .iter()
189424×
                .filter(|h| !self.store.has(h))
189524×
                .copied()
189624×
                .collect();
189724×
            if !missing.is_empty() {
18980×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
18990×
                let bundle = remote.fetch(&needed, max_blob)?;
19000×
                self.import_bundle(&bundle, false)?;
190124×
            }
190224×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
190324×
            let mut check = TagCheck::Fetched {
190424×
                remote: remote_name,
190524×
                log: &log,
190624×
                notes: &mut log_notes,
190724×
            };
190824×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
190922×
                Ok(()) => new_tags += 1,
1910
                // Nothing says when a short-lived key signed it: the tag is
1911
                // left out, said so, and the rest is fetched (oxygen#129).
19122×
                Err(e) if e.untimed => {
19132×
                    skipped.push((format!("tags/{}", t.name), e.reason));
19142×
                }
19150×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1916
            }
1917
        }
1918
        // The remote withdrew a tag this repository has: so does this one,
1919
        // once the withdrawal is checked as a push's would be; one that is
1920
        // not is left as it is, said so (oxygenhub#301).
1921399×
        let mut withdrawn_tags = Vec::new();
1922399×
        for t in &resp.withdrawn {
19231×
            if !view.tags.contains_key(&t.name) {
19240×
                continue;
19251×
            }
19261×
            let mut check = TagCheck::Fetched {
19271×
                remote: remote_name,
19281×
                log: &log,
19291×
                notes: &mut log_notes,
19301×
            };
19311×
            match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut check) {
19321×
                Ok(true) => withdrawn_tags.push(t.name.clone()),
19330×
                Ok(false) => {}
19340×
                Err(e) => skipped.push((
19350×
                    format!("tags/{}", t.name),
19360×
                    format!("withdrawn on {remote_name}, kept here: {}", e.reason),
19370×
                )),
1938
            }
1939
        }
1940399×
        if view != op.view {
1941383×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
194216×
        }
1943399×
        let _ = self.run_hook(
1944399×
            "post-fetch",
1945399×
            &format!(
1946
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1947399×
                json_str(remote_name),
1948414×
                json_array(report.iter().map(|(n, heads, _)| format!(
1949
                    "{{\"name\":{},\"heads\":{}}}",
1950414×
                    json_str(n),
1951544×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1952
                )))
1953
            ),
1954
        );
1955399×
        Ok(FetchReport {
1956399×
            refs: report,
1957399×
            unverified,
1958399×
            new_tags,
1959399×
            withdrawn_tags,
1960399×
            log_notes,
1961399×
            skipped,
1962399×
        })
1963408×
    }
1964
1965
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1966
    /// the changes within `depth` steps of its heads, and the boundary below.
19673×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
19683×
        let remote = self.open_named_remote(remote_name)?;
19693×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
19703×
        let resp = remote.refs()?;
19713×
        let bookmark = self.config.bookmark.clone();
19723×
        if let Some(sp) = &resp.policy {
19730×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
19740×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
19750×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
19763×
        }
19773×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
19780×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1979
        };
19803×
        if r.heads.is_empty() {
19810×
            return Ok(0);
19823×
        }
1983
        // Base: the remote's checkpoint of exactly these heads, without its
1984
        // graph blobs, which come in parts below (#137).
19853×
        let cp_bundle = {
19863×
            let _t = crate::timing::phase("shallow: checkpoint request");
19873×
            remote.checkpoint_index(&r.heads)?
1988
        };
1989
        // In one batch: a big state's checkpoint is tens of thousands of
1990
        // graph blobs and chunks, which stored one by one were each written
1991
        // loose and flushed (a VS Code clone ran at 27 objects a second).
19923×
        let objects: Vec<(ObjectType, &[u8])> = cp_bundle
19933×
            .objects
19943×
            .iter()
19959×
            .map(|(ty, body)| (*ty, body.as_slice()))
19963×
            .collect();
19973×
        let t_store = crate::timing::phase("shallow: store the checkpoint");
19983×
        let batch = self.store.begin_batch()?;
19993×
        let stored = self.store.put_many(&objects);
20003×
        batch.finish()?;
20013×
        drop(t_store);
20023×
        let cp_ref = objects
20033×
            .iter()
20043×
            .zip(stored?)
20059×
            .find(|((ty, _), _)| *ty == ObjectType::Checkpoint)
20063×
            .map(|(_, r)| r);
20073×
        let Some(cp_ref) = cp_ref else {
20080×
            return fail(format!("{remote_name} sent no checkpoint"));
2009
        };
2010
        // The graph blobs the payload names, with their chunks, a part at
2011
        // a time (#137): one answer for a big state was gigabytes, held
2012
        // whole on both sides. A remote that sent the whole checkpoint has
2013
        // left none to ask for.
20143×
        let cp = crate::objects::Checkpoint::decode(
20153×
            &self.store.get_typed(&cp_ref, ObjectType::Checkpoint)?,
20160×
        )?;
20173×
        let graphs: Vec<ObjectRef> = self
20183×
            .checkpoint_graph_blobs(&cp)?
20193×
            .into_iter()
20203×
            .filter(|b| !self.store.has(b))
20213×
            .collect();
2022
        {
20233×
            let _t = crate::timing::phase("shallow: the checkpoint's graphs, in parts");
20243×
            for part in graphs.chunks(CHECKPOINT_PART) {
20250×
                let objects = remote.objects(part)?;
20260×
                let objects: Vec<(ObjectType, &[u8])> = objects
20270×
                    .iter()
20280×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
20290×
                    .map(|(ty, body)| (*ty, body.as_slice()))
20300×
                    .collect();
20310×
                let batch = self.store.begin_batch()?;
20320×
                let stored = self.store.put_many(&objects);
20330×
                batch.finish()?;
20340×
                stored?;
2035
            }
20363×
            if let Some(b) = graphs.iter().find(|b| !self.store.has(b)) {
20370×
                return fail(format!(
2038
                    "{remote_name} did not send graph blob {}",
20390×
                    b.short(12)
2040
                ));
20413×
            }
2042
        }
20433×
        self.install_checkpoint(&bookmark, &cp_ref)?;
20443×
        let _t_blobs = crate::timing::phase("shallow: the binary files' blobs");
2045
        // The blobs of the state's opaque files come with no change when the
2046
        // window holds none of the changes that set them (#137): fetch them
2047
        // now, or under `filter.max-blob` leave them to be fetched on read.
20483×
        let base = State::from_checkpoint_history(&self.read_blob(&cp.payload)?)?;
20493×
        let mut missing: Vec<ObjectRef> = base
20503×
            .opaque_nodes()
20513×
            .iter()
20523×
            .flat_map(|n| base.live_blobs(n))
20533×
            .filter(|b| !self.store.has(b))
20543×
            .collect();
20553×
        missing.sort();
20563×
        missing.dedup();
20573×
        if self.config.max_blob.is_some() {
20581×
            for b in &missing {
20591×
                self.register_lazy(b, remote_name)?;
2060
            }
2061
        } else {
20622×
            for part in missing.chunks(512) {
20631×
                let objects = remote.objects(part)?;
20641×
                let objects: Vec<(ObjectType, &[u8])> = objects
20651×
                    .iter()
20662×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
20672×
                    .map(|(ty, body)| (*ty, body.as_slice()))
20681×
                    .collect();
20691×
                let batch = self.store.begin_batch()?;
20701×
                let stored = self.store.put_many(&objects);
20711×
                batch.finish()?;
20721×
                stored?;
2073
            }
20742×
            if let Some(b) = missing.iter().find(|b| !self.store.has(b)) {
20750×
                return fail(format!("{remote_name} did not send blob {}", b.short(12)));
20762×
            }
2077
        }
2078
        // History window. Depth 0 takes none (#137): the checkpoint holds
2079
        // every change's metadata, and its heads become the boundary, so a
2080
        // state of many heads (33,835 in the VS Code import) costs nothing
2081
        // to fetch.
20823×
        let imported = if depth == 0 {
20832×
            let mut boundary = self.boundary();
20842×
            boundary.extend(r.heads.iter().filter(|h| !self.store.has(h)).copied());
20852×
            self.write_boundary(&boundary)?;
20862×
            Vec::new()
2087
        } else {
20881×
            let wanted = remote.shallow(&r.heads, depth)?;
20891×
            let bundle = remote.fetch(&wanted, self.config.max_blob)?;
20901×
            self.import_bundle_shallow(&bundle, false)?
2091
        };
20923×
        if self.config.max_blob.is_some() {
20931×
            self.register_missing_blobs(&imported, remote_name)?;
20942×
        }
20953×
        self.refresh_boundary(&imported)?;
20963×
        if let Some(sa) = &r.attestation {
20970×
            let ar = self.store.put_attest(&sa.attest)?;
20980×
            for sig in &sa.sigs {
20990×
                self.store.put_signature(&ar, sig)?;
2100
            }
21010×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
21020×
                self.record_serial(remote_name, &r.name, serial)?;
21030×
            }
21043×
        }
21053×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
21063×
        let (op_ref, op) = self.head_op()?;
21073×
        let mut view = op.view.clone();
21083×
        view.remotes
21093×
            .entry(remote_name.to_string())
21103×
            .or_default()
21113×
            .insert(r.name.clone(), state);
21123×
        self.record_op(
21133×
            &[op_ref],
21143×
            &format!("oxy fetch {remote_name} --depth {depth}"),
21153×
            view,
21160×
        )?;
21173×
        Ok(imported.len())
21183×
    }
2119
2120
    /// Fetch, then take the union of the local bookmark's state with the
2121
    /// remote's: no merge change, conflicts become reified (spec §9.4).
2122108×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
2123108×
        let _wc = self.lock_working_copy()?;
2124108×
        let skipped = self.fetch(remote_name)?.skipped;
2125104×
        let (op_ref, op) = self.head_op()?;
2126104×
        let current = self.config.bookmark.clone();
2127104×
        let mut local_current = self.heads_of(&op.view, &current)?;
2128104×
        local_current.sort();
2129104×
        let mut view = op.view.clone();
2130104×
        let mut current_heads = local_current.clone();
2131104×
        let mut changed = false;
2132104×
        let mut others = Vec::new();
2133104×
        let tracked = op
2134104×
            .view
2135104×
            .remotes
2136104×
            .get(remote_name)
2137104×
            .cloned()
2138104×
            .unwrap_or_default();
2139109×
        for (name, remote_state) in tracked {
2140
            // Every local bookmark tracks the remote's of the same name;
2141
            // the current one may be new here.
2142109×
            let local_state = op.view.bookmarks.get(&name).copied();
2143109×
            if local_state.is_none() && name != current {
21441×
                continue;
2145108×
            }
2146108×
            if local_state == Some(remote_state) {
214710×
                continue;
214898×
            }
214998×
            let local = self.heads_of(&op.view, &name)?;
215098×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2151129×
            if remote_heads.iter().all(|h| local.contains(h)) {
21520×
                continue;
215398×
            }
215498×
            let mut all = local.clone();
215598×
            all.extend(remote_heads);
215698×
            let st = self.load_state_history(&all)?;
215798×
            let mut heads = st.maximal(&all);
215898×
            heads.sort();
215998×
            let mut sorted_local = local;
216098×
            sorted_local.sort();
216198×
            if heads == sorted_local {
21621×
                continue;
216397×
            }
216497×
            view.bookmarks.insert(
216597×
                name.clone(),
216697×
                self.store.put_state(&StateObject::new(heads.clone()))?,
2167
            );
216897×
            if name == current {
216995×
                changed = true;
217095×
                current_heads = heads;
217195×
            } else {
21722×
                others.push(name);
21732×
            }
2174
        }
2175104×
        if changed || !others.is_empty() {
217696×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
21778×
        }
2178
        // The working copy follows its bookmark whenever nothing would be
2179
        // lost, also when this pull brought nothing new but it had been
2180
        // left behind (oxygen#89).
2181104×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2182
        Ok(PullReport {
2183104×
            heads: if changed {
218495×
                current_heads
2185
            } else {
21869×
                local_current
2187
            },
2188104×
            changed,
2189104×
            checked_out,
2190104×
            others,
2191104×
            skipped,
2192
        })
2193108×
    }
2194
2195
    /// How many changes the working copy's bookmark has that its base
2196
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2197
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2198
    /// the bookmark or holds changes the bookmark lacks. History is read
2199
    /// only when the base and the bookmark's heads differ (oxygen#89).
22007×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
22017×
        let (_, wc) = self.working_copy()?;
22027×
        let mut base = wc.deps.clone();
22037×
        base.sort();
22047×
        let mut heads = self.bookmark_heads()?;
22057×
        heads.sort();
22067×
        if base == heads || heads.is_empty() {
22076×
            return Ok(None);
22081×
        }
22091×
        let state = self.load_state_history(&heads)?;
22101×
        if !base.iter().all(|h| state.contains(h)) {
22110×
            return Ok(None);
22121×
        }
22131×
        let had = if base.is_empty() {
22140×
            0
2215
        } else {
22161×
            self.load_state_history(&base)?.len()
2217
        };
22181×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
22197×
    }
2220
2221
    /// Bring the working copy to `heads`, the state of its bookmark
2222
    /// `bookmark`, when nothing would be lost: its base is part of that
2223
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2224
    /// with uncommitted work, the work comes along when the new changes
2225
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2226
    /// it followed only from exactly the bookmark's old heads, so a working
2227
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2228
    /// or a pull from another workspace) never caught up, and nothing said
2229
    /// so (oxygen#74, #89). Returns whether it moved.
2230104×
    pub fn follow_bookmark(
2231104×
        &self,
2232104×
        heads: &[ChangeHash],
2233104×
        bookmark: &str,
2234104×
        command: &str,
2235104×
    ) -> Result<bool> {
2236104×
        let snap = self.snapshot(command)?;
2237104×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2238104×
        let mut base = snap.base.maximal(&snap.wc.deps);
2239104×
        base.sort();
2240104×
        let mut target = heads.to_vec();
2241104×
        target.sort();
2242104×
        if base == target {
22438×
            return Ok(false);
224496×
        }
224596×
        let state = self.load_state_history(heads)?;
2246180×
        if !base.iter().all(|h| state.contains(h)) {
2247
            // The working copy holds changes the bookmark lacks: not ours to move.
22480×
            return Ok(false);
224996×
        }
225096×
        if clean {
225196×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
225296×
            Ok(true)
2253
        } else {
22540×
            Ok(self
22550×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
22560×
                .is_ok())
2257
        }
2258104×
    }
2259
2260
    /// Withdraw tag `tag` on `remote_name` (`oxy push --delete tags/NAME`,
2261
    /// oxygenhub#301): withdrawn here first when it still is a tag here
2262
    /// (`oxy tag delete`), then the withdrawal alone is sent, with its
2263
    /// signer's identity and certificate.
22643×
    pub fn push_tag_withdrawal(&self, remote_name: &str, tag: &str) -> Result<Vec<RefResult>> {
22653×
        let remote = self.open_named_remote(remote_name)?;
22663×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
22673×
        let resp = remote.refs()?;
22683×
        let name = format!("tags/{tag}");
22693×
        if resp.withdrawn.iter().any(|t| t.name == tag) {
22701×
            return Ok(vec![RefResult {
22711×
                name,
22721×
                ok: true,
22731×
                reason: "already withdrawn".into(),
22741×
            }]);
22752×
        }
22762×
        let Some(there) = resp.tags.iter().find(|t| t.name == tag) else {
22770×
            return fail(format!("{remote_name} has no tag {tag}"));
2278
        };
22792×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
22800×
            return fail(format!("{remote_name} enforces a trust policy; withdrawing a tag needs an identity (`oxy identity create`)"));
22812×
        }
22822×
        if self.tag_withdrawal(tag)?.is_none() {
22832×
            match self.view()?.tags.get(tag) {
22842×
                Some(st) if *st == there.state => {
22852×
                    self.tag_delete(tag, "")?;
2286
                }
2287
                Some(_) => {
22880×
                    return fail(format!(
2289
                        "tag {tag} names another state here than on {remote_name}"
2290
                    ))
2291
                }
2292
                None => {
22930×
                    return fail(format!(
2294
                        "there is no tag {tag} here to withdraw: `oxy fetch {remote_name}` first"
2295
                    ))
2296
                }
2297
            }
22980×
        }
22992×
        let Some(w) = self
23002×
            .withdrawn_refs()?
23012×
            .into_iter()
23022×
            .find(|w| w.name == tag && w.state == there.state)
2303
        else {
23040×
            return fail(format!(
2305
                "tag {tag} was withdrawn here at another state than {remote_name}'s"
2306
            ));
2307
        };
23082×
        let mut bundle = Bundle::default();
23092×
        let signers: Vec<KeyId> = w
23102×
            .attestation
23112×
            .iter()
23122×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
23132×
            .collect();
23142×
        for k in &signers {
23152×
            if let Ok(id) = self.identity(k) {
23162×
                bundle.objects.push((ObjectType::Identity, id.encode()));
23172×
            }
2318
        }
23192×
        self.attach_certificates_for(&mut bundle, &signers)?;
23202×
        remote.push(bundle, vec![], None, vec![w])
23213×
    }
2322
2323
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2324
    /// changes and attesting the reference when a key is available.
2325
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2326
    /// state, attested when we have an identity. The local bookmark, if
2327
    /// any, is kept; only the remote-tracking entry goes.
23288×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
23298×
        if let Some(tag) = bookmark.strip_prefix("tags/") {
23303×
            return self.push_tag_withdrawal(remote_name, tag);
23315×
        }
23325×
        let remote = self.open_named_remote(remote_name)?;
23335×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
23345×
        let resp = remote.refs()?;
23357×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
23361×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2337
        };
23384×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
23390×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
23404×
        }
23414×
        let attestation = match self.secret_key()? {
23422×
            Some(_) => Some(self.sign_attest(&Attest {
23432×
                repo: self.id()?,
23442×
                hlc: Hlc::now(),
23452×
                body: AttestBody::Ref {
23462×
                    name: bookmark.to_string(),
23472×
                    old_state: r.state,
23482×
                    new_state: ObjectRef::ZERO,
23492×
                    serial: r.last_serial.unwrap_or(0) + 1,
23502×
                },
23510×
            })?),
23522×
            None => None,
2353
        };
23544×
        let results = remote.push(
23554×
            Bundle::default(),
23564×
            vec![RefUpdate {
23574×
                name: bookmark.to_string(),
23584×
                old_state: r.state,
23594×
                new_state: ObjectRef::ZERO,
23604×
                force: true,
23614×
                attestation,
23624×
            }],
23634×
            None,
23644×
            vec![],
23650×
        )?;
23664×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
23672×
            let (op_ref, op) = self.head_op()?;
23682×
            let mut view = op.view.clone();
23692×
            if let Some(m) = view.remotes.get_mut(remote_name) {
23702×
                m.remove(bookmark);
23712×
            }
23722×
            self.record_op(
23732×
                &[op_ref],
23742×
                &format!("oxy push {remote_name} --delete {bookmark}"),
23752×
                view,
23760×
            )?;
23772×
        }
23784×
        Ok(results)
23798×
    }
2380
2381
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2382
    /// repository's config (its URL, token, CA and store settings), its
2383
    /// tracking bookmarks in the view, and a store remote's mirror under
2384
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
23853×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
23863×
        if !self.config.remotes.contains_key(name) {
23871×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
23882×
        }
23892×
        let prefix = format!("remote.{name}.");
23902×
        let keys: Vec<String> = self
23912×
            .config
23922×
            .repo_layer()
23932×
            .keys()
23944×
            .filter(|k| k.starts_with(&prefix))
23952×
            .cloned()
23962×
            .collect();
23973×
        for k in keys {
23983×
            self.config.set(&k, "")?;
2399
        }
24002×
        self.config.remotes.remove(name);
24012×
        self.save_config()?;
24022×
        let (op_ref, op) = self.head_op()?;
24032×
        if op.view.remotes.contains_key(name) {
24041×
            let mut view = op.view.clone();
24051×
            view.remotes.remove(name);
24061×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
24071×
        }
24082×
        let mirror = self.oxy.join("remotes").join(name);
24092×
        if mirror.is_dir() {
24100×
            fs::remove_dir_all(&mirror)?;
24112×
        }
24122×
        Ok(())
24133×
    }
2414
2415
    /// Send `bundle`'s blobs and chunks ahead of it, in parts of about
2416
    /// `push.batch-bytes` of objects alone, when the whole would be larger
2417
    /// (oxygen#133): one change can bring more blobs than one request may
2418
    /// carry, and a proxy in front of a hub refuses a request past its limit
2419
    /// (Cloudflare's is 100 MB). What is left, the changes with their
2420
    /// identities and states, is returned to send as before. A receiver
2421
    /// stores objects as they come, and checks a change's blobs are stored.
2422331×
    fn send_objects_ahead(
2423331×
        &self,
2424331×
        remote: &dyn crate::protocol::Remote,
2425331×
        remote_name: &str,
2426331×
        mut bundle: Bundle,
2427331×
        progress: crate::store::Progress,
2428331×
    ) -> Result<Bundle> {
2429331×
        let limit = self.config.push_batch_bytes;
2430331×
        let changes: u64 = bundle
2431331×
            .changes
2432331×
            .iter()
2433406×
            .map(|(c, _)| c.encode().len() as u64)
2434331×
            .sum();
2435331×
        let objects: u64 = bundle.objects.iter().map(|(_, b)| b.len() as u64).sum();
2436331×
        if changes + objects <= limit {
2437324×
            return Ok(bundle);
24387×
        }
24397×
        let (mut kept, mut parts, mut part, mut bytes) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
24409×
        for (ty, body) in std::mem::take(&mut bundle.objects) {
24419×
            if !matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
24420×
                kept.push((ty, body));
24430×
                continue;
24449×
            }
24459×
            if !part.is_empty() && bytes + body.len() as u64 > limit {
24463×
                parts.push(std::mem::take(&mut part));
24473×
                bytes = 0;
24486×
            }
24499×
            bytes += body.len() as u64;
24509×
            part.push((ty, body));
2451
        }
24527×
        if !part.is_empty() {
24531×
            parts.push(part);
24546×
        }
24557×
        let n = parts.len();
24567×
        for (i, objects) in parts.into_iter().enumerate() {
24574×
            progress(&format!(
24584×
                "objects {} of {n}: {} blobs and chunks",
24594×
                i + 1,
24604×
                objects.len()
24614×
            ));
24624×
            let results = remote.push(
24634×
                Bundle {
24644×
                    objects,
24654×
                    ..Default::default()
24664×
                },
24674×
                vec![],
24684×
                None,
24694×
                vec![],
24700×
            )?;
24714×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
24724×
                Some(r) if r.ok => {}
24730×
                Some(r) => {
24740×
                    return fail(format!(
2475
                        "{remote_name} refused objects part {} of {n}: {}",
24760×
                        i + 1,
2477
                        r.reason
2478
                    ))
2479
                }
2480
                None => {
24810×
                    return fail(format!(
2482
                        "{remote_name} does not take a push in parts, and this one is too large for one: update the server's oxy"
2483
                    ))
2484
                }
2485
            }
2486
        }
24877×
        bundle.objects = kept;
24887×
        Ok(bundle)
2489331×
    }
2490
2491
    /// `changes`, in dependency order, cut into batches of about
2492
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2493
    /// There is always one, perhaps empty.
2494326×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2495326×
        let blob_len = |r: &ObjectRef| -> u64 {
249637×
            self.store
249737×
                .get_typed(r, ObjectType::Blob)
249837×
                .ok()
249937×
                .and_then(|b| Blob::decode(&b).ok())
250037×
                .map_or(0, |b| b.length)
250137×
        };
2502326×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2503406×
        for h in changes {
2504406×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2505406×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2506406×
            let mut weight = raw.len() as u64;
2507501×
            for t in &texts {
2508501×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
250926×
                    weight += blob_len(r);
2510475×
                }
2511
            }
2512650×
            for e in &c.edits {
251311×
                if let Edit::Replace { new: Some(b), .. } = e {
251411×
                    weight += blob_len(b);
2515639×
                }
2516
            }
2517406×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
25185×
                out.push(std::mem::take(&mut batch));
25195×
                bytes = 0;
2520401×
            }
2521406×
            batch.push(*h);
2522406×
            bytes += weight;
2523
        }
2524326×
        out.push(batch);
2525326×
        Ok(out)
2526326×
    }
2527
2528381×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2529381×
        let bookmark = self.config.bookmark.clone();
2530381×
        self.push_bookmark(remote_name, &bookmark, force)
2531381×
    }
2532
2533
    /// `push` for a named bookmark (`oxy push -b NAME`).
2534396×
    pub fn push_bookmark(
2535396×
        &self,
2536396×
        remote_name: &str,
2537396×
        bookmark: &str,
2538396×
        force: bool,
2539396×
    ) -> Result<Vec<RefResult>> {
2540396×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2541396×
    }
2542
2543
    /// `push_bookmark`, saying how a long push is going: one line per
2544
    /// batch sent (oxygen#95).
2545
    /// What a push may take the remote to hold already: the heads of the
2546
    /// bookmark pushed, and of every other bookmark it lists that are held
2547
    /// here, so a new bookmark made from main sends only what main lacks
2548
    /// (oxygen#142), not its whole history again.
2549328×
    pub(crate) fn remote_holds(
2550328×
        &self,
2551328×
        refs: &[crate::protocol::RemoteRef],
2552328×
        bookmark_heads: &[ChangeHash],
2553328×
    ) -> Vec<ChangeHash> {
2554328×
        let mut have: Vec<ChangeHash> = bookmark_heads.to_vec();
2555356×
        for h in refs.iter().flat_map(|r| &r.heads) {
2556356×
            if !have.contains(h) && self.store.has(h) {
255721×
                have.push(*h);
2558335×
            }
2559
        }
2560328×
        have
2561328×
    }
2562
2563405×
    pub fn push_bookmark_with(
2564405×
        &self,
2565405×
        remote_name: &str,
2566405×
        bookmark: &str,
2567405×
        force: bool,
2568405×
        progress: crate::store::Progress,
2569405×
    ) -> Result<Vec<RefResult>> {
2570405×
        let (op_ref, op) = self.head_op()?;
2571405×
        if !op.view.bookmarks.contains_key(bookmark) {
25720×
            return fail(format!("no bookmark {bookmark}"));
2573405×
        }
2574405×
        let bookmark = bookmark.to_string();
2575405×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2576
        // pre-push hook: may veto before the remote is contacted.
2577405×
        self.run_hook(
2578405×
            "pre-push",
2579405×
            &format!(
2580
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2581405×
                json_str(remote_name),
2582405×
                json_str(&bookmark),
2583784×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2584
            ),
25851×
        )?;
2586404×
        let remote = self.open_named_remote(remote_name)?;
2587404×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2588401×
        let resp = remote.refs()?;
2589401×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2590401×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2591401×
        let policy_to_send = match (&local_policy, &resp.policy) {
259244×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
259316×
            (Some(l), None) => Some(l.clone()),
259426×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
25951×
                return fail(format!(
2596
                    "{remote_name} has a newer policy (serial {}); fetch first",
2597
                    r.policy.serial
2598
                ));
2599
            }
2600366×
            _ => None,
2601
        };
2602400×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2603400×
        if remote_has_policy && self.secret_key()?.is_none() {
26041×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2605399×
        }
2606399×
        let remote_tags: BTreeSet<String> = resp
2607399×
            .tags
2608399×
            .iter()
2609399×
            .chain(&resp.withdrawn)
2610399×
            .map(|t| t.name.clone())
2611399×
            .collect();
2612399×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2613399×
            .tag_refs()?
2614399×
            .into_iter()
2615399×
            .filter(|t| !remote_tags.contains(&t.name))
2616399×
            .collect();
2617
        // Tags withdrawn here that the remote still has, at the same state
2618
        // (oxygenhub#301).
2619399×
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2620399×
            .withdrawn_refs()?
2621399×
            .into_iter()
2622399×
            .filter(|w| {
26232×
                resp.tags
26242×
                    .iter()
26252×
                    .any(|t| t.name == w.name && t.state == w.state)
26262×
            })
2627399×
            .collect();
2628399×
        let refs = resp.refs;
2629399×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2630399×
        let (remote_state, remote_heads, last_serial) =
2631400×
            match refs.iter().find(|r| r.name == bookmark) {
2632375×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
263324×
                None => (empty, vec![], None),
2634
            };
2635399×
        let new_state = self
2636399×
            .store
2637399×
            .put_state(&StateObject::new(local_heads.clone()))?;
2638
        // A push that carries a policy re-attests the bookmark even when its
2639
        // state is unchanged, so the current attestation is always by a key
2640
        // the current policy authorizes (a revoked key's attestation would
2641
        // otherwise be refused by every later fetch).
2642399×
        if new_state == remote_state
264334×
            && policy_to_send.is_none()
264417×
            && tags_to_send.is_empty()
26458×
            && withdrawals_to_send.is_empty()
2646
        {
26477×
            return Ok(vec![RefResult {
26487×
                name: bookmark,
26497×
                ok: true,
26507×
                reason: "already up to date".into(),
26517×
            }]);
2652392×
        }
2653
        // A shallow repository knows the changes on its boundary without
2654
        // holding them: a depth-0 clone's are the heads it cloned (#137).
2655392×
        let boundary = self.boundary();
2656414×
        for h in &remote_heads {
2657414×
            if !self.store.has(h) && !boundary.contains(h) {
265865×
                return fail(format!(
2659
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
266065×
                    h.short(12)
2661
                ));
2662349×
            }
2663
        }
2664327×
        if !force {
2665327×
            let closure = self.closure_in_store(&local_heads)?;
2666327×
            if let Some(h) = remote_heads
2667327×
                .iter()
2668330×
                .find(|h| !closure.contains(h) && !boundary.contains(h))
2669
            {
26700×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2671327×
            }
26720×
        }
2673327×
        let to_send = self.negotiate(&self.remote_holds(&refs, &remote_heads), &local_heads)?;
2674327×
        let key = self.secret_key()?.map(|(k, _)| k);
2675327×
        if let Some(key) = key {
2676
            // Seal this author's changes that carry no valid authenticator,
2677
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2678
            // are stored, so each batch's bundle carries those it needs.
2679112×
            let mut unsigned = Vec::new();
2680112×
            for h in &to_send {
268182×
                let c = self.store.get_change_meta(h)?;
268282×
                if self.seals_for_author(&c.author, &key)
268380×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
268453×
                {
268553×
                    unsigned.push(*h);
268653×
                }
2687
            }
2688112×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
268950×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2690
            }
2691215×
        }
2692
        // A long history goes in batches, in dependency order, so neither
2693
        // side holds it whole and no request passes the remote's limit:
2694
        // all but the last carry objects alone; the last moves the bookmark
2695
        // (oxygen#95).
2696326×
        let batches = self.push_batches(&to_send)?;
2697326×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2698326×
        for (i, batch) in earlier.iter().enumerate() {
26995×
            progress(&format!(
27005×
                "part {} of {}: {} changes",
27015×
                i + 1,
27025×
                batches.len(),
27035×
                batch.len()
27045×
            ));
27055×
            let bundle = self.send_objects_ahead(
27065×
                remote.as_ref(),
27075×
                remote_name,
27085×
                self.bundle_for(batch)?,
27095×
                &mut *progress,
27100×
            )?;
27115×
            let results = remote.push(bundle, vec![], None, vec![])?;
27125×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
27135×
                Some(r) if r.ok => {}
27140×
                Some(r) => {
27150×
                    return fail(format!(
2716
                        "{remote_name} refused part {} of the push: {}",
27170×
                        i + 1,
2718
                        r.reason
2719
                    ))
2720
                }
2721
                None => {
27220×
                    return fail(format!(
2723
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2724
                    ))
2725
                }
2726
            }
2727
        }
2728326×
        if batches.len() > 1 {
27291×
            progress(&format!(
27301×
                "part {} of {}: {} changes",
27311×
                batches.len(),
27321×
                batches.len(),
27331×
                last.len()
27341×
            ));
2735325×
        }
2736326×
        let mut bundle = self.send_objects_ahead(
2737326×
            remote.as_ref(),
2738326×
            remote_name,
2739326×
            self.bundle_for(last)?,
2740326×
            &mut *progress,
27410×
        )?;
2742326×
        bundle.objects.push((
2743326×
            ObjectType::State,
2744326×
            StateObject::new(local_heads.clone()).encode(),
2745326×
        ));
2746326×
        let attestation = match key {
2747111×
            Some(_) => Some(self.sign_attest(&Attest {
2748111×
                repo: self.id()?,
2749111×
                hlc: Hlc::now(),
2750111×
                body: AttestBody::Ref {
2751111×
                    name: bookmark.clone(),
2752111×
                    old_state: remote_state,
2753111×
                    new_state,
2754111×
                    serial: next_serial(last_serial),
2755111×
                },
27561×
            })?),
2757215×
            None => None,
2758
        };
2759
        // Whoever signed the move, and whom a delegate acts for, travel with
2760
        // it: a receiver that has never seen a change by this delegate could
2761
        // not otherwise check its signature (oxygenhub#129).
2762325×
        if attestation.is_some() {
2763220×
            for k in [self.signing_key(), self.config.author_key]
2764110×
                .into_iter()
2765110×
                .flatten()
2766
            {
2767220×
                if let Ok(id) = self.identity(&k) {
2768220×
                    let body = id.encode();
2769220×
                    if !bundle
2770220×
                        .objects
2771220×
                        .iter()
2772267×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
277338×
                    {
277438×
                        bundle.objects.push((ObjectType::Identity, body));
2775182×
                    }
27760×
                }
2777
            }
2778
            // A short-lived signing key's certificate goes with it (§14.7).
2779110×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2780110×
            self.attach_certificates_for(&mut bundle, &signers)?;
2781215×
        }
2782325×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2783110×
            AttestBody::Ref { serial, .. } => Some(serial),
27840×
            _ => None,
2785110×
        });
2786325×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2787
        // Tag states must be present on the remote: bundle their changes too.
2788325×
        for t in &tags_to_send {
278916×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
279016×
            let extra: Vec<ChangeHash> =
279116×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
279216×
            if !extra.is_empty() {
27930×
                let more = self.bundle_for(&extra)?;
27940×
                bundle.changes.extend(more.changes);
27950×
                bundle.hashes.extend(more.hashes);
27960×
                bundle.attests.extend(more.attests);
27970×
                bundle.objects.extend(more.objects);
279816×
            }
279916×
            bundle.objects.push((
280016×
                ObjectType::State,
280116×
                StateObject::new(t.heads.clone()).encode(),
280216×
            ));
2803
        }
2804
        // A tag's signer travels with it, as the bookmark's does: a tag made
2805
        // by `oxy tag create` under a short-lived key was signed by a key the
2806
        // receiver has never seen, so its identity and certificate go too.
2807325×
        let tag_signers: Vec<KeyId> = tags_to_send
2808325×
            .iter()
2809325×
            .chain(&withdrawals_to_send)
2810325×
            .filter_map(|t| t.attestation.as_ref())
2811325×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2812325×
            .collect();
2813325×
        for k in &tag_signers {
281416×
            if let Ok(id) = self.identity(k) {
281516×
                let body = id.encode();
281616×
                if !bundle
281716×
                    .objects
281816×
                    .iter()
281930×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
28202×
                {
28212×
                    bundle.objects.push((ObjectType::Identity, body));
282214×
                }
28230×
            }
2824
        }
2825325×
        if !tag_signers.is_empty() {
282615×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2827310×
        }
2828325×
        if let Some(l) = &policy_to_send {
282934×
            let remote_serial = resp_policy_serial;
283034×
            bundle.policies = self
283134×
                .policy_history()?
283234×
                .into_iter()
283366×
                .filter(|sp| {
283466×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
283536×
                        && sp.policy.serial < l.policy.serial
283666×
                })
283734×
                .collect();
2838291×
        }
2839325×
        let results = remote.push(
2840325×
            bundle,
2841325×
            vec![RefUpdate {
2842325×
                name: bookmark.clone(),
2843325×
                old_state: remote_state,
2844325×
                new_state,
2845325×
                force,
2846325×
                attestation,
2847325×
            }],
2848325×
            policy_to_send,
2849325×
            tags_to_send
2850325×
                .into_iter()
2851325×
                .chain(withdrawals_to_send)
2852325×
                .collect(),
28538×
        )?;
285434×
        if let (Some(serial), true) = (
2855317×
            sent_serial,
2856331×
            results.iter().any(|r| r.ok && r.name == "policy"),
2857
        ) {
285834×
            self.record_policy_serial(remote_name, serial)?;
2859283×
        }
2860354×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2861290×
            let mut view = op.view.clone();
2862290×
            view.remotes
2863290×
                .entry(remote_name.to_string())
2864290×
                .or_default()
2865290×
                .insert(bookmark.clone(), new_state);
2866290×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2867287×
            if let Some(s) = serial {
286886×
                self.record_serial(remote_name, &bookmark, s)?;
2869201×
            }
287027×
        }
2871312×
        Ok(results)
2872405×
    }
2873
2874
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2875
    /// bookmark set to the remote's, working copy checked out.
2876264×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2877264×
        Self::clone_with(url, dest, None, &[])
2878264×
    }
2879
2880
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2881
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2882
    /// unless a size is given, so out-of-scope binaries are never fetched).
2883267×
    pub fn clone_with(
2884267×
        url: &str,
2885267×
        dest: &Path,
2886267×
        max_blob: Option<u64>,
2887267×
        sparse: &[String],
2888267×
    ) -> Result<Repo> {
2889267×
        Self::clone_full(url, dest, max_blob, sparse, None)
2890267×
    }
2891
2892
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2893
    /// changes within `depth` steps of them; the rest is the boundary.
28943×
    pub fn clone_shallow(
28953×
        url: &str,
28963×
        dest: &Path,
28973×
        depth: u32,
28983×
        max_blob: Option<u64>,
28993×
        sparse: &[String],
29003×
    ) -> Result<Repo> {
29013×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
29023×
    }
2903
2904270×
    fn clone_full(
2905270×
        url: &str,
2906270×
        dest: &Path,
2907270×
        max_blob: Option<u64>,
2908270×
        sparse: &[String],
2909270×
        depth: Option<u32>,
2910270×
    ) -> Result<Repo> {
2911270×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2912270×
    }
2913
2914
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2915
    /// `depth`), also returning the bookmarks the fetch left out because
2916
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2917
    /// for the caller to warn about. The bookmark checked out is never one
2918
    /// of them: that fails the clone.
2919276×
    pub fn clone_reporting(
2920276×
        url: &str,
2921276×
        dest: &Path,
2922276×
        max_blob: Option<u64>,
2923276×
        sparse: &[String],
2924276×
        depth: Option<u32>,
2925276×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2926276×
        let options = crate::credentials::Credentials::user().options_for(url);
2927276×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2928276×
    }
2929
2930
    /// Clone a subrepo with the credentials the parent would use for its
2931
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2932
    /// subrepo: it finds the same ones again through its parent.
293312×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
293412×
        let options = self.credentials_for(url);
293512×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
293612×
    }
2937
2938
    /// The name of a remote of this repository on the same hub (scheme,
2939
    /// host and port) as `url`.
294027×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
294131×
        let origin = |u: &str| -> Option<String> {
294231×
            let (scheme, rest) = u.split_once("://")?;
29438×
            if !matches!(scheme, "http" | "https") {
29440×
                return None;
29458×
            }
29468×
            let host = rest.split('/').next()?;
29478×
            Some(format!(
29488×
                "{}://{}",
29498×
                scheme.to_ascii_lowercase(),
29508×
                host.to_ascii_lowercase()
29518×
            ))
295231×
        };
295327×
        let want = origin(url)?;
29544×
        self.config
29554×
            .remotes
29564×
            .iter()
29574×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
29584×
            .map(|(name, _)| name.clone())
295927×
    }
2960
2961
    /// The token and CA to reach `url` with: those of a remote of this
2962
    /// repository on the same hub (scheme, host and port), else the
2963
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2964
    /// and enclosing checkouts', as a clone would use them.
296527×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
296627×
        match self.remote_on_same_hub(url) {
29671×
            Some(name) => RemoteOptions {
29681×
                repo_id: None,
29691×
                cache_dir: None,
29701×
                ..self.remote_options(&name)
29711×
            },
2972
            None => {
297326×
                let mut options = RemoteOptions::default();
297426×
                self.fill_credentials(url, &mut options);
297526×
                options
2976
            }
2977
        }
297827×
    }
2979
2980288×
    fn clone_using(
2981288×
        url: &str,
2982288×
        dest: &Path,
2983288×
        max_blob: Option<u64>,
2984288×
        sparse: &[String],
2985288×
        depth: Option<u32>,
2986288×
        options: &RemoteOptions,
2987288×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2988288×
        let remote = open_remote(url, options)?;
2989288×
        let id = remote.repo_id()?;
2990284×
        if id == crate::protocol::UNBOUND_ID {
29912×
            return fail(format!(
2992
                "{url} is empty and unbound: push a repository to it first"
2993
            ));
2994282×
        }
2995282×
        let mut repo = Repo::init_with_id(dest, id)?;
2996282×
        repo.config
2997282×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2998282×
        if let Some(m) = max_blob {
29993×
            repo.config.set("filter.max-blob", &m.to_string())?;
3000279×
        } else if !sparse.is_empty() {
30011×
            repo.config.set("filter.max-blob", "0")?;
3002278×
        }
3003282×
        if !sparse.is_empty() {
30041×
            repo.config.set("filter.paths", &sparse.join(","))?;
3005281×
        }
3006282×
        repo.save_config()?;
3007282×
        let skipped = if let Some(depth) = depth {
30083×
            repo.fetch_shallow("origin", depth)?;
30093×
            Vec::new()
3010
        } else {
3011279×
            repo.fetch("origin")?.skipped
3012
        };
3013280×
        let (op_ref, op) = repo.head_op()?;
3014
        // The remote's default bookmark, else ours (main), else its only
3015
        // one; a bookmark the fetch skipped counts, so the clone fails
3016
        // rather than check out another (oxygenhub#266).
3017280×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
3018280×
        for (name, _) in &skipped {
30193×
            theirs.insert(name.clone(), ObjectRef::ZERO);
30203×
        }
3021
        // Asked of the remote as now configured, so a store-backed one
3022
        // answers from the mirror the fetch just filled.
3023280×
        let advertised = repo
3024280×
            .open_named_remote("origin")
3025280×
            .ok()
3026280×
            .and_then(|r| r.refs().ok())
3027280×
            .and_then(|r| r.default_bookmark);
3028280×
        let bookmark = advertised
3029280×
            .filter(|b| theirs.contains_key(b))
3030280×
            .or_else(|| {
30317×
                theirs
30327×
                    .contains_key(&repo.config.bookmark)
30337×
                    .then(|| repo.config.bookmark.clone())
30347×
            })
3035280×
            .or_else(|| {
30360×
                (theirs.len() == 1)
30370×
                    .then(|| theirs.keys().next().cloned())
30380×
                    .flatten()
30390×
            })
3040280×
            .unwrap_or_else(|| repo.config.bookmark.clone());
3041280×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
30420×
            return fail(format!("cannot check out {bookmark}: {why}"));
3043280×
        }
3044280×
        let initial = repo.config.bookmark.clone();
3045280×
        if bookmark != repo.config.bookmark {
30461×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
30471×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
30481×
            repo.config.bookmark = bookmark.clone();
3049279×
        }
3050280×
        if let Some(state) = theirs.get(&bookmark).copied() {
3051280×
            let heads = repo.store.get_state(&state)?.heads;
3052280×
            let mut view = op.view.clone();
3053
            // The empty bookmark `init` made goes when another is checked out.
3054280×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
30551×
                view.bookmarks.remove(&initial);
3056279×
            }
3057280×
            view.bookmarks.insert(bookmark, state);
3058280×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
3059280×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
30600×
        }
3061280×
        Ok((repo, skipped))
3062288×
    }
3063
}
3064
3065
/// The serial of a reference's next attestation: one more than the last the
3066
/// remote reports, or, for a bookmark the remote does not have, the clock in
3067
/// milliseconds, so a bookmark created again after a deletion goes past the
3068
/// deletion's serial the remote keeps.
3069111×
fn next_serial(last: Option<u64>) -> u64 {
3070111×
    match last {
307169×
        Some(l) => l + 1,
307242×
        None => Hlc::now().wall_ms.max(1),
3073
    }
3074111×
}