OXYGENHUB

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

2239 of 2491 lines run, 362 of 478 functions · run #426 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::tags::TagCheck;
4
use super::*;
5
6
/// What a push did, for hosts (hub spec §6.12).
7
#[derive(Clone, Debug, Default)]
8
pub struct PushReport {
9
    pub results: Vec<RefResult>,
10
    /// Accepted reference updates, in request order.
11
    pub updated: Vec<RefUpdated>,
12
    /// Changes this push stored that were not already present.
13
    pub imported: Vec<ChangeHash>,
14
}
15
16
#[derive(Clone, Debug)]
17
pub struct RefUpdated {
18
    pub name: String,
19
    pub old_state: ObjectRef,
20
    pub new_state: ObjectRef,
21
    pub heads: Vec<ChangeHash>,
22
}
23
24
/// What a fetch brought in.
25
#[derive(Debug, Clone, PartialEq, Eq, Default)]
26
pub struct FetchReport {
27
    /// Bookmark name, its heads, and how many changes were new.
28
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
29
    /// Tags adopted from the remote.
30
    pub new_tags: usize,
31
    /// Tags the remote withdrew, and so withdrawn here (oxygenhub#301).
32
    pub withdrawn_tags: Vec<String>,
33
    /// The remote has never presented a policy, so nothing was verified
34
    /// against one (spec §14.5: warn loudly).
35
    pub unverified: bool,
36
    /// What checking the host's transparency log found short of a fork
37
    /// (spec §14.8): attestations not logged yet, a log that could not be
38
    /// read. A fork fails the fetch instead.
39
    pub log_notes: Vec<String>,
40
    /// Bookmarks left as they were because their attestation could not be
41
    /// verified (its signer unknown here, or its signature bad), each with
42
    /// why (oxygenhub#266). The current bookmark is never skipped: its
43
    /// fetch fails instead.
44
    pub skipped: Vec<(String, String)>,
45
}
46
47
#[derive(Debug, Clone, PartialEq, Eq)]
48
pub struct PullReport {
49
    /// The current bookmark's heads after the pull.
50
    pub heads: Vec<ChangeHash>,
51
    /// Whether the current bookmark changed.
52
    pub changed: bool,
53
    pub checked_out: bool,
54
    /// Other bookmarks the pull moved: each local bookmark tracks the
55
    /// remote's of the same name.
56
    pub others: Vec<String>,
57
    /// What the fetch left as it was ([`FetchReport::skipped`]).
58
    pub skipped: Vec<(String, String)>,
59
}
60
61
/// The result a push of objects alone reports (a batch of a long history):
62
/// not a reference.
63
pub const OBJECTS_RESULT: &str = "objects";
64
65
/// Graph blobs asked for in one `objects` request when a shallow clone
66
/// fetches its checkpoint in parts (#137): their chunk lists and chunks,
67
/// a few MiB a request rather than one answer of gigabytes.
68
const CHECKPOINT_PART: usize = 2048;
69
70
impl Repo {
71
    // ------------------------------------------------------------ serving (spec §16)
72
731835×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
741835×
        self.oxy.join("attest").join(name_file(bookmark))
751835×
    }
76
77
    /// The latest reference attestation stored for a bookmark.
781496×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
791496×
        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
            }
911151×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
920×
            Err(e) => Err(e.into()),
93
        }
941496×
    }
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
1011160×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
1021160×
        let view = self.view()?;
1031160×
        let mut out = Vec::new();
1041255×
        for (name, state) in &view.bookmarks {
1051255×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
1061255×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
107230×
                AttestBody::Ref { serial, .. } => Some(serial),
1080×
                _ => None,
109230×
            });
1101255×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1111255×
            let accepted = match &attestation {
112219×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
1131036×
                None => None,
114
            };
1151255×
            out.push(RemoteRef {
1161255×
                name: name.clone(),
1171255×
                state: *state,
1181255×
                heads: self.store.get_state(state)?.heads,
1191255×
                attestation,
1201255×
                last_serial,
1211255×
                accepted,
1221255×
                logged: None,
1231255×
                integration: vec![],
124
            });
125
        }
1261160×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1271160×
        let history = self
1281160×
            .policy_history()?
1291160×
            .into_iter()
1301160×
            .filter(|sp| {
131221×
                policy
132221×
                    .as_ref()
133221×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
134221×
            })
1351160×
            .collect();
136
        Ok(RefsResponse {
1371160×
            refs: out,
1381160×
            policy,
1391160×
            tags: self.tag_refs()?,
1401160×
            history,
1411160×
            default_bookmark: Some(self.config.bookmark.clone()),
1421160×
            log: None,
1431160×
            witnesses: vec![],
1441160×
            withdrawn: self.withdrawn_refs()?,
145
        })
1461160×
    }
147
148
    /// Every change reachable from `heads` that is in the store.
1491440×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1501440×
        let mut seen = BTreeSet::new();
1511440×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1524799×
        while let Some(h) = stack.pop() {
1533359×
            if seen.contains(&h) || !self.store.has(&h) {
154858×
                continue;
1552501×
            }
1562501×
            seen.insert(h);
1572501×
            stack.extend(self.store.get_change_meta(&h)?.deps);
158
        }
1591440×
        Ok(seen)
1601440×
    }
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
1873536×
    fn shallow_path(&self) -> PathBuf {
1883536×
        self.oxy.join("shallow")
1893536×
    }
190
191
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1923527×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1933527×
        fs::read_to_string(self.shallow_path())
1943527×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1953527×
            .unwrap_or_default()
1963527×
    }
197
1981379×
    pub fn is_shallow(&self) -> bool {
1991379×
        !self.boundary().is_empty()
2001379×
    }
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).
247773×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
248773×
        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.
251773×
        let boundary = self.boundary();
252773×
        let mut out = Vec::new();
253773×
        let mut done: BTreeSet<ChangeHash> = have.clone();
254773×
        done.extend(boundary.iter().copied());
255
        // Iterative post-order DFS.
256773×
        let shallow = self.is_shallow();
2571256×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2583295×
        while let Some((h, expanded)) = stack.pop() {
2592522×
            if done.contains(&h) {
260361×
                continue;
2612161×
            }
2622161×
            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)));
2722160×
            }
2732160×
            if expanded {
2741080×
                done.insert(h);
2751080×
                out.push(h);
2761080×
                continue;
2771080×
            }
2781080×
            stack.push((h, true));
2791080×
            for d in self.store.get_change_meta(&h)?.deps {
280678×
                if !done.contains(&d) {
281186×
                    stack.push((d, false));
282492×
                }
283
            }
284
        }
285773×
        Ok(out)
286773×
    }
287
288
    /// Bundle changes (in the given dependency order) with their signatures,
289
    /// seals, identities, blobs, chunks.
290351×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
291351×
        self.bundle_of(changes, None, false, false)
292351×
    }
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.
33037×
    pub fn bundle_for_filtered(
33137×
        &self,
33237×
        changes: &[ChangeHash],
33337×
        max_blob: Option<u64>,
33437×
    ) -> Result<Bundle> {
33537×
        self.bundle_of(changes, max_blob, false, true)
33637×
    }
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.
342262×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
343262×
        self.bundle_of(changes, max_blob, true, true)
344262×
    }
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.
357299×
    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);
360299×
        let key = (self.oxy.clone(), self.head_op()?.0);
361299×
        if let Some(keys) = SERVED
362299×
            .lock()
363299×
            .unwrap_or_else(|p| p.into_inner())
364299×
            .as_ref()
365299×
            .and_then(|m| m.get(&key))
366
        {
36789×
            return Ok(keys.clone());
368210×
        }
369210×
        let keys = self.attest_signers_now()?;
370210×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
371210×
        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.
3741897×
        map.retain(|(oxy, _), _| *oxy != key.0);
375210×
        if map.len() >= 1024 {
3760×
            map.clear();
377210×
        }
378210×
        map.insert(key, keys.clone());
379210×
        Ok(keys)
380299×
    }
381
382210×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
383210×
        let view = self.view()?;
384210×
        let pointers = view
385210×
            .bookmarks
386210×
            .keys()
387230×
            .map(|b| self.ref_attest_path(b))
388210×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
389210×
        let mut keys = BTreeSet::new();
390250×
        for p in pointers {
391250×
            let Ok(text) = fs::read_to_string(&p) else {
392195×
                continue;
393
            };
39455×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3950×
                continue;
396
            };
39755×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
398
        }
399210×
        Ok(keys)
400210×
    }
401
402
    /// `serving`: a fetch's answer, which carries the identities and
403
    /// certificates of [`Repo::served_attest_signers`] too.
404650×
    fn bundle_of(
405650×
        &self,
406650×
        changes: &[ChangeHash],
407650×
        max_blob: Option<u64>,
408650×
        raw: bool,
409650×
        serving: bool,
410650×
    ) -> Result<Bundle> {
411650×
        let mut bundle = Bundle::default();
412650×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
413650×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
4141186×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
4151186×
            if !r.is_zero() && self.store.has(r) {
416319×
                objects.insert(*r);
417867×
            }
4181186×
        };
419994×
        for h in changes {
420
            // Raw: the stored bytes, and a skeleton for the rest.
421994×
            let (c, encoded) = if raw {
422526×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
423526×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
4242850×
                for t in texts {
4252850×
                    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);
4292847×
                    }
430
                }
431526×
                (skel, Some(bytes))
432
            } else {
433468×
                (self.store.get_change(h)?, None)
434
            };
435994×
            let sigs = self.store.signatures(h)?;
436994×
            add_object(&c.author, &mut objects);
437994×
            for s in &sigs {
43826×
                add_object(&s.key, &mut objects);
43926×
            }
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).
4443814×
            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×
                    }
4563782×
                }
457
            }
458994×
            for s in self.store.seals_for(h)? {
459104×
                seals.insert(s);
460104×
            }
461994×
            match encoded {
462526×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
463468×
                None => {
464468×
                    bundle.changes.push((c, sigs));
465468×
                    bundle.hashes.push(*h);
466468×
                }
467
            }
468
        }
469650×
        for r in seals {
47099×
            let attest = self.store.get_attest(&r)?;
47199×
            let sigs = self.store.signatures(&r)?;
47299×
            for s in &sigs {
47399×
                add_object(&s.key, &mut objects);
47499×
            }
47599×
            bundle.attests.push(SignedAttest { attest, sigs });
476
        }
477650×
        let signers: Vec<KeyId> = if serving {
478299×
            let signers = self.served_attest_signers()?;
479299×
            for k in &signers {
48067×
                add_object(k, &mut objects);
48167×
            }
482299×
            signers.into_iter().collect()
483
        } else {
484351×
            Vec::new()
485
        };
486650×
        for r in objects {
487299×
            let (ty, body) = self.store.get(&r)?;
488299×
            bundle.objects.push((ty, body));
489
        }
490650×
        self.attach_certificates_for(&mut bundle, &signers)?;
491650×
        Ok(bundle)
492650×
    }
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).
498777×
    pub(crate) fn attach_certificates_for(
499777×
        &self,
500777×
        bundle: &mut Bundle,
501777×
        also: &[KeyId],
502777×
    ) -> Result<()> {
503777×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
504777×
        keys.extend(
505777×
            bundle
506777×
                .changes
507777×
                .iter()
508777×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
509
        );
510777×
        keys.extend(
511777×
            bundle
512777×
                .raw_changes
513777×
                .iter()
514777×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
515
        );
516777×
        keys.extend(
517777×
            bundle
518777×
                .attests
519777×
                .iter()
520777×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
521
        );
522777×
        for k in keys {
523288×
            let Some(r) = self.store.certificate_of(&k)? else {
524244×
                continue;
525
            };
52644×
            let cert = self.store.get_certificate(&r)?;
52744×
            if bundle
52844×
                .certificates
52944×
                .iter()
53044×
                .any(|c| c.cert.hash() == cert.cert.hash())
531
            {
53212×
                continue;
53332×
            }
534
            // An agent's certificate brings its grant's signer too, so the
535
            // receiver can check the grant (oxygen#134).
53632×
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
53771×
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
53871×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
53970×
                    if !bundle
54070×
                        .objects
54170×
                        .iter()
542130×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
54330×
                    {
54430×
                        bundle.objects.push((ObjectType::Identity, body));
54540×
                    }
5461×
                }
547
            }
54832×
            bundle.certificates.push(cert);
549
        }
550777×
        Ok(())
551777×
    }
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.
555696×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
556696×
        for c in certs {
55731×
            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×
            })?;
56331×
            c.verify(&issuer)
56431×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
56531×
            self.store.put_identity(&c.cert.key)?;
56631×
            self.store.put_certificate(c)?;
567
        }
568696×
        Ok(())
569696×
    }
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).
604691×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
605691×
        self.import_bundle_inner(bundle, strict, false)
606691×
    }
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
614696×
    fn import_bundle_inner(
615696×
        &self,
616696×
        bundle: &Bundle,
617696×
        strict: bool,
618696×
        shallow: bool,
619696×
    ) -> Result<Vec<ChangeHash>> {
620696×
        let batch = self.store.begin_batch()?;
621696×
        let result = self.import_bundle_batched(bundle, strict, shallow);
622696×
        batch.finish()?;
623694×
        result
624696×
    }
625
626696×
    fn import_bundle_batched(
627696×
        &self,
628696×
        bundle: &Bundle,
629696×
        strict: bool,
630696×
        shallow: bool,
631696×
    ) -> Result<Vec<ChangeHash>> {
632771×
        for (ty, _) in &bundle.objects {
6330×
            if !matches!(
634771×
                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()));
642771×
            }
643
        }
644
        // All at once: in a large batch they are compressed on every core.
645696×
        let objects: Vec<(ObjectType, &[u8])> = bundle
646696×
            .objects
647696×
            .iter()
648771×
            .map(|(ty, body)| (*ty, body.as_slice()))
649696×
            .collect();
650696×
        self.store.put_many(&objects)?;
651696×
        self.adopt_certificates(&bundle.certificates)?;
652696×
        for sa in &bundle.attests {
653102×
            let r = self.store.put_attest(&sa.attest)?;
654102×
            for sig in &sa.sigs {
655102×
                self.store.put_signature(&r, sig)?;
656
            }
657102×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
658107×
                for h in hashes {
659107×
                    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).
666696×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
667687×
            bundle.hashes.clone()
668
        } else {
6699×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
670
        };
671696×
        let raw_hashes: Vec<ChangeHash> = bundle
672696×
            .raw_changes
673696×
            .iter()
674696×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
675696×
            .collect();
676696×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
677696×
        let boundary = self.boundary();
678696×
        let mut imported = Vec::new();
679
        // Changes as stored: checked, then stored as they are, their text
680
        // blobs having come with the objects.
681696×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
682527×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
683527×
            for d in &skel.deps {
684353×
                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
                    ));
691353×
                }
692
            }
6932851×
            for t in texts {
6942851×
                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×
                    }
7022847×
                }
703
            }
704526×
            self.store.put(ObjectType::Change, bytes)?;
705526×
            for sig in sigs {
7067×
                self.store.put_signature(&h, sig)?;
707
            }
708526×
            imported.push(h);
709
        }
710695×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
711492×
            for d in &c.deps {
712278×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
713
                {
7143×
                    return fail(format!(
715
                        "change {} depends on {}, which is neither stored nor in the bundle",
7163×
                        h.short(12),
7173×
                        d.short(12)
718
                    ));
719275×
                }
720
            }
721489×
            let stored = self.store.put_change(c)?;
722489×
            if stored != h {
7230×
                return fail(format!(
724
                    "change {} is not the change the bundle names",
7250×
                    h.short(12)
726
                ));
727489×
            }
728489×
            for sig in sigs {
72928×
                self.store.put_signature(&h, sig)?;
730
            }
731489×
            imported.push(h);
732
        }
733692×
        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
            }
742625×
        }
743688×
        Ok(imported)
744696×
    }
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.
888325×
    pub fn receive_push(
889325×
        &self,
890325×
        bundle: Bundle,
891325×
        updates: Vec<RefUpdate>,
892325×
        policy: Option<SignedPolicy>,
893325×
        tags: Vec<crate::protocol::TagRef>,
894325×
    ) -> Result<Vec<RefResult>> {
895325×
        Ok(self
896325×
            .receive_push_report(bundle, updates, policy, tags)?
897
            .results)
898325×
    }
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).
903373×
    pub fn receive_push_report(
904373×
        &self,
905373×
        bundle: Bundle,
906373×
        updates: Vec<RefUpdate>,
907373×
        policy: Option<SignedPolicy>,
908373×
        tags: Vec<crate::protocol::TagRef>,
909373×
    ) -> 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.
913373×
        self.refresh()?;
914373×
        let mut report = PushReport::default();
915373×
        let results = &mut report.results;
916373×
        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
            }
941337×
        }
942371×
        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`.
945371×
        let objects_only = updates.is_empty() && tags.is_empty();
946371×
        match self.import_bundle(&bundle, policy.is_some()) {
947365×
            Ok(imported) => {
948365×
                if objects_only {
94911×
                    results.push(RefResult {
95011×
                        name: OBJECTS_RESULT.into(),
95111×
                        ok: true,
95211×
                        reason: format!("{} changes stored", imported.len()),
95311×
                    });
954354×
                }
955365×
                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
        }
975365×
        let (op_ref, op) = self.head_op()?;
976365×
        let mut view = op.view.clone();
977365×
        let mut names = Vec::new();
978365×
        for u in updates {
979349×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
980349×
            let (ok, reason) = match outcome {
981321×
                Ok(()) => (true, String::new()),
98228×
                Err(e) => (false, e),
983
            };
984349×
            if ok {
985321×
                names.push(u.name.clone());
986321×
                let heads = self
987321×
                    .store
988321×
                    .get_state(&u.new_state)
989321×
                    .map(|s| s.heads)
990321×
                    .unwrap_or_default();
991321×
                report.updated.push(RefUpdated {
992321×
                    name: u.name.clone(),
993321×
                    old_state: u.old_state,
994321×
                    new_state: u.new_state,
995321×
                    heads,
996321×
                });
99728×
            }
998349×
            results.push(RefResult {
999349×
                name: u.name,
1000349×
                ok,
1001349×
                reason,
1002349×
            });
1003
        }
1004365×
        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
        }
1068365×
        if !names.is_empty() {
1069323×
            self.record_op(
1070323×
                &[op_ref],
1071323×
                &format!("push received: {}", names.join(" ")),
1072323×
                view,
10733×
            )?;
107442×
        }
1075362×
        Ok(report)
1076373×
    }
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.
1160102×
    pub(crate) fn issuer_acceptance(
1161102×
        &self,
1162102×
        signer: &KeyId,
1163102×
        sa: &SignedAttest,
1164102×
        accepted: Option<&SignedAttest>,
1165102×
    ) -> Option<u64> {
1166102×
        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
        };
117251×
        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)
1177102×
    }
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
1308349×
    fn apply_update(
1309349×
        &self,
1310349×
        view: &mut View,
1311349×
        u: &RefUpdate,
1312349×
        policy: Option<&crate::policy::Policy>,
1313349×
    ) -> std::result::Result<(), String> {
1314349×
        if u.name == "policy" {
13150×
            return Err(
13160×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
13170×
            );
1318349×
        }
1319349×
        let empty = self
1320349×
            .store
1321349×
            .put_state(&StateObject::new(vec![]))
1322349×
            .map_err(|e| e.to_string())?;
1323349×
        if u.new_state.is_zero() {
13243×
            return self.apply_deletion(view, u, policy);
1325346×
        }
1326346×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1327346×
        if current != u.old_state {
13288×
            return Err("stale: the remote bookmark has moved; pull first".into());
1329338×
        }
1330338×
        let new_state = self
1331338×
            .store
1332338×
            .get_state(&u.new_state)
1333338×
            .map_err(|_| "new state object is missing".to_string())?;
1334614×
        for h in &new_state.heads {
1335614×
            if !self.store.has(h) {
13361×
                return Err(format!("head {} is missing", h.short(12)));
1337613×
            }
1338
        }
1339337×
        if !u.force {
1340336×
            let old_heads = self
1341336×
                .store
1342336×
                .get_state(&current)
1343336×
                .map_err(|e| e.to_string())?
1344
                .heads;
1345336×
            let closure = self
1346336×
                .closure_in_store(&new_state.heads)
1347336×
                .map_err(|e| e.to_string())?;
1348336×
            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×
                ));
1353335×
            }
13541×
        }
1355336×
        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)?;
1385277×
        }
1386325×
        if let Some(sa) = &u.attestation {
1387105×
            self.record_update_attest(u, sa)?;
1388220×
        }
1389319×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1390319×
        Ok(())
1391349×
    }
1392
1393
    // ------------------------------------------------------------ client side
1394
13951542×
    fn remote_url(&self, name: &str) -> Result<String> {
13961542×
        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×
        })
14121542×
    }
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).
1417837×
    fn check_remote_id(
1418837×
        &self,
1419837×
        remote: &dyn crate::protocol::Remote,
1420837×
        remote_name: &str,
1421837×
        allow_unbound: bool,
1422837×
    ) -> Result<()> {
1423837×
        let theirs = remote.repo_id()?;
1424836×
        if theirs == self.id()? {
1425806×
            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
        ))
1438837×
    }
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`]).
14431150×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
14441150×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
14451150×
        let mut options = RemoteOptions {
14461150×
            repo_id: self.id().ok(),
14471150×
            token: self.config.remote_tokens.get(name).cloned(),
14481150×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
14491150×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
14501150×
            ..RemoteOptions::default()
14511150×
        };
14521150×
        self.fill_credentials(&url, &mut options);
14531150×
        options
14541150×
    }
1455
1456
    /// The user's credential store (`credentials.toml` beside the user
1457
    /// configuration file).
14581178×
    pub fn credentials(&self) -> crate::credentials::Credentials {
14591178×
        crate::credentials::Credentials::at(
14601178×
            self.user_config
14611178×
                .parent()
14621178×
                .map(Path::to_path_buf)
14631178×
                .unwrap_or_else(default_home),
1464
        )
14651178×
    }
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).
14741178×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14751178×
        if options.token.is_some() && options.ca.is_some() {
14761×
            return;
14771177×
        }
14781177×
        let own = options.token.is_some();
14791177×
        let env = std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14801177×
        let explicit = own || env;
14811177×
        let stored = self.credentials().options_for(url);
1482
        // A checkout's own token refused as expired or unknown (401) falls
1483
        // back to this computer's sign-in for the hub, never to another
1484
        // checkout's, and never when it is refused for permission (#155).
14851177×
        if own && !env {
14869×
            if let Some(t) = stored
14879×
                .token
14889×
                .clone()
14899×
                .filter(|t| options.token.as_ref() != Some(t))
14903×
            {
14913×
                options.fallback_tokens.push(t);
14923×
                options.fallback_on_401_only = true;
14936×
            }
14941168×
        }
14951177×
        options.token = options.token.take().or(stored.token);
14961177×
        options.ca = options.ca.take().or(stored.ca);
14971177×
        let enclosing = self.enclosing_credentials(url);
14981177×
        if options.token.is_none() {
14991165×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
150012×
        }
15011177×
        if options.ca.is_none() {
15021171×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
15036×
        }
15041177×
        if !explicit {
15051168×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
15065×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
15072×
                    options.fallback_tokens.push(t);
15083×
                }
1509
            }
15109×
        }
15111178×
    }
1512
1513
    /// What to do when `remote`'s own token was refused (`message` says
1514
    /// HTTP 401) and so was this computer's sign-in for its hub, which it
1515
    /// falls back to (oxygen#155).
15163×
    pub fn stale_token_note(&self, remote: &str, message: &str) -> Option<String> {
15173×
        if !message.contains("HTTP 401") {
15182×
            return None;
15191×
        }
15201×
        let own = self.config.remote_tokens.get(remote)?;
15211×
        let url = self.config.remotes.get(remote)?;
15221×
        let stored = self.credentials().options_for(url).token?;
15231×
        (stored != *own).then(|| {
15241×
            format!(
1525
                "the hub refused both this checkout's own token for {remote} (remote.{remote}.token) and your sign-in: \
1526
                 `oxy auth login HUB`, then `oxy config --unset remote.{remote}.token` so the sign-in is used"
1527
            )
15281×
        })
15293×
    }
1530
1531
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1532
    /// checkouts, nearest first.
15331177×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
15341177×
        let mut out = Vec::new();
15351177×
        let Some(hub) = crate::credentials::hub_of(url) else {
15361014×
            return out;
1537
        };
1538163×
        let mut at = self.root.parent();
1539664×
        while let Some(dir) = at {
1540501×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
15410×
                break;
1542
            };
1543501×
            for (key, remote_url) in &cfg {
154419×
                let Some(name) = key
154519×
                    .strip_prefix("remote.")
154619×
                    .and_then(|k| k.strip_suffix(".url"))
1547
                else {
15489×
                    continue;
1549
                };
155010×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
15511×
                    continue;
15529×
                }
15539×
                out.push((
15549×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
15559×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
15569×
                ));
1557
            }
1558501×
            at = dir.parent();
1559
        }
1560163×
        out
15611177×
    }
1562
1563
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1564
    /// no changes and no reference updates, which the receiver stores.
15650×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
15660×
        let remote = self.open_named_remote(remote_name)?;
15670×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
15680×
        let mut bundle = Bundle::default();
15690×
        for r in seals {
15700×
            let attest = self.store.get_attest(r)?;
15710×
            let sigs = self.store.signatures(r)?;
15720×
            bundle
15730×
                .attests
15740×
                .push(crate::protocol::SignedAttest { attest, sigs });
1575
        }
15760×
        let results = remote.push(bundle, vec![], None, vec![])?;
15770×
        if let Some(r) = results.iter().find(|r| !r.ok) {
15780×
            return fail(format!("{}: {}", r.name, r.reason));
15790×
        }
15800×
        Ok(())
15810×
    }
1582
1583
    /// The remote whose URL starts with `base` (a hub), if configured.
15845×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
15855×
        let base = base.trim_end_matches('/');
15865×
        self.config
15875×
            .remotes
15885×
            .iter()
15895×
            .find(|(_, url)| url.trim_end_matches('/') == base)
15905×
            .map(|(name, _)| name.clone())
15915×
    }
1592
1593
    /// Open a remote by name or, failing that, by URL with the default
1594
    /// credentials (see [`Repo::credentials_for`]).
15950×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15960×
        if let Some(name) = self.remote_for_url(url) {
15970×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15980×
        }
15990×
        let options = RemoteOptions {
16000×
            repo_id: self.id().ok(),
16010×
            ..self.credentials_for(url)
16020×
        };
16030×
        Ok((url.to_string(), open_remote(url, &options)?))
16040×
    }
1605
1606
    /// Credentials for a URL: those of the configured remote with that
1607
    /// URL, else the environment's.
16085×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
16095×
        match self.remote_for_url(url) {
16105×
            Some(name) => self.remote_options(&name),
16110×
            None => RemoteOptions {
16120×
                repo_id: self.id().ok(),
16130×
                ..self.credentials_for(url)
16140×
            },
1615
        }
16165×
    }
1617
16181132×
    pub(crate) fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
16191132×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
16201132×
    }
1621
1622220×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1623220×
        self.oxy
1624220×
            .join("remotes")
1625220×
            .join(remote)
1626220×
            .join(format!("{bookmark}.serial"))
1627220×
    }
1628
162973×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
163073×
        fs::read_to_string(self.serial_path(remote, bookmark))
163173×
            .ok()
163273×
            .and_then(|s| s.trim().parse().ok())
163373×
    }
1634
1635147×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1636147×
        let p = self.serial_path(remote, bookmark);
1637147×
        fs::create_dir_all(p.parent().unwrap())?;
1638147×
        write_atomic(&p, serial.to_string().as_bytes())
1639147×
    }
1640
1641482×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1642482×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1643482×
    }
1644
1645
    /// The highest policy serial `remote` has ever presented.
1646410×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1647410×
        fs::read_to_string(self.policy_serial_path(remote))
1648410×
            .ok()
1649410×
            .and_then(|s| s.trim().parse().ok())
1650410×
    }
1651
165272×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
165372×
        let p = self.policy_serial_path(remote);
165472×
        fs::create_dir_all(p.parent().unwrap())?;
165572×
        write_atomic(&p, serial.to_string().as_bytes())
165672×
    }
1657
165832×
    fn lazy_dir(&self) -> PathBuf {
165932×
        self.oxy.join("lazy")
166032×
    }
1661
1662
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
16635×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
16645×
        fs::create_dir_all(self.lazy_dir())?;
16655×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
16665×
    }
1667
1668
    /// Which remote promised an absent blob, if any.
166917×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
167017×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
167117×
            .ok()
167217×
            .map(|s| s.trim().to_string())
167317×
    }
1674
1675
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
16765×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
16775×
        let Some(remote_name) = self.lazy_remote(blob) else {
16780×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1679
        };
16805×
        let remote = self.open_named_remote(&remote_name)?;
16815×
        let objects = remote.objects(&[*blob])?;
168211×
        for (ty, body) in objects {
168311×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
168411×
                self.store.put(ty, &body)?;
16850×
            }
1686
        }
16875×
        if !self.store.has(blob) {
16880×
            return fail(format!(
1689
                "{remote_name} did not send blob {}",
16900×
                blob.short(12)
1691
            ));
16925×
        }
16935×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
16945×
        Ok(())
16955×
    }
1696
1697
    /// After importing from `remote`, record every blob the changes reference
1698
    /// that the store lacks as lazily available from that remote.
16995×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
17005×
        let mut n = 0;
17015×
        for h in changes {
17024×
            let c = self.store.get_change(h)?;
170313×
            for e in &c.edits {
170413×
                if let Edit::Replace { old, new, .. } = e {
17056×
                    for b in [old, new].into_iter().flatten() {
17066×
                        if !self.store.has(b) {
17074×
                            self.register_lazy(b, remote)?;
17084×
                            n += 1;
17092×
                        }
1710
                    }
17117×
                }
1712
            }
1713
        }
17145×
        Ok(n)
17155×
    }
1716
1717
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1718410×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1719410×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1720567×
        for st in view
1721410×
            .bookmarks
1722410×
            .values()
1723410×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1724
        {
1725567×
            if let Ok(s) = self.store.get_state(st) {
1726567×
                have.extend(s.heads);
1727567×
            }
1728
        }
1729410×
        have.extend(view.workspaces.values().copied());
1730410×
        Ok(have.into_iter().collect())
1731410×
    }
1732
1733
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1734416×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1735416×
        let remote = self.open_named_remote(remote_name)?;
1736413×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1737410×
        let resp = {
1738411×
            let _t = crate::timing::phase("fetch: refs");
1739411×
            remote.refs()?
1740
        };
1741
        // The host's transparency log (spec §14.8): a fork fails here.
1742410×
        let log_phase = crate::timing::phase("fetch: transparency log");
1743410×
        let log = self.check_log(
1744410×
            &self.remote_url(remote_name)?,
1745410×
            self.config.remote_cas.get(remote_name).map(Path::new),
1746410×
            &resp,
17470×
        )?;
1748410×
        drop(log_phase);
1749410×
        let mut log_notes = log.notes.clone();
1750
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1751
        // and signed by roots we trust, or on first contact. A remote that
1752
        // once presented a policy may never present none or an older one:
1753
        // that is a downgrade. A remote that never presented one is
1754
        // unverified, and this fetch is checked only as far as possible.
1755410×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1756410×
        let seen = self.remote_policy_serial(remote_name);
1757410×
        let mut unverified = false;
1758410×
        match &resp.policy {
175938×
            Some(sp) => {
176038×
                if seen.is_some_and(|s| sp.policy.serial < s) {
17610×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
176238×
                }
176314×
                match &local_policy {
176414×
                    Some(l) if sp.policy.serial < l.serial => {}
176514×
                    Some(l) if sp.policy.serial == l.serial => {
176610×
                        if sp.policy.hash() != l.hash() {
17670×
                            return fail(format!(
1768
                                "{remote_name} presents a different policy with the same serial {}",
1769
                                l.serial
1770
                            ));
177110×
                        }
1772
                    }
1773
                    _ => {
177428×
                        self.adopt_policy_chain(
177528×
                            &resp.history,
177628×
                            sp,
177728×
                            &format!("oxy fetch {remote_name}"),
1778
                        )
177928×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1780
                    }
1781
                }
178238×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1783
            }
1784
            None => {
1785372×
                if seen.is_some() {
17860×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1787372×
                }
1788372×
                unverified = true;
1789
            }
1790
        }
1791410×
        let policy = if unverified {
1792372×
            None
1793
        } else {
179438×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1795
        };
1796410×
        let (op_ref, op) = self.head_op()?;
1797410×
        let mut view = op.view.clone();
1798410×
        let have = self.known_heads(&view)?;
1799410×
        let mut report = Vec::new();
1800410×
        let mut skipped = Vec::new();
1801410×
        let max_blob = self.config.max_blob;
1802
        // One negotiation and one bundle for every bookmark's heads at
1803
        // once (oxygen#158): a bookmark at a time cost a round trip each and
1804
        // sent again the changes bookmarks share, as `have` did not grow
1805
        // between them (160 bookmarks: 160 bundles, 49k changes encoded for
1806
        // a few hundred). Heads already here, with every attestation's
1807
        // signer known, need no round trip at all.
1808410×
        let mut wanted: Vec<ChangeHash> = resp
1809410×
            .refs
1810410×
            .iter()
1811460×
            .flat_map(|r| r.heads.iter().copied())
1812617×
            .filter(|h| !self.store.has(h))
1813410×
            .collect();
1814410×
        wanted.sort();
1815410×
        wanted.dedup();
1816
        // A bundle also carries the identities and certificates of the keys
1817
        // that signed the remote's attestations (spec §16.2): with no change
1818
        // wanted, ask anyway when one of those signers is unknown here.
1819410×
        let unknown_signer = resp
1820410×
            .refs
1821410×
            .iter()
1822450×
            .filter_map(|r| r.attestation.as_ref())
1823410×
            .chain(resp.tags.iter().filter_map(|t| t.attestation.as_ref()))
1824410×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
1825410×
            .any(|k| {
182683×
                self.store.get_identity(&k).is_err()
182727×
                    && !matches!(self.store.certificate_of(&k), Ok(Some(_)))
182883×
            });
1829410×
        let shallow = self.is_shallow();
1830410×
        let imported: Vec<ChangeHash> = if wanted.is_empty() && !unknown_signer {
1831118×
            Vec::new()
1832
        } else {
1833292×
            let needed = {
1834292×
                let _t = crate::timing::phase("fetch: negotiate");
1835292×
                remote.negotiate(&have, &wanted)?
1836
            };
1837292×
            let bundle = {
1838292×
                let _t = crate::timing::phase("fetch: bundle");
1839292×
                remote.fetch(&needed, max_blob)?
1840
            };
1841
            // Changes are not individually re-verified here: each bookmark's
1842
            // attestation (checked below) binds its whole state, and the
1843
            // receiver of the push verified the added changes at that time.
1844
            // A shallow repository takes changes whose dependencies it never
1845
            // held (below what it cloned), as its clone did (#137).
1846292×
            let _t = crate::timing::phase("fetch: import");
1847292×
            if shallow {
18482×
                self.import_bundle_shallow(&bundle, false)?
1849
            } else {
1850290×
                self.import_bundle(&bundle, false)?
1851
            }
1852
        };
1853410×
        if shallow {
18542×
            self.refresh_boundary(&imported)?;
1855408×
        }
1856410×
        if max_blob.is_some() {
18574×
            self.register_missing_blobs(&imported, remote_name)?;
1858406×
        }
1859410×
        let boundary = if shallow {
18602×
            self.boundary()
1861
        } else {
1862408×
            BTreeSet::new()
1863
        };
1864
        // Each bookmark's new changes: those just imported that its heads
1865
        // reach, for the report.
1866410×
        let mut new_deps: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
1867551×
        for h in &imported {
1868551×
            if let Ok(m) = self.store.get_change_meta(h) {
1869551×
                new_deps.insert(*h, m.deps);
1870551×
            }
1871
        }
1872445×
        let new_in = |heads: &[ChangeHash]| -> usize {
1873445×
            let mut seen: HashSet<ChangeHash> = HashSet::new();
1874445×
            let mut stack: Vec<ChangeHash> = heads
1875445×
                .iter()
1876602×
                .filter(|h| new_deps.contains_key(*h))
1877445×
                .copied()
1878445×
                .collect();
18791024×
            while let Some(h) = stack.pop() {
1880579×
                if seen.insert(h) {
1881573×
                    stack.extend(
1882573×
                        new_deps[&h]
1883573×
                            .iter()
1884573×
                            .filter(|d| new_deps.contains_key(*d) && !seen.contains(*d)),
1885
                    );
18866×
                }
1887
            }
1888445×
            seen.len()
1889445×
        };
1890410×
        let checks = crate::timing::phase("fetch: check each bookmark");
1891457×
        for r in resp.refs {
1892614×
            for h in &r.heads {
1893614×
                if !self.store.has(h) && !boundary.contains(h) {
18940×
                    return fail(format!("remote did not send head {}", h.short(12)));
1895614×
                }
1896
            }
1897457×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1898457×
            if state != r.state {
18990×
                return fail(format!(
1900
                    "remote state {} does not match its heads",
19010×
                    r.state.short(12)
1902
                ));
1903457×
            }
1904457×
            if let Some(p) = &policy {
190541×
                let Some(sa) = &r.attestation else {
19060×
                    return fail(format!(
1907
                        "{remote_name}/{} has no attestation, which its policy requires",
1908
                        r.name
1909
                    ));
1910
                };
191141×
                let signer = sa
191241×
                    .sigs
191341×
                    .first()
191441×
                    .map(|s| s.key)
191541×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
191641×
                if !p.authorizes(&signer, &r.name) {
191720×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
191821×
                }
1919416×
            }
1920457×
            if let Some(sa) = &r.attestation {
1921
                let AttestBody::Ref {
192273×
                    old_state,
192373×
                    new_state,
1924
                    ..
192573×
                } = &sa.attest.body
1926
                else {
19270×
                    return fail("remote sent a non-ref attestation for a bookmark");
1928
                };
192973×
                let (old_state, new_state) = (*old_state, *new_state);
193073×
                let serial = self
193173×
                    .check_ref_attest_body(
193273×
                        sa,
193373×
                        &r.name,
193473×
                        &old_state,
193573×
                        &new_state,
193673×
                        self.last_seen_serial(remote_name, &r.name),
1937
                        true,
1938
                    )
193973×
                    .map_err(|e| {
19400×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
19410×
                    })?;
194273×
                if new_state != r.state {
19430×
                    return fail(format!(
1944
                        "attestation for {}/{} does not cover its current state",
1945
                        remote_name, r.name
1946
                    ));
194773×
                }
1948
                // A signature this client cannot verify (its signer unknown
1949
                // here, as from a host that did not send the identity, or
1950
                // bad) fails that bookmark alone: it stays as it was and
1951
                // the rest are fetched (oxygenhub#266). The current
1952
                // bookmark, which a pull would take, still fails the fetch.
1953
                // A policy's requirements were checked above and still fail.
195473×
                if let Err(e) = self.verify_attest_signature(sa) {
195512×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
195612×
                    if r.name == self.config.bookmark {
19573×
                        return fail(why);
19589×
                    }
19599×
                    skipped.push((r.name, why));
19609×
                    continue;
196161×
                }
196261×
                let ar = self.store.put_attest(&sa.attest)?;
196361×
                for sig in &sa.sigs {
196461×
                    self.store.put_signature(&ar, sig)?;
1965
                }
196661×
                self.record_serial(remote_name, &r.name, serial)?;
1967384×
            }
1968445×
            view.remotes
1969445×
                .entry(remote_name.to_string())
1970445×
                .or_default()
1971445×
                .insert(r.name.clone(), state);
1972445×
            let n = new_in(&r.heads);
1973445×
            report.push((r.name, r.heads, n));
1974
        }
1975407×
        drop(checks);
1976407×
        let tags_phase = crate::timing::phase("fetch: tags");
1977407×
        let mut new_tags = 0;
1978407×
        for t in &resp.tags {
197932×
            if view.tags.contains_key(&t.name) {
19807×
                continue;
198125×
            }
1982
            // Withdrawn here: the name is not used again.
198325×
            if self.tag_withdrawal(&t.name)?.is_some() {
19840×
                continue;
198525×
            }
1986
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
198725×
            let missing: Vec<ChangeHash> = t
198825×
                .heads
198925×
                .iter()
199025×
                .filter(|h| !self.store.has(h))
199125×
                .copied()
199225×
                .collect();
199325×
            if !missing.is_empty() {
19940×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
19950×
                let bundle = remote.fetch(&needed, max_blob)?;
19960×
                self.import_bundle(&bundle, false)?;
199725×
            }
199825×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
199925×
            let mut check = TagCheck::Fetched {
200025×
                remote: remote_name,
200125×
                log: &log,
200225×
                notes: &mut log_notes,
200325×
            };
200425×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
200523×
                Ok(()) => new_tags += 1,
2006
                // Nothing says when a short-lived key signed it: the tag is
2007
                // left out, said so, and the rest is fetched (oxygen#129).
20082×
                Err(e) if e.untimed => {
20092×
                    skipped.push((format!("tags/{}", t.name), e.reason));
20102×
                }
20110×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
2012
            }
2013
        }
2014
        // The remote withdrew a tag this repository has: so does this one,
2015
        // once the withdrawal is checked as a push's would be; one that is
2016
        // not is left as it is, said so (oxygenhub#301).
2017407×
        drop(tags_phase);
2018407×
        let mut withdrawn_tags = Vec::new();
2019407×
        for t in &resp.withdrawn {
20201×
            if !view.tags.contains_key(&t.name) {
20210×
                continue;
20221×
            }
20231×
            let mut check = TagCheck::Fetched {
20241×
                remote: remote_name,
20251×
                log: &log,
20261×
                notes: &mut log_notes,
20271×
            };
20281×
            match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut check) {
20291×
                Ok(true) => withdrawn_tags.push(t.name.clone()),
20300×
                Ok(false) => {}
20310×
                Err(e) => skipped.push((
20320×
                    format!("tags/{}", t.name),
20330×
                    format!("withdrawn on {remote_name}, kept here: {}", e.reason),
20340×
                )),
2035
            }
2036
        }
2037407×
        if view != op.view {
2038389×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
203918×
        }
2040407×
        let _ = self.run_hook(
2041407×
            "post-fetch",
2042407×
            &format!(
2043
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
2044407×
                json_str(remote_name),
2045442×
                json_array(report.iter().map(|(n, heads, _)| format!(
2046
                    "{{\"name\":{},\"heads\":{}}}",
2047442×
                    json_str(n),
2048599×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
2049
                )))
2050
            ),
2051
        );
2052407×
        Ok(FetchReport {
2053407×
            refs: report,
2054407×
            unverified,
2055407×
            new_tags,
2056407×
            withdrawn_tags,
2057407×
            log_notes,
2058407×
            skipped,
2059407×
        })
2060416×
    }
2061
2062
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
2063
    /// the changes within `depth` steps of its heads, and the boundary below.
20643×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
20653×
        let remote = self.open_named_remote(remote_name)?;
20663×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
20673×
        let resp = remote.refs()?;
20683×
        let bookmark = self.config.bookmark.clone();
20693×
        if let Some(sp) = &resp.policy {
20700×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
20710×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
20720×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
20733×
        }
20743×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
20750×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
2076
        };
20773×
        if r.heads.is_empty() {
20780×
            return Ok(0);
20793×
        }
2080
        // Base: the remote's checkpoint of exactly these heads, without its
2081
        // graph blobs, which come in parts below (#137).
20823×
        let cp_bundle = {
20833×
            let _t = crate::timing::phase("shallow: checkpoint request");
20843×
            remote.checkpoint_index(&r.heads)?
2085
        };
2086
        // In one batch: a big state's checkpoint is tens of thousands of
2087
        // graph blobs and chunks, which stored one by one were each written
2088
        // loose and flushed (a VS Code clone ran at 27 objects a second).
20893×
        let objects: Vec<(ObjectType, &[u8])> = cp_bundle
20903×
            .objects
20913×
            .iter()
20929×
            .map(|(ty, body)| (*ty, body.as_slice()))
20933×
            .collect();
20943×
        let t_store = crate::timing::phase("shallow: store the checkpoint");
20953×
        let batch = self.store.begin_batch()?;
20963×
        let stored = self.store.put_many(&objects);
20973×
        batch.finish()?;
20983×
        drop(t_store);
20993×
        let cp_ref = objects
21003×
            .iter()
21013×
            .zip(stored?)
21029×
            .find(|((ty, _), _)| *ty == ObjectType::Checkpoint)
21033×
            .map(|(_, r)| r);
21043×
        let Some(cp_ref) = cp_ref else {
21050×
            return fail(format!("{remote_name} sent no checkpoint"));
2106
        };
2107
        // The graph blobs the payload names, with their chunks, a part at
2108
        // a time (#137): one answer for a big state was gigabytes, held
2109
        // whole on both sides. A remote that sent the whole checkpoint has
2110
        // left none to ask for.
21113×
        let cp = crate::objects::Checkpoint::decode(
21123×
            &self.store.get_typed(&cp_ref, ObjectType::Checkpoint)?,
21130×
        )?;
21143×
        let graphs: Vec<ObjectRef> = self
21153×
            .checkpoint_graph_blobs(&cp)?
21163×
            .into_iter()
21173×
            .filter(|b| !self.store.has(b))
21183×
            .collect();
2119
        {
21203×
            let _t = crate::timing::phase("shallow: the checkpoint's graphs, in parts");
21213×
            for part in graphs.chunks(CHECKPOINT_PART) {
21220×
                let objects = remote.objects(part)?;
21230×
                let objects: Vec<(ObjectType, &[u8])> = objects
21240×
                    .iter()
21250×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
21260×
                    .map(|(ty, body)| (*ty, body.as_slice()))
21270×
                    .collect();
21280×
                let batch = self.store.begin_batch()?;
21290×
                let stored = self.store.put_many(&objects);
21300×
                batch.finish()?;
21310×
                stored?;
2132
            }
21333×
            if let Some(b) = graphs.iter().find(|b| !self.store.has(b)) {
21340×
                return fail(format!(
2135
                    "{remote_name} did not send graph blob {}",
21360×
                    b.short(12)
2137
                ));
21383×
            }
2139
        }
21403×
        self.install_checkpoint(&bookmark, &cp_ref)?;
21413×
        let _t_blobs = crate::timing::phase("shallow: the binary files' blobs");
2142
        // The blobs of the state's opaque files come with no change when the
2143
        // window holds none of the changes that set them (#137): fetch them
2144
        // now, or under `filter.max-blob` leave them to be fetched on read.
21453×
        let base = State::from_checkpoint_history(&self.read_blob(&cp.payload)?)?;
21463×
        let mut missing: Vec<ObjectRef> = base
21473×
            .opaque_nodes()
21483×
            .iter()
21493×
            .flat_map(|n| base.live_blobs(n))
21503×
            .filter(|b| !self.store.has(b))
21513×
            .collect();
21523×
        missing.sort();
21533×
        missing.dedup();
21543×
        if self.config.max_blob.is_some() {
21551×
            for b in &missing {
21561×
                self.register_lazy(b, remote_name)?;
2157
            }
2158
        } else {
21592×
            for part in missing.chunks(512) {
21601×
                let objects = remote.objects(part)?;
21611×
                let objects: Vec<(ObjectType, &[u8])> = objects
21621×
                    .iter()
21632×
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
21642×
                    .map(|(ty, body)| (*ty, body.as_slice()))
21651×
                    .collect();
21661×
                let batch = self.store.begin_batch()?;
21671×
                let stored = self.store.put_many(&objects);
21681×
                batch.finish()?;
21691×
                stored?;
2170
            }
21712×
            if let Some(b) = missing.iter().find(|b| !self.store.has(b)) {
21720×
                return fail(format!("{remote_name} did not send blob {}", b.short(12)));
21732×
            }
2174
        }
2175
        // History window. Depth 0 takes none (#137): the checkpoint holds
2176
        // every change's metadata, and its heads become the boundary, so a
2177
        // state of many heads (33,835 in the VS Code import) costs nothing
2178
        // to fetch.
21793×
        let imported = if depth == 0 {
21802×
            let mut boundary = self.boundary();
21812×
            boundary.extend(r.heads.iter().filter(|h| !self.store.has(h)).copied());
21822×
            self.write_boundary(&boundary)?;
21832×
            Vec::new()
2184
        } else {
21851×
            let wanted = remote.shallow(&r.heads, depth)?;
21861×
            let bundle = remote.fetch(&wanted, self.config.max_blob)?;
21871×
            self.import_bundle_shallow(&bundle, false)?
2188
        };
21893×
        if self.config.max_blob.is_some() {
21901×
            self.register_missing_blobs(&imported, remote_name)?;
21912×
        }
21923×
        self.refresh_boundary(&imported)?;
21933×
        if let Some(sa) = &r.attestation {
21940×
            let ar = self.store.put_attest(&sa.attest)?;
21950×
            for sig in &sa.sigs {
21960×
                self.store.put_signature(&ar, sig)?;
2197
            }
21980×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
21990×
                self.record_serial(remote_name, &r.name, serial)?;
22000×
            }
22013×
        }
22023×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
22033×
        let (op_ref, op) = self.head_op()?;
22043×
        let mut view = op.view.clone();
22053×
        view.remotes
22063×
            .entry(remote_name.to_string())
22073×
            .or_default()
22083×
            .insert(r.name.clone(), state);
22093×
        self.record_op(
22103×
            &[op_ref],
22113×
            &format!("oxy fetch {remote_name} --depth {depth}"),
22123×
            view,
22130×
        )?;
22143×
        Ok(imported.len())
22153×
    }
2216
2217
    /// Fetch, then take the union of the local bookmark's state with the
2218
    /// remote's: no merge change, conflicts become reified (spec §9.4).
2219109×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
2220109×
        let _wc = self.lock_working_copy()?;
2221109×
        let skipped = self.fetch(remote_name)?.skipped;
2222105×
        let (op_ref, op) = self.head_op()?;
2223105×
        let current = self.config.bookmark.clone();
2224105×
        let mut local_current = self.heads_of(&op.view, &current)?;
2225105×
        local_current.sort();
2226105×
        let mut view = op.view.clone();
2227105×
        let mut current_heads = local_current.clone();
2228105×
        let mut changed = false;
2229105×
        let mut others = Vec::new();
2230105×
        let tracked = op
2231105×
            .view
2232105×
            .remotes
2233105×
            .get(remote_name)
2234105×
            .cloned()
2235105×
            .unwrap_or_default();
2236110×
        for (name, remote_state) in tracked {
2237
            // Every local bookmark tracks the remote's of the same name;
2238
            // the current one may be new here.
2239110×
            let local_state = op.view.bookmarks.get(&name).copied();
2240110×
            if local_state.is_none() && name != current {
22411×
                continue;
2242109×
            }
2243109×
            if local_state == Some(remote_state) {
224410×
                continue;
224599×
            }
224699×
            let local = self.heads_of(&op.view, &name)?;
224799×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2248134×
            if remote_heads.iter().all(|h| local.contains(h)) {
22490×
                continue;
225099×
            }
225199×
            let mut all = local.clone();
225299×
            all.extend(remote_heads);
225399×
            let st = self.load_state_history(&all)?;
225499×
            let mut heads = st.maximal(&all);
225599×
            heads.sort();
225699×
            let mut sorted_local = local;
225799×
            sorted_local.sort();
225899×
            if heads == sorted_local {
22591×
                continue;
226098×
            }
226198×
            view.bookmarks.insert(
226298×
                name.clone(),
226398×
                self.store.put_state(&StateObject::new(heads.clone()))?,
2264
            );
226598×
            if name == current {
226696×
                changed = true;
226796×
                current_heads = heads;
226896×
            } else {
22692×
                others.push(name);
22702×
            }
2271
        }
2272105×
        if changed || !others.is_empty() {
227397×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
22748×
        }
2275
        // The working copy follows its bookmark whenever nothing would be
2276
        // lost, also when this pull brought nothing new but it had been
2277
        // left behind (oxygen#89).
2278105×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2279
        Ok(PullReport {
2280105×
            heads: if changed {
228196×
                current_heads
2282
            } else {
22839×
                local_current
2284
            },
2285105×
            changed,
2286105×
            checked_out,
2287105×
            others,
2288105×
            skipped,
2289
        })
2290109×
    }
2291
2292
    /// How many changes the working copy's bookmark has that its base
2293
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2294
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2295
    /// the bookmark or holds changes the bookmark lacks. History is read
2296
    /// only when the base and the bookmark's heads differ (oxygen#89).
229712×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
229812×
        let (_, wc) = self.working_copy()?;
229912×
        let mut base = wc.deps.clone();
230012×
        base.sort();
230112×
        let mut heads = self.bookmark_heads()?;
230212×
        heads.sort();
230312×
        if base == heads || heads.is_empty() {
230411×
            return Ok(None);
23051×
        }
23061×
        let state = self.load_state_history(&heads)?;
23071×
        if !base.iter().all(|h| state.contains(h)) {
23080×
            return Ok(None);
23091×
        }
23101×
        let had = if base.is_empty() {
23110×
            0
2312
        } else {
23131×
            self.load_state_history(&base)?.len()
2314
        };
23151×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
231612×
    }
2317
2318
    /// Bring the working copy to `heads`, the state of its bookmark
2319
    /// `bookmark`, when nothing would be lost: its base is part of that
2320
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2321
    /// with uncommitted work, the work comes along when the new changes
2322
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2323
    /// it followed only from exactly the bookmark's old heads, so a working
2324
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2325
    /// or a pull from another workspace) never caught up, and nothing said
2326
    /// so (oxygen#74, #89). Returns whether it moved.
2327105×
    pub fn follow_bookmark(
2328105×
        &self,
2329105×
        heads: &[ChangeHash],
2330105×
        bookmark: &str,
2331105×
        command: &str,
2332105×
    ) -> Result<bool> {
2333105×
        let snap = self.snapshot(command)?;
2334105×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2335105×
        let mut base = snap.base.maximal(&snap.wc.deps);
2336105×
        base.sort();
2337105×
        let mut target = heads.to_vec();
2338105×
        target.sort();
2339105×
        if base == target {
23408×
            return Ok(false);
234197×
        }
234297×
        let state = self.load_state_history(heads)?;
2343185×
        if !base.iter().all(|h| state.contains(h)) {
2344
            // The working copy holds changes the bookmark lacks: not ours to move.
23450×
            return Ok(false);
234697×
        }
234797×
        if clean {
234897×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
234997×
            Ok(true)
2350
        } else {
23510×
            Ok(self
23520×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
23530×
                .is_ok())
2354
        }
2355105×
    }
2356
2357
    /// Withdraw tag `tag` on `remote_name` (`oxy push --delete tags/NAME`,
2358
    /// oxygenhub#301): withdrawn here first when it still is a tag here
2359
    /// (`oxy tag delete`), then the withdrawal alone is sent, with its
2360
    /// signer's identity and certificate.
23613×
    pub fn push_tag_withdrawal(&self, remote_name: &str, tag: &str) -> Result<Vec<RefResult>> {
23623×
        let remote = self.open_named_remote(remote_name)?;
23633×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
23643×
        let resp = remote.refs()?;
23653×
        let name = format!("tags/{tag}");
23663×
        if resp.withdrawn.iter().any(|t| t.name == tag) {
23671×
            return Ok(vec![RefResult {
23681×
                name,
23691×
                ok: true,
23701×
                reason: "already withdrawn".into(),
23711×
            }]);
23722×
        }
23732×
        let Some(there) = resp.tags.iter().find(|t| t.name == tag) else {
23740×
            return fail(format!("{remote_name} has no tag {tag}"));
2375
        };
23762×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
23770×
            return fail(format!("{remote_name} enforces a trust policy; withdrawing a tag needs an identity (`oxy identity create`)"));
23782×
        }
23792×
        if self.tag_withdrawal(tag)?.is_none() {
23802×
            match self.view()?.tags.get(tag) {
23812×
                Some(st) if *st == there.state => {
23822×
                    self.tag_delete(tag, "")?;
2383
                }
2384
                Some(_) => {
23850×
                    return fail(format!(
2386
                        "tag {tag} names another state here than on {remote_name}"
2387
                    ))
2388
                }
2389
                None => {
23900×
                    return fail(format!(
2391
                        "there is no tag {tag} here to withdraw: `oxy fetch {remote_name}` first"
2392
                    ))
2393
                }
2394
            }
23950×
        }
23962×
        let Some(w) = self
23972×
            .withdrawn_refs()?
23982×
            .into_iter()
23992×
            .find(|w| w.name == tag && w.state == there.state)
2400
        else {
24010×
            return fail(format!(
2402
                "tag {tag} was withdrawn here at another state than {remote_name}'s"
2403
            ));
2404
        };
24052×
        let mut bundle = Bundle::default();
24062×
        let signers: Vec<KeyId> = w
24072×
            .attestation
24082×
            .iter()
24092×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
24102×
            .collect();
24112×
        for k in &signers {
24122×
            if let Ok(id) = self.identity(k) {
24132×
                bundle.objects.push((ObjectType::Identity, id.encode()));
24142×
            }
2415
        }
24162×
        self.attach_certificates_for(&mut bundle, &signers)?;
24172×
        remote.push(bundle, vec![], None, vec![w])
24183×
    }
2419
2420
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2421
    /// changes and attesting the reference when a key is available.
2422
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2423
    /// state, attested when we have an identity. The local bookmark, if
2424
    /// any, is kept; only the remote-tracking entry goes.
24258×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
24268×
        if let Some(tag) = bookmark.strip_prefix("tags/") {
24273×
            return self.push_tag_withdrawal(remote_name, tag);
24285×
        }
24295×
        let remote = self.open_named_remote(remote_name)?;
24305×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
24315×
        let resp = remote.refs()?;
24327×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
24331×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2434
        };
24354×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
24360×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
24374×
        }
24384×
        let attestation = match self.secret_key()? {
24392×
            Some(_) => Some(self.sign_attest(&Attest {
24402×
                repo: self.id()?,
24412×
                hlc: Hlc::now(),
24422×
                body: AttestBody::Ref {
24432×
                    name: bookmark.to_string(),
24442×
                    old_state: r.state,
24452×
                    new_state: ObjectRef::ZERO,
24462×
                    serial: r.last_serial.unwrap_or(0) + 1,
24472×
                },
24480×
            })?),
24492×
            None => None,
2450
        };
24514×
        let results = remote.push(
24524×
            Bundle::default(),
24534×
            vec![RefUpdate {
24544×
                name: bookmark.to_string(),
24554×
                old_state: r.state,
24564×
                new_state: ObjectRef::ZERO,
24574×
                force: true,
24584×
                attestation,
24594×
            }],
24604×
            None,
24614×
            vec![],
24620×
        )?;
24634×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
24642×
            let (op_ref, op) = self.head_op()?;
24652×
            let mut view = op.view.clone();
24662×
            if let Some(m) = view.remotes.get_mut(remote_name) {
24672×
                m.remove(bookmark);
24682×
            }
24692×
            self.record_op(
24702×
                &[op_ref],
24712×
                &format!("oxy push {remote_name} --delete {bookmark}"),
24722×
                view,
24730×
            )?;
24742×
        }
24754×
        Ok(results)
24768×
    }
2477
2478
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2479
    /// repository's config (its URL, token, CA and store settings), its
2480
    /// tracking bookmarks in the view, and a store remote's mirror under
2481
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
24823×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
24833×
        if !self.config.remotes.contains_key(name) {
24841×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
24852×
        }
24862×
        let prefix = format!("remote.{name}.");
24872×
        let keys: Vec<String> = self
24882×
            .config
24892×
            .repo_layer()
24902×
            .keys()
24914×
            .filter(|k| k.starts_with(&prefix))
24922×
            .cloned()
24932×
            .collect();
24943×
        for k in keys {
24953×
            self.config.set(&k, "")?;
2496
        }
24972×
        self.config.remotes.remove(name);
24982×
        self.save_config()?;
24992×
        let (op_ref, op) = self.head_op()?;
25002×
        if op.view.remotes.contains_key(name) {
25011×
            let mut view = op.view.clone();
25021×
            view.remotes.remove(name);
25031×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
25041×
        }
25052×
        let mirror = self.oxy.join("remotes").join(name);
25062×
        if mirror.is_dir() {
25070×
            fs::remove_dir_all(&mirror)?;
25082×
        }
25092×
        Ok(())
25103×
    }
2511
2512
    /// Send `bundle`'s blobs and chunks ahead of it, in parts of about
2513
    /// `push.batch-bytes` of objects alone, when the whole would be larger
2514
    /// (oxygen#133): one change can bring more blobs than one request may
2515
    /// carry, and a proxy in front of a hub refuses a request past its limit
2516
    /// (Cloudflare's is 100 MB). What is left, the changes with their
2517
    /// identities and states, is returned to send as before. A receiver
2518
    /// stores objects as they come, and checks a change's blobs are stored.
2519335×
    fn send_objects_ahead(
2520335×
        &self,
2521335×
        remote: &dyn crate::protocol::Remote,
2522335×
        remote_name: &str,
2523335×
        mut bundle: Bundle,
2524335×
        progress: crate::store::Progress,
2525335×
    ) -> Result<Bundle> {
2526335×
        let limit = self.config.push_batch_bytes;
2527335×
        let changes: u64 = bundle
2528335×
            .changes
2529335×
            .iter()
2530409×
            .map(|(c, _)| c.encode().len() as u64)
2531335×
            .sum();
2532335×
        let objects: u64 = bundle.objects.iter().map(|(_, b)| b.len() as u64).sum();
2533335×
        if changes + objects <= limit {
2534328×
            return Ok(bundle);
25357×
        }
25367×
        let (mut kept, mut parts, mut part, mut bytes) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
25379×
        for (ty, body) in std::mem::take(&mut bundle.objects) {
25389×
            if !matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
25390×
                kept.push((ty, body));
25400×
                continue;
25419×
            }
25429×
            if !part.is_empty() && bytes + body.len() as u64 > limit {
25433×
                parts.push(std::mem::take(&mut part));
25443×
                bytes = 0;
25456×
            }
25469×
            bytes += body.len() as u64;
25479×
            part.push((ty, body));
2548
        }
25497×
        if !part.is_empty() {
25501×
            parts.push(part);
25516×
        }
25527×
        let n = parts.len();
25537×
        for (i, objects) in parts.into_iter().enumerate() {
25544×
            progress(&format!(
25554×
                "objects {} of {n}: {} blobs and chunks",
25564×
                i + 1,
25574×
                objects.len()
25584×
            ));
25594×
            let results = remote.push(
25604×
                Bundle {
25614×
                    objects,
25624×
                    ..Default::default()
25634×
                },
25644×
                vec![],
25654×
                None,
25664×
                vec![],
25670×
            )?;
25684×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
25694×
                Some(r) if r.ok => {}
25700×
                Some(r) => {
25710×
                    return fail(format!(
2572
                        "{remote_name} refused objects part {} of {n}: {}",
25730×
                        i + 1,
2574
                        r.reason
2575
                    ))
2576
                }
2577
                None => {
25780×
                    return fail(format!(
2579
                        "{remote_name} does not take a push in parts, and this one is too large for one: update the server's oxy"
2580
                    ))
2581
                }
2582
            }
2583
        }
25847×
        bundle.objects = kept;
25857×
        Ok(bundle)
2586335×
    }
2587
2588
    /// `changes`, in dependency order, cut into batches of about
2589
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2590
    /// There is always one, perhaps empty.
2591330×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2592330×
        let blob_len = |r: &ObjectRef| -> u64 {
259337×
            self.store
259437×
                .get_typed(r, ObjectType::Blob)
259537×
                .ok()
259637×
                .and_then(|b| Blob::decode(&b).ok())
259737×
                .map_or(0, |b| b.length)
259837×
        };
2599330×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2600409×
        for h in changes {
2601409×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2602409×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2603409×
            let mut weight = raw.len() as u64;
2604490×
            for t in &texts {
2605490×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
260626×
                    weight += blob_len(r);
2607464×
                }
2608
            }
2609642×
            for e in &c.edits {
261011×
                if let Edit::Replace { new: Some(b), .. } = e {
261111×
                    weight += blob_len(b);
2612631×
                }
2613
            }
2614409×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
26155×
                out.push(std::mem::take(&mut batch));
26165×
                bytes = 0;
2617404×
            }
2618409×
            batch.push(*h);
2619409×
            bytes += weight;
2620
        }
2621330×
        out.push(batch);
2622330×
        Ok(out)
2623330×
    }
2624
2625390×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2626390×
        let bookmark = self.config.bookmark.clone();
2627390×
        self.push_bookmark(remote_name, &bookmark, force)
2628390×
    }
2629
2630
    /// `push` for a named bookmark (`oxy push -b NAME`).
2631405×
    pub fn push_bookmark(
2632405×
        &self,
2633405×
        remote_name: &str,
2634405×
        bookmark: &str,
2635405×
        force: bool,
2636405×
    ) -> Result<Vec<RefResult>> {
2637405×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2638405×
    }
2639
2640
    /// `push_bookmark`, saying how a long push is going: one line per
2641
    /// batch sent (oxygen#95).
2642
    /// What a push may take the remote to hold already: the heads of the
2643
    /// bookmark pushed, and of every other bookmark it lists that are held
2644
    /// here, so a new bookmark made from main sends only what main lacks
2645
    /// (oxygen#142), not its whole history again.
2646332×
    pub(crate) fn remote_holds(
2647332×
        &self,
2648332×
        refs: &[crate::protocol::RemoteRef],
2649332×
        bookmark_heads: &[ChangeHash],
2650332×
    ) -> Vec<ChangeHash> {
2651332×
        let mut have: Vec<ChangeHash> = bookmark_heads.to_vec();
2652374×
        for h in refs.iter().flat_map(|r| &r.heads) {
2653374×
            if !have.contains(h) && self.store.has(h) {
265440×
                have.push(*h);
2655334×
            }
2656
        }
2657332×
        have
2658332×
    }
2659
2660414×
    pub fn push_bookmark_with(
2661414×
        &self,
2662414×
        remote_name: &str,
2663414×
        bookmark: &str,
2664414×
        force: bool,
2665414×
        progress: crate::store::Progress,
2666414×
    ) -> Result<Vec<RefResult>> {
2667414×
        let (op_ref, op) = self.head_op()?;
2668414×
        if !op.view.bookmarks.contains_key(bookmark) {
26690×
            return fail(format!("no bookmark {bookmark}"));
2670414×
        }
2671414×
        let bookmark = bookmark.to_string();
2672414×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2673
        // pre-push hook: may veto before the remote is contacted.
2674414×
        self.run_hook(
2675414×
            "pre-push",
2676414×
            &format!(
2677
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2678414×
                json_str(remote_name),
2679414×
                json_str(&bookmark),
2680818×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2681
            ),
26821×
        )?;
2683413×
        let remote = self.open_named_remote(remote_name)?;
2684413×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2685410×
        let resp = remote.refs()?;
2686410×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2687410×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2688410×
        let policy_to_send = match (&local_policy, &resp.policy) {
268944×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
269016×
            (Some(l), None) => Some(l.clone()),
269126×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
26921×
                return fail(format!(
2693
                    "{remote_name} has a newer policy (serial {}); fetch first",
2694
                    r.policy.serial
2695
                ));
2696
            }
2697375×
            _ => None,
2698
        };
2699409×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2700409×
        if remote_has_policy && self.secret_key()?.is_none() {
27011×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2702408×
        }
2703408×
        let remote_tags: BTreeSet<String> = resp
2704408×
            .tags
2705408×
            .iter()
2706408×
            .chain(&resp.withdrawn)
2707408×
            .map(|t| t.name.clone())
2708408×
            .collect();
2709408×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2710408×
            .tag_refs()?
2711408×
            .into_iter()
2712408×
            .filter(|t| !remote_tags.contains(&t.name))
2713408×
            .collect();
2714
        // Tags withdrawn here that the remote still has, at the same state
2715
        // (oxygenhub#301).
2716408×
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2717408×
            .withdrawn_refs()?
2718408×
            .into_iter()
2719408×
            .filter(|w| {
27202×
                resp.tags
27212×
                    .iter()
27222×
                    .any(|t| t.name == w.name && t.state == w.state)
27232×
            })
2724408×
            .collect();
2725408×
        let refs = resp.refs;
2726408×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2727408×
        let (remote_state, remote_heads, last_serial) =
2728422×
            match refs.iter().find(|r| r.name == bookmark) {
2729379×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
273029×
                None => (empty, vec![], None),
2731
            };
2732408×
        let new_state = self
2733408×
            .store
2734408×
            .put_state(&StateObject::new(local_heads.clone()))?;
2735
        // A push that carries a policy re-attests the bookmark even when its
2736
        // state is unchanged, so the current attestation is always by a key
2737
        // the current policy authorizes (a revoked key's attestation would
2738
        // otherwise be refused by every later fetch).
2739408×
        if new_state == remote_state
274036×
            && policy_to_send.is_none()
274119×
            && tags_to_send.is_empty()
274210×
            && withdrawals_to_send.is_empty()
2743
        {
27449×
            return Ok(vec![RefResult {
27459×
                name: bookmark,
27469×
                ok: true,
27479×
                reason: "already up to date".into(),
27489×
            }]);
2749399×
        }
2750
        // A shallow repository knows the changes on its boundary without
2751
        // holding them: a depth-0 clone's are the heads it cloned (#137).
2752399×
        let boundary = self.boundary();
2753406×
        for h in &remote_heads {
2754406×
            if !self.store.has(h) && !boundary.contains(h) {
275568×
                return fail(format!(
2756
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
275768×
                    h.short(12)
2758
                ));
2759338×
            }
2760
        }
2761331×
        if !force {
2762331×
            let closure = self.closure_in_store(&local_heads)?;
2763331×
            if let Some(h) = remote_heads
2764331×
                .iter()
2765331×
                .find(|h| !closure.contains(h) && !boundary.contains(h))
2766
            {
27670×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2768331×
            }
27690×
        }
2770331×
        let to_send = self.negotiate(&self.remote_holds(&refs, &remote_heads), &local_heads)?;
2771331×
        let key = self.secret_key()?.map(|(k, _)| k);
2772331×
        if let Some(key) = key {
2773
            // Seal this author's changes that carry no valid authenticator,
2774
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2775
            // are stored, so each batch's bundle carries those it needs.
2776112×
            let mut unsigned = Vec::new();
2777112×
            for h in &to_send {
277882×
                let c = self.store.get_change_meta(h)?;
277982×
                if self.seals_for_author(&c.author, &key)
278080×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
278153×
                {
278253×
                    unsigned.push(*h);
278353×
                }
2784
            }
2785112×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
278650×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2787
            }
2788219×
        }
2789
        // A long history goes in batches, in dependency order, so neither
2790
        // side holds it whole and no request passes the remote's limit:
2791
        // all but the last carry objects alone; the last moves the bookmark
2792
        // (oxygen#95).
2793330×
        let batches = self.push_batches(&to_send)?;
2794330×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2795330×
        for (i, batch) in earlier.iter().enumerate() {
27965×
            progress(&format!(
27975×
                "part {} of {}: {} changes",
27985×
                i + 1,
27995×
                batches.len(),
28005×
                batch.len()
28015×
            ));
28025×
            let bundle = self.send_objects_ahead(
28035×
                remote.as_ref(),
28045×
                remote_name,
28055×
                self.bundle_for(batch)?,
28065×
                &mut *progress,
28070×
            )?;
28085×
            let results = remote.push(bundle, vec![], None, vec![])?;
28095×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
28105×
                Some(r) if r.ok => {}
28110×
                Some(r) => {
28120×
                    return fail(format!(
2813
                        "{remote_name} refused part {} of the push: {}",
28140×
                        i + 1,
2815
                        r.reason
2816
                    ))
2817
                }
2818
                None => {
28190×
                    return fail(format!(
2820
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2821
                    ))
2822
                }
2823
            }
2824
        }
2825330×
        if batches.len() > 1 {
28261×
            progress(&format!(
28271×
                "part {} of {}: {} changes",
28281×
                batches.len(),
28291×
                batches.len(),
28301×
                last.len()
28311×
            ));
2832329×
        }
2833330×
        let mut bundle = self.send_objects_ahead(
2834330×
            remote.as_ref(),
2835330×
            remote_name,
2836330×
            self.bundle_for(last)?,
2837330×
            &mut *progress,
28380×
        )?;
2839330×
        bundle.objects.push((
2840330×
            ObjectType::State,
2841330×
            StateObject::new(local_heads.clone()).encode(),
2842330×
        ));
2843330×
        let attestation = match key {
2844111×
            Some(_) => Some(self.sign_attest(&Attest {
2845111×
                repo: self.id()?,
2846111×
                hlc: Hlc::now(),
2847111×
                body: AttestBody::Ref {
2848111×
                    name: bookmark.clone(),
2849111×
                    old_state: remote_state,
2850111×
                    new_state,
2851111×
                    serial: next_serial(last_serial),
2852111×
                },
28531×
            })?),
2854219×
            None => None,
2855
        };
2856
        // Whoever signed the move, and whom a delegate acts for, travel with
2857
        // it: a receiver that has never seen a change by this delegate could
2858
        // not otherwise check its signature (oxygenhub#129).
2859329×
        if attestation.is_some() {
2860220×
            for k in [self.signing_key(), self.config.author_key]
2861110×
                .into_iter()
2862110×
                .flatten()
2863
            {
2864220×
                if let Ok(id) = self.identity(&k) {
2865220×
                    let body = id.encode();
2866220×
                    if !bundle
2867220×
                        .objects
2868220×
                        .iter()
2869267×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
287038×
                    {
287138×
                        bundle.objects.push((ObjectType::Identity, body));
2872182×
                    }
28730×
                }
2874
            }
2875
            // A short-lived signing key's certificate goes with it (§14.7).
2876110×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2877110×
            self.attach_certificates_for(&mut bundle, &signers)?;
2878219×
        }
2879329×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2880110×
            AttestBody::Ref { serial, .. } => Some(serial),
28810×
            _ => None,
2882110×
        });
2883329×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2884
        // Tag states must be present on the remote: bundle their changes too.
2885329×
        for t in &tags_to_send {
288616×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
288716×
            let extra: Vec<ChangeHash> =
288816×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
288916×
            if !extra.is_empty() {
28900×
                let more = self.bundle_for(&extra)?;
28910×
                bundle.changes.extend(more.changes);
28920×
                bundle.hashes.extend(more.hashes);
28930×
                bundle.attests.extend(more.attests);
28940×
                bundle.objects.extend(more.objects);
289516×
            }
289616×
            bundle.objects.push((
289716×
                ObjectType::State,
289816×
                StateObject::new(t.heads.clone()).encode(),
289916×
            ));
2900
        }
2901
        // A tag's signer travels with it, as the bookmark's does: a tag made
2902
        // by `oxy tag create` under a short-lived key was signed by a key the
2903
        // receiver has never seen, so its identity and certificate go too.
2904329×
        let tag_signers: Vec<KeyId> = tags_to_send
2905329×
            .iter()
2906329×
            .chain(&withdrawals_to_send)
2907329×
            .filter_map(|t| t.attestation.as_ref())
2908329×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2909329×
            .collect();
2910329×
        for k in &tag_signers {
291116×
            if let Ok(id) = self.identity(k) {
291216×
                let body = id.encode();
291316×
                if !bundle
291416×
                    .objects
291516×
                    .iter()
291630×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
29172×
                {
29182×
                    bundle.objects.push((ObjectType::Identity, body));
291914×
                }
29200×
            }
2921
        }
2922329×
        if !tag_signers.is_empty() {
292315×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2924314×
        }
2925329×
        if let Some(l) = &policy_to_send {
292634×
            let remote_serial = resp_policy_serial;
292734×
            bundle.policies = self
292834×
                .policy_history()?
292934×
                .into_iter()
293066×
                .filter(|sp| {
293166×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
293236×
                        && sp.policy.serial < l.policy.serial
293366×
                })
293434×
                .collect();
2935295×
        }
2936329×
        let results = remote.push(
2937329×
            bundle,
2938329×
            vec![RefUpdate {
2939329×
                name: bookmark.clone(),
2940329×
                old_state: remote_state,
2941329×
                new_state,
2942329×
                force,
2943329×
                attestation,
2944329×
            }],
2945329×
            policy_to_send,
2946329×
            tags_to_send
2947329×
                .into_iter()
2948329×
                .chain(withdrawals_to_send)
2949329×
                .collect(),
29508×
        )?;
295134×
        if let (Some(serial), true) = (
2952321×
            sent_serial,
2953335×
            results.iter().any(|r| r.ok && r.name == "policy"),
2954
        ) {
295534×
            self.record_policy_serial(remote_name, serial)?;
2956287×
        }
2957358×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2958296×
            let mut view = op.view.clone();
2959296×
            view.remotes
2960296×
                .entry(remote_name.to_string())
2961296×
                .or_default()
2962296×
                .insert(bookmark.clone(), new_state);
2963296×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2964293×
            if let Some(s) = serial {
296586×
                self.record_serial(remote_name, &bookmark, s)?;
2966207×
            }
296725×
        }
2968316×
        Ok(results)
2969414×
    }
2970
2971
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2972
    /// bookmark set to the remote's, working copy checked out.
2973267×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2974267×
        Self::clone_with(url, dest, None, &[])
2975267×
    }
2976
2977
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2978
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2979
    /// unless a size is given, so out-of-scope binaries are never fetched).
2980270×
    pub fn clone_with(
2981270×
        url: &str,
2982270×
        dest: &Path,
2983270×
        max_blob: Option<u64>,
2984270×
        sparse: &[String],
2985270×
    ) -> Result<Repo> {
2986270×
        Self::clone_full(url, dest, max_blob, sparse, None)
2987270×
    }
2988
2989
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2990
    /// changes within `depth` steps of them; the rest is the boundary.
29913×
    pub fn clone_shallow(
29923×
        url: &str,
29933×
        dest: &Path,
29943×
        depth: u32,
29953×
        max_blob: Option<u64>,
29963×
        sparse: &[String],
29973×
    ) -> Result<Repo> {
29983×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
29993×
    }
3000
3001273×
    fn clone_full(
3002273×
        url: &str,
3003273×
        dest: &Path,
3004273×
        max_blob: Option<u64>,
3005273×
        sparse: &[String],
3006273×
        depth: Option<u32>,
3007273×
    ) -> Result<Repo> {
3008273×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
3009273×
    }
3010
3011
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
3012
    /// `depth`), also returning the bookmarks the fetch left out because
3013
    /// their attestation could not be verified ([`FetchReport::skipped`]),
3014
    /// for the caller to warn about. The bookmark checked out is never one
3015
    /// of them: that fails the clone.
3016279×
    pub fn clone_reporting(
3017279×
        url: &str,
3018279×
        dest: &Path,
3019279×
        max_blob: Option<u64>,
3020279×
        sparse: &[String],
3021279×
        depth: Option<u32>,
3022279×
    ) -> Result<(Repo, Vec<(String, String)>)> {
3023279×
        let options = crate::credentials::Credentials::user().options_for(url);
3024279×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
3025279×
    }
3026
3027
    /// Clone a subrepo with the credentials the parent would use for its
3028
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
3029
    /// subrepo: it finds the same ones again through its parent.
303013×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
303113×
        let options = self.credentials_for(url);
303213×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
303313×
    }
3034
3035
    /// The name of a remote of this repository on the same hub (scheme,
3036
    /// host and port) as `url`.
303729×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
303833×
        let origin = |u: &str| -> Option<String> {
303933×
            let (scheme, rest) = u.split_once("://")?;
30408×
            if !matches!(scheme, "http" | "https") {
30410×
                return None;
30428×
            }
30438×
            let host = rest.split('/').next()?;
30448×
            Some(format!(
30458×
                "{}://{}",
30468×
                scheme.to_ascii_lowercase(),
30478×
                host.to_ascii_lowercase()
30488×
            ))
304933×
        };
305029×
        let want = origin(url)?;
30514×
        self.config
30524×
            .remotes
30534×
            .iter()
30544×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
30554×
            .map(|(name, _)| name.clone())
305629×
    }
3057
3058
    /// The token and CA to reach `url` with: those of a remote of this
3059
    /// repository on the same hub (scheme, host and port), else the
3060
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
3061
    /// and enclosing checkouts', as a clone would use them.
306229×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
306329×
        match self.remote_on_same_hub(url) {
30641×
            Some(name) => RemoteOptions {
30651×
                repo_id: None,
30661×
                cache_dir: None,
30671×
                ..self.remote_options(&name)
30681×
            },
3069
            None => {
307028×
                let mut options = RemoteOptions::default();
307128×
                self.fill_credentials(url, &mut options);
307228×
                options
3073
            }
3074
        }
307529×
    }
3076
3077292×
    fn clone_using(
3078292×
        url: &str,
3079292×
        dest: &Path,
3080292×
        max_blob: Option<u64>,
3081292×
        sparse: &[String],
3082292×
        depth: Option<u32>,
3083292×
        options: &RemoteOptions,
3084292×
    ) -> Result<(Repo, Vec<(String, String)>)> {
3085292×
        let remote = open_remote(url, options)?;
3086292×
        let id = remote.repo_id()?;
3087288×
        if id == crate::protocol::UNBOUND_ID {
30882×
            return fail(format!(
3089
                "{url} is empty and unbound: push a repository to it first"
3090
            ));
3091286×
        }
3092286×
        let mut repo = Repo::init_with_id(dest, id)?;
3093286×
        repo.config
3094286×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
3095286×
        if let Some(m) = max_blob {
30963×
            repo.config.set("filter.max-blob", &m.to_string())?;
3097283×
        } else if !sparse.is_empty() {
30981×
            repo.config.set("filter.max-blob", "0")?;
3099282×
        }
3100286×
        if !sparse.is_empty() {
31011×
            repo.config.set("filter.paths", &sparse.join(","))?;
3102285×
        }
3103286×
        repo.save_config()?;
3104286×
        let skipped = if let Some(depth) = depth {
31053×
            repo.fetch_shallow("origin", depth)?;
31063×
            Vec::new()
3107
        } else {
3108283×
            repo.fetch("origin")?.skipped
3109
        };
3110284×
        let (op_ref, op) = repo.head_op()?;
3111
        // The remote's default bookmark, else ours (main), else its only
3112
        // one; a bookmark the fetch skipped counts, so the clone fails
3113
        // rather than check out another (oxygenhub#266).
3114284×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
3115284×
        for (name, _) in &skipped {
31163×
            theirs.insert(name.clone(), ObjectRef::ZERO);
31173×
        }
3118
        // Asked of the remote as now configured, so a store-backed one
3119
        // answers from the mirror the fetch just filled.
3120284×
        let advertised = repo
3121284×
            .open_named_remote("origin")
3122284×
            .ok()
3123284×
            .and_then(|r| r.refs().ok())
3124284×
            .and_then(|r| r.default_bookmark);
3125284×
        let bookmark = advertised
3126284×
            .filter(|b| theirs.contains_key(b))
3127284×
            .or_else(|| {
31287×
                theirs
31297×
                    .contains_key(&repo.config.bookmark)
31307×
                    .then(|| repo.config.bookmark.clone())
31317×
            })
3132284×
            .or_else(|| {
31330×
                (theirs.len() == 1)
31340×
                    .then(|| theirs.keys().next().cloned())
31350×
                    .flatten()
31360×
            })
3137284×
            .unwrap_or_else(|| repo.config.bookmark.clone());
3138284×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
31390×
            return fail(format!("cannot check out {bookmark}: {why}"));
3140284×
        }
3141284×
        let initial = repo.config.bookmark.clone();
3142284×
        if bookmark != repo.config.bookmark {
31431×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
31441×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
31451×
            repo.config.bookmark = bookmark.clone();
3146283×
        }
3147284×
        if let Some(state) = theirs.get(&bookmark).copied() {
3148284×
            let heads = repo.store.get_state(&state)?.heads;
3149284×
            let mut view = op.view.clone();
3150
            // The empty bookmark `init` made goes when another is checked out.
3151284×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
31521×
                view.bookmarks.remove(&initial);
3153283×
            }
3154284×
            view.bookmarks.insert(bookmark, state);
3155284×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
3156284×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
31570×
        }
3158284×
        Ok((repo, skipped))
3159292×
    }
3160
}
3161
3162
/// The serial of a reference's next attestation: one more than the last the
3163
/// remote reports, or, for a bookmark the remote does not have, the clock in
3164
/// milliseconds, so a bookmark created again after a deletion goes past the
3165
/// deletion's serial the remote keeps.
3166111×
fn next_serial(last: Option<u64>) -> u64 {
3167111×
    match last {
316869×
        Some(l) => l + 1,
316942×
        None => Hlc::now().wall_ms.max(1),
3170
    }
3171111×
}