OXYGENHUB

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

1727 of 1937 lines run, 251 of 362 functions · run #339 on proposal/124 · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
    /// What checking the host's transparency log found short of a fork
34
    /// (spec §14.8): attestations not logged yet, a log that could not be
35
    /// read. A fork fails the fetch instead.
36
    pub log_notes: Vec<String>,
37
}
38
39
#[derive(Debug, Clone, PartialEq, Eq)]
40
pub struct PullReport {
41
    /// The current bookmark's heads after the pull.
42
    pub heads: Vec<ChangeHash>,
43
    /// Whether the current bookmark changed.
44
    pub changed: bool,
45
    pub checked_out: bool,
46
    /// Other bookmarks the pull moved: each local bookmark tracks the
47
    /// remote's of the same name.
48
    pub others: Vec<String>,
49
}
50
51
/// The result a push of objects alone reports (a batch of a long history):
52
/// not a reference.
53
pub const OBJECTS_RESULT: &str = "objects";
54
55
impl Repo {
56
    // ------------------------------------------------------------ serving (spec §16)
57
581324×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
591324×
        self.oxy.join("attest").join(name_file(bookmark))
601324×
    }
61
62
    /// The latest reference attestation stored for a bookmark.
631240×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
641240×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
65235×
            Ok(h) => {
66235×
                let r = ObjectRef::from_hex(h.trim())
67235×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
68
                Ok(Some((
69235×
                    r,
70
                    SignedAttest {
71235×
                        attest: self.store.get_attest(&r)?,
72235×
                        sigs: self.store.signatures(&r)?,
73
                    },
74
                )))
75
            }
761005×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
770×
            Err(e) => Err(e.into()),
78
        }
791240×
    }
80
8184×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
8284×
        fs::create_dir_all(self.oxy.join("attest"))?;
8384×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8484×
    }
85
861008×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
871008×
        let view = self.view()?;
881008×
        let mut out = Vec::new();
891032×
        for (name, state) in &view.bookmarks {
901032×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
911032×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
92136×
                AttestBody::Ref { serial, .. } => Some(serial),
930×
                _ => None,
94136×
            });
951032×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
961032×
            let accepted = match &attestation {
97125×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
98907×
                None => None,
99
            };
1001032×
            out.push(RemoteRef {
1011032×
                name: name.clone(),
1021032×
                state: *state,
1031032×
                heads: self.store.get_state(state)?.heads,
1041032×
                attestation,
1051032×
                last_serial,
1061032×
                accepted,
1071032×
                logged: None,
108
            });
109
        }
1101008×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1111008×
        let history = self
1121008×
            .policy_history()?
1131008×
            .into_iter()
1141008×
            .filter(|sp| {
115126×
                policy
116126×
                    .as_ref()
117126×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
118126×
            })
1191008×
            .collect();
120
        Ok(RefsResponse {
1211008×
            refs: out,
1221008×
            policy,
1231008×
            tags: self.tag_refs()?,
1241008×
            history,
1251008×
            default_bookmark: Some(self.config.bookmark.clone()),
1261008×
            log: None,
127
        })
1281008×
    }
129
130
    /// Every change reachable from `heads` that is in the store.
1311348×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1321348×
        let mut seen = BTreeSet::new();
1331348×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1344628×
        while let Some(h) = stack.pop() {
1353280×
            if seen.contains(&h) || !self.store.has(&h) {
136928×
                continue;
1372352×
            }
1382352×
            seen.insert(h);
1392352×
            stack.extend(self.store.get_change_meta(&h)?.deps);
140
        }
1411348×
        Ok(seen)
1421348×
    }
143
144
    /// The changes within `depth` dependency steps of `heads` (spec §17),
145
    /// nearest first; depth 1 is the heads themselves.
1463×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1473×
        let mut out = Vec::new();
1483×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1493×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1503×
        for _ in 0..depth.max(1) {
1518×
            let mut next = Vec::new();
15212×
            for h in layer {
15312×
                if !seen.insert(h) || !self.store.has(&h) {
1542×
                    continue;
15510×
                }
15610×
                let c = self.store.get_change(&h)?;
15710×
                next.extend(c.deps.iter().copied());
15810×
                out.push(h);
159
            }
1608×
            if next.is_empty() {
1611×
                break;
1627×
            }
1637×
            layer = next;
164
        }
1653×
        out.reverse();
1663×
        Ok(out)
1673×
    }
168
1691945×
    fn shallow_path(&self) -> PathBuf {
1701945×
        self.oxy.join("shallow")
1711945×
    }
172
173
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1741942×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1751942×
        fs::read_to_string(self.shallow_path())
1761942×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1771942×
            .unwrap_or_default()
1781942×
    }
179
180189×
    pub fn is_shallow(&self) -> bool {
181189×
        !self.boundary().is_empty()
182189×
    }
183
1843×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1853×
        if boundary.is_empty() {
1861×
            let _ = fs::remove_file(self.shallow_path());
1871×
            return Ok(());
1882×
        }
1892×
        let text: String = boundary
1902×
            .iter()
1912×
            .map(|h| format!("{}\n", h.to_hex()))
1922×
            .collect();
1932×
        write_atomic(&self.shallow_path(), text.as_bytes())
1943×
    }
195
196
    /// Recompute the boundary from what is stored: every dependency of a
197
    /// stored change that is not itself stored.
1983×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1993×
        let mut boundary = self.boundary();
2003×
        boundary.retain(|h| !self.store.has(h));
20110×
        for h in imported {
20213×
            for d in self.store.get_change_meta(h)?.deps {
20313×
                if !self.store.has(&d) {
2042×
                    boundary.insert(d);
20511×
                }
206
            }
207
        }
2083×
        self.write_boundary(&boundary)
2093×
    }
210
211
    /// Fetch `depth` more levels of history below the shallow boundary.
2122×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2132×
        let boundary = self.boundary();
2142×
        if boundary.is_empty() {
2150×
            return Ok(0);
2162×
        }
2172×
        let remote = self.open_named_remote(remote_name)?;
2182×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2192×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2202×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2212×
        if self.config.max_blob.is_some() {
2220×
            self.register_missing_blobs(&imported, remote_name)?;
2232×
        }
2242×
        self.refresh_boundary(&imported)?;
2252×
        Ok(imported.len())
2262×
    }
227
228
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
229769×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
230769×
        let have = self.closure_in_store(have)?;
231
        // In a shallow repository the walk stops at the boundary, whose
232
        // changes the remote is assumed to hold.
233769×
        let boundary = self.boundary();
234769×
        let mut out = Vec::new();
235769×
        let mut done: BTreeSet<ChangeHash> = have.clone();
236769×
        done.extend(boundary.iter().copied());
237
        // Iterative post-order DFS.
2381223×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2393214×
        while let Some((h, expanded)) = stack.pop() {
2402445×
            if done.contains(&h) {
241401×
                continue;
2422044×
            }
2432044×
            if !self.store.has(&h) {
2440×
                return fail(format!("change {} is not in this repository", h.short(12)));
2452044×
            }
2462044×
            if expanded {
2471022×
                done.insert(h);
2481022×
                out.push(h);
2491022×
                continue;
2501022×
            }
2511022×
            stack.push((h, true));
2521022×
            for d in self.store.get_change_meta(&h)?.deps {
253685×
                if !done.contains(&d) {
254200×
                    stack.push((d, false));
255485×
                }
256
            }
257
        }
258769×
        Ok(out)
259769×
    }
260
261
    /// Bundle changes (in the given dependency order) with their signatures,
262
    /// seals, identities, blobs, chunks.
263305×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
264305×
        self.bundle_for_filtered(changes, None)
265305×
    }
266
267
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2684×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2694×
        let mut out = Vec::new();
2704×
        for r in refs {
2714×
            let (ty, body) = match self.store.get(r) {
2724×
                Ok(x) => x,
2730×
                Err(StoreError::NotFound(_)) => continue,
2740×
                Err(e) => return Err(e.into()),
275
            };
2764×
            if ty == ObjectType::Blob {
2775×
                for c in Blob::decode(&body)?.chunks {
2785×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2795×
                        out.push((cty, cb));
2805×
                    }
281
                }
2820×
            }
2834×
            out.push((ty, body));
284
        }
2854×
        Ok(out)
2864×
    }
287
288
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
289
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
290351×
    pub fn bundle_for_filtered(
291351×
        &self,
292351×
        changes: &[ChangeHash],
293351×
        max_blob: Option<u64>,
294351×
    ) -> Result<Bundle> {
295351×
        self.bundle_of(changes, max_blob, false)
296351×
    }
297
298
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
299
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
300
    /// with their text blobs and chunks among the objects, so neither side
301
    /// decodes or encodes their text.
302323×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
303323×
        self.bundle_of(changes, max_blob, true)
304323×
    }
305
306674×
    fn bundle_of(
307674×
        &self,
308674×
        changes: &[ChangeHash],
309674×
        max_blob: Option<u64>,
310674×
        raw: bool,
311674×
    ) -> Result<Bundle> {
312674×
        let mut bundle = Bundle::default();
313674×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
314674×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3151054×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3161054×
            if !r.is_zero() && self.store.has(r) {
317219×
                objects.insert(*r);
318835×
            }
3191054×
        };
320947×
        for h in changes {
321
            // Raw: the stored bytes, and a skeleton for the rest.
322947×
            let (c, encoded) = if raw {
323499×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
324499×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3254930×
                for t in texts {
3264930×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3273×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3283×
                        objects.insert(r);
3293×
                        objects.extend(blob.chunks);
3304927×
                    }
331
                }
332499×
                (skel, Some(bytes))
333
            } else {
334448×
                (self.store.get_change(h)?, None)
335
            };
336947×
            let sigs = self.store.signatures(h)?;
337947×
            add_object(&c.author, &mut objects);
338947×
            for s in &sigs {
33922×
                add_object(&s.key, &mut objects);
34022×
            }
3415898×
            for e in &c.edits {
3425898×
                if let Edit::Replace { old, new, .. } = e {
34314×
                    for b in [old, new].into_iter().flatten() {
34414×
                        if self.store.has(b) {
34514×
                            if let Ok(blob) =
34614×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
347
                            {
34814×
                                if max_blob.is_some_and(|m| blob.length > m) {
3494×
                                    continue;
35010×
                                }
35110×
                                objects.insert(*b);
35210×
                                objects.extend(blob.chunks.iter().copied());
3530×
                            }
3540×
                        }
355
                    }
3565886×
                }
357
            }
358947×
            for s in self.store.seals_for(h)? {
35990×
                seals.insert(s);
36090×
            }
361947×
            match encoded {
362499×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
363448×
                None => {
364448×
                    bundle.changes.push((c, sigs));
365448×
                    bundle.hashes.push(*h);
366448×
                }
367
            }
368
        }
369674×
        for r in seals {
37085×
            let attest = self.store.get_attest(&r)?;
37185×
            let sigs = self.store.signatures(&r)?;
37285×
            for s in &sigs {
37385×
                add_object(&s.key, &mut objects);
37485×
            }
37585×
            bundle.attests.push(SignedAttest { attest, sigs });
376
        }
377674×
        for r in objects {
378134×
            let (ty, body) = self.store.get(&r)?;
379134×
            bundle.objects.push((ty, body));
380
        }
381674×
        self.attach_certificates(&mut bundle)?;
382674×
        Ok(bundle)
383674×
    }
384
385
    /// Add the certificates of short-lived keys that signed what `bundle`
386
    /// carries, and their issuers' identities, so a receiver can tell who
387
    /// they stand for (spec §14.7). `also` names more signers (a reference
388
    /// attestation sent beside the bundle).
389759×
    pub(crate) fn attach_certificates_for(
390759×
        &self,
391759×
        bundle: &mut Bundle,
392759×
        also: &[KeyId],
393759×
    ) -> Result<()> {
394759×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
395759×
        keys.extend(
396759×
            bundle
397759×
                .changes
398759×
                .iter()
399759×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
400
        );
401759×
        keys.extend(
402759×
            bundle
403759×
                .raw_changes
404759×
                .iter()
405759×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
406
        );
407759×
        keys.extend(
408759×
            bundle
409759×
                .attests
410759×
                .iter()
411759×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
412
        );
413759×
        for k in keys {
414193×
            let Some(r) = self.store.certificate_of(&k)? else {
415172×
                continue;
416
            };
41721×
            let cert = self.store.get_certificate(&r)?;
41821×
            if bundle
41921×
                .certificates
42021×
                .iter()
42121×
                .any(|c| c.cert.hash() == cert.cert.hash())
422
            {
4237×
                continue;
42414×
            }
42528×
            for id in [&k, &cert.cert.issuer] {
42628×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
42728×
                    if !bundle
42828×
                        .objects
42928×
                        .iter()
43043×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
43114×
                    {
43214×
                        bundle.objects.push((ObjectType::Identity, body));
43314×
                    }
4340×
                }
435
            }
43614×
            bundle.certificates.push(cert);
437
        }
438759×
        Ok(())
439759×
    }
440
441674×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
442674×
        self.attach_certificates_for(bundle, &[])
443674×
    }
444
445
    /// Keep the certificates a bundle brings once each verifies with the
446
    /// identity of the issuer it names; one that does not refuses the bundle.
447719×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
448719×
        for c in certs {
44914×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4500×
                RepoError::Msg(format!(
4510×
                    "a certificate names issuer {}, whose identity did not come with it",
4520×
                    c.cert.issuer.short(12)
4530×
                ))
4540×
            })?;
45514×
            c.verify(&issuer)
45614×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
45714×
            self.store.put_identity(&c.cert.key)?;
45814×
            self.store.put_certificate(c)?;
459
        }
460719×
        Ok(())
461719×
    }
462
463
    /// A signer authorized for `reference` by what an issuer certified it
464
    /// as (spec §14.7): a short-lived key with a kept certificate that
465
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
466
    /// signer did not choose) and names a subject the policy grants.
46718×
    pub(crate) fn certified_authorized(
46818×
        &self,
46918×
        p: &crate::policy::Policy,
47018×
        signer: &KeyId,
47118×
        reference: &str,
47218×
        scope: Scope,
47318×
        at_ms: u64,
47418×
    ) -> bool {
47518×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
4765×
            return false;
477
        };
47813×
        let Ok(c) = self.store.get_certificate(&r) else {
4790×
            return false;
480
        };
48113×
        let Some(issuer) = p
48213×
            .identity(&c.cert.issuer)
48313×
            .cloned()
48413×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
485
        else {
4860×
            return false;
487
        };
48813×
        c.verify(&issuer).is_ok()
48913×
            && c.cert.key_id() == *signer
49013×
            && c.cert.covers(scope, at_ms)
49112×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
49218×
    }
493
494
    /// Store a bundle's contents. With `strict`, every change must
495
    /// authenticate (signature or seal by its author or a delegate).
496716×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
497716×
        self.import_bundle_inner(bundle, strict, false)
498716×
    }
499
500
    /// Like `import_bundle`, accepting changes whose dependencies are absent
501
    /// (they join the shallow boundary).
5023×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5033×
        self.import_bundle_inner(bundle, strict, true)
5043×
    }
505
506719×
    fn import_bundle_inner(
507719×
        &self,
508719×
        bundle: &Bundle,
509719×
        strict: bool,
510719×
        shallow: bool,
511719×
    ) -> Result<Vec<ChangeHash>> {
512719×
        let batch = self.store.begin_batch()?;
513719×
        let result = self.import_bundle_batched(bundle, strict, shallow);
514719×
        batch.finish()?;
515717×
        result
516719×
    }
517
518719×
    fn import_bundle_batched(
519719×
        &self,
520719×
        bundle: &Bundle,
521719×
        strict: bool,
522719×
        shallow: bool,
523719×
    ) -> Result<Vec<ChangeHash>> {
524719×
        for (ty, _) in &bundle.objects {
5250×
            if !matches!(
526527×
                ty,
527
                ObjectType::Chunk
528
                    | ObjectType::Blob
529
                    | ObjectType::Identity
530
                    | ObjectType::State
531
                    | ObjectType::Checkpoint
532
            ) {
5330×
                return fail(format!("bundle may not carry {} objects", ty.name()));
534527×
            }
535
        }
536
        // All at once: in a large batch they are compressed on every core.
537719×
        let objects: Vec<(ObjectType, &[u8])> = bundle
538719×
            .objects
539719×
            .iter()
540719×
            .map(|(ty, body)| (*ty, body.as_slice()))
541719×
            .collect();
542719×
        self.store.put_many(&objects)?;
543719×
        self.adopt_certificates(&bundle.certificates)?;
544719×
        for sa in &bundle.attests {
54588×
            let r = self.store.put_attest(&sa.attest)?;
54688×
            for sig in &sa.sigs {
54788×
                self.store.put_signature(&r, sig)?;
548
            }
54988×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
55093×
                for h in hashes {
55193×
                    self.store.index_seal(h, &r)?;
552
                }
5530×
            }
554
        }
555
        // Each change's hash: from the bundle when its maker knew it, else
556
        // worked out once (for a change adding a whole tree, hashing is
557
        // chunking all its text).
558719×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
559710×
            bundle.hashes.clone()
560
        } else {
5619×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
562
        };
563719×
        let raw_hashes: Vec<ChangeHash> = bundle
564719×
            .raw_changes
565719×
            .iter()
566719×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
567719×
            .collect();
568719×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
569719×
        let boundary = self.boundary();
570719×
        let mut imported = Vec::new();
571
        // Changes as stored: checked, then stored as they are, their text
572
        // blobs having come with the objects.
573719×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
574500×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
575500×
            for d in &skel.deps {
576356×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
577
                {
5780×
                    return fail(format!(
579
                        "change {} depends on {}, which is neither stored nor in the bundle",
5800×
                        h.short(12),
5810×
                        d.short(12)
582
                    ));
583356×
                }
584
            }
5854931×
            for t in texts {
5864931×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
5874×
                    if !self.store.has(&r) {
5881×
                        return fail(format!(
589
                            "change {} came without its text blob {}",
5901×
                            h.short(12),
5911×
                            r.short(12)
592
                        ));
5933×
                    }
5944927×
                }
595
            }
596499×
            self.store.put(ObjectType::Change, bytes)?;
597499×
            for sig in sigs {
5984×
                self.store.put_signature(&h, sig)?;
599
            }
600499×
            imported.push(h);
601
        }
602718×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
603476×
            for d in &c.deps {
604283×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
605
                {
6063×
                    return fail(format!(
607
                        "change {} depends on {}, which is neither stored nor in the bundle",
6083×
                        h.short(12),
6093×
                        d.short(12)
610
                    ));
611280×
                }
612
            }
613473×
            let stored = self.store.put_change(c)?;
614473×
            if stored != h {
6150×
                return fail(format!(
616
                    "change {} is not the change the bundle names",
6170×
                    h.short(12)
618
                ));
619473×
            }
620473×
            for sig in sigs {
62127×
                self.store.put_signature(&h, sig)?;
622
            }
623473×
            imported.push(h);
624
        }
625715×
        if strict {
62643×
            for h in &imported {
62730×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6284×
                    return fail(format!(
629
                        "change {} is not authenticated by its author",
6304×
                        h.short(12)
631
                    ));
63226×
                }
633
            }
634672×
        }
635711×
        Ok(imported)
636719×
    }
637
638
    /// Verify a reference attestation against an update it claims to describe.
639
    /// `allow_equal` lets a client re-read the attestation it already has; a
640
    /// server receiving a push requires a strictly greater serial.
641
    /// A reference attestation signed by a delegate of an identity the
642
    /// rule lists is authorized as that identity (spec §14.5): the identity
643
    /// named the delegate with the `refs` scope, still in force at `at_ms`
644
    /// (the attestation's wall time), and the policy names the identity.
645
    /// Revoked keys authorize nothing either way.
64622×
    pub(crate) fn delegate_authorized(
64722×
        &self,
64822×
        p: &crate::policy::Policy,
64922×
        signer: &KeyId,
65022×
        reference: &str,
65122×
        at_ms: u64,
65222×
    ) -> bool {
65322×
        if p.is_revoked(signer) {
6541×
            return false;
65521×
        }
65621×
        let Some(rule) = p.rule_for(reference) else {
6570×
            return false;
658
        };
65922×
        rule.keys.iter().any(|k| {
66022×
            !p.is_revoked(k)
66122×
                && p.identity(k)
66222×
                    .cloned()
66322×
                    .or_else(|| self.store.get_identity(k).ok())
66422×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
66522×
        })
66622×
    }
667
668
    /// A lasting attestation (a tag) signed by a key the policy has since
669
    /// rotated away from (spec §14.2) is authorized as the key that
670
    /// succeeded it: a key the rule lists reaches the signer through
671
    /// `previous` links, and the attestation is dated (`at_ms`) before the
672
    /// signer's successor was made, so a superseded key makes nothing new.
673
    /// Revoked keys authorize nothing.
6746×
    pub(crate) fn predecessor_authorized(
6756×
        &self,
6766×
        p: &crate::policy::Policy,
6776×
        signer: &KeyId,
6786×
        reference: &str,
6796×
        at_ms: u64,
6806×
    ) -> bool {
6816×
        if p.is_revoked(signer) {
6820×
            return false;
6836×
        }
6846×
        let Some(rule) = p.rule_for(reference) else {
6850×
            return false;
686
        };
6877×
        let identity = |k: &KeyId| {
6887×
            p.identity(k)
6897×
                .cloned()
6907×
                .or_else(|| self.store.get_identity(k).ok())
6917×
        };
6926×
        rule.keys.iter().any(|k| {
6936×
            if p.is_revoked(k) {
6940×
                return false;
6956×
            }
6966×
            let mut cur = identity(k);
6976×
            for _ in 0..32 {
6987×
                let Some(id) = cur else {
6990×
                    return false;
700
                };
7011×
                match id.previous {
7026×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7031×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
7041×
                    _ => return false,
705
                }
706
            }
7070×
            false
7086×
        })
7096×
    }
710
711114×
    fn check_ref_attest(
712114×
        &self,
713114×
        sa: &SignedAttest,
714114×
        name: &str,
715114×
        old_state: &ObjectRef,
716114×
        new_state: &ObjectRef,
717114×
        last_serial: Option<u64>,
718114×
        allow_equal: bool,
719114×
    ) -> std::result::Result<u64, String> {
720
        let AttestBody::Ref {
721114×
            name: n,
722114×
            old_state: o,
723114×
            new_state: nw,
724114×
            serial,
725114×
        } = &sa.attest.body
726
        else {
7270×
            return Err("attestation is not a ref attestation".into());
728
        };
729114×
        if n != name || o != old_state || nw != new_state {
7301×
            return Err("attestation does not describe this update".into());
731113×
        }
732113×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7330×
            return Err("attestation is for a different repository".into());
734113×
        }
735113×
        if let Some(last) = last_serial {
73668×
            if *serial < last || (*serial == last && !allow_equal) {
7371×
                return Err(format!(
7381×
                    "attestation serial {serial} is not greater than the last seen {last}"
7391×
                ));
74067×
            }
74145×
        }
742112×
        let r = sa.attest.hash();
743112×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
744112×
        let id = self
745112×
            .store
746112×
            .get_identity(&sig.key)
747112×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
748112×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
749112×
        Ok(*serial)
750114×
    }
751
752
    /// Accept a push (spec §16.4). Without a trust policy every repository
753
    /// is unverified, so unsigned changes and unattested updates are accepted;
754
    /// attestations that are present must still be valid. With a policy,
755
    /// every change and update is checked against it. A newer policy in the
756
    /// push is applied first when it is signed by the current roots.
757283×
    pub fn receive_push(
758283×
        &self,
759283×
        bundle: Bundle,
760283×
        updates: Vec<RefUpdate>,
761283×
        policy: Option<SignedPolicy>,
762283×
        tags: Vec<crate::protocol::TagRef>,
763283×
    ) -> Result<Vec<RefResult>> {
764283×
        Ok(self
765283×
            .receive_push_report(bundle, updates, policy, tags)?
766
            .results)
767283×
    }
768
769
    /// `receive_push` with what a host wants to log: each accepted
770
    /// reference's old and new state and heads, and the changes this push
771
    /// stored (hub spec §6.12).
772323×
    pub fn receive_push_report(
773323×
        &self,
774323×
        bundle: Bundle,
775323×
        updates: Vec<RefUpdate>,
776323×
        policy: Option<SignedPolicy>,
777323×
        tags: Vec<crate::protocol::TagRef>,
778323×
    ) -> Result<PushReport> {
779
        // Updates are checked against the head as it is now, not as this
780
        // handle first read it (oxygenhub#249): another push may have
781
        // landed since.
782323×
        self.refresh()?;
783323×
        let mut report = PushReport::default();
784323×
        let results = &mut report.results;
785323×
        if let Some(sp) = policy {
78625×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
78723×
                Ok(()) => {
78823×
                    results.push(RefResult {
78923×
                        name: "policy".into(),
79023×
                        ok: true,
79123×
                        reason: format!("serial {}", sp.policy.serial),
79223×
                    });
79323×
                }
7942×
                Err(e) => {
7952×
                    results.push(RefResult {
7962×
                        name: "policy".into(),
7972×
                        ok: false,
7982×
                        reason: e,
7992×
                    });
8002×
                    for u in updates {
8010×
                        results.push(RefResult {
8020×
                            name: u.name,
8030×
                            ok: false,
8040×
                            reason: "policy update was rejected".into(),
8050×
                        });
8060×
                    }
8072×
                    return Ok(report);
808
                }
809
            }
810298×
        }
811321×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
812
        // A push of objects alone (one batch of a long history, oxygen#95)
813
        // names no reference: its outcome is reported as `objects`.
814321×
        let objects_only = updates.is_empty() && tags.is_empty();
815321×
        match self.import_bundle(&bundle, policy.is_some()) {
816315×
            Ok(imported) => {
817315×
                if objects_only {
8187×
                    results.push(RefResult {
8197×
                        name: OBJECTS_RESULT.into(),
8207×
                        ok: true,
8217×
                        reason: format!("{} changes stored", imported.len()),
8227×
                    });
823308×
                }
824315×
                report.imported = imported;
825
            }
8266×
            Err(e) => {
8276×
                if objects_only {
8280×
                    results.push(RefResult {
8290×
                        name: OBJECTS_RESULT.into(),
8300×
                        ok: false,
8310×
                        reason: e.to_string(),
8320×
                    });
8336×
                }
8346×
                for u in updates {
8356×
                    results.push(RefResult {
8366×
                        name: u.name,
8376×
                        ok: false,
8386×
                        reason: e.to_string(),
8396×
                    });
8406×
                }
8416×
                return Ok(report);
842
            }
843
        }
844315×
        let (op_ref, op) = self.head_op()?;
845315×
        let mut view = op.view.clone();
846315×
        let mut names = Vec::new();
847315×
        for u in updates {
848306×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
849306×
            let (ok, reason) = match outcome {
850280×
                Ok(()) => (true, String::new()),
85126×
                Err(e) => (false, e),
852
            };
853306×
            if ok {
854280×
                names.push(u.name.clone());
855280×
                let heads = self
856280×
                    .store
857280×
                    .get_state(&u.new_state)
858280×
                    .map(|s| s.heads)
859280×
                    .unwrap_or_default();
860280×
                report.updated.push(RefUpdated {
861280×
                    name: u.name.clone(),
862280×
                    old_state: u.old_state,
863280×
                    new_state: u.new_state,
864280×
                    heads,
865280×
                });
86626×
            }
867306×
            results.push(RefResult {
868306×
                name: u.name,
869306×
                ok,
870306×
                reason,
871306×
            });
872
        }
873315×
        for t in &tags {
8748×
            let name = format!("tags/{}", t.name);
8758×
            let new = !view.tags.contains_key(&t.name);
8768×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
877
                Ok(()) => {
878
                    // A tag new here is an update too, so a hub can start
879
                    // its pipeline's tag jobs (oxygenflow#24); one it
880
                    // already had, sent again, is not.
8816×
                    if new {
8826×
                        report.updated.push(RefUpdated {
8836×
                            name: name.clone(),
8846×
                            old_state: ObjectRef::ZERO,
8856×
                            new_state: t.state,
8866×
                            heads: t.heads.clone(),
8876×
                        });
8886×
                    }
8896×
                    names.push(name.clone());
8906×
                    results.push(RefResult {
8916×
                        name,
8926×
                        ok: true,
8936×
                        reason: String::new(),
8946×
                    });
895
                }
8962×
                Err(e) => results.push(RefResult {
8972×
                    name,
8982×
                    ok: false,
8992×
                    reason: e,
9002×
                }),
901
            }
902
        }
903315×
        if !names.is_empty() {
904280×
            self.record_op(
905280×
                &[op_ref],
906280×
                &format!("push received: {}", names.join(" ")),
907280×
                view,
9083×
            )?;
90935×
        }
910312×
        Ok(report)
911323×
    }
912
913
    /// Check an update's attestation against the latest one for its
914
    /// reference and store it as the new latest. Failures say what was
915
    /// being done, for which reference, so a refused push can be diagnosed
916
    /// from its reason alone.
91784×
    fn record_update_attest(
91884×
        &self,
91984×
        u: &RefUpdate,
92084×
        sa: &SignedAttest,
92184×
    ) -> std::result::Result<(), String> {
92284×
        let name = &u.name;
92384×
        let last = self
92484×
            .latest_ref_attest(name)
92584×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
92684×
            .and_then(|(_, a)| match a.attest.body {
92755×
                AttestBody::Ref { serial, .. } => Some(serial),
9280×
                _ => None,
92955×
            });
93084×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
93182×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
93282×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
93381×
        for sig in &sa.sigs {
93481×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
935
        }
93681×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
937
        // Signed by a short-lived key: a host records when it accepted it.
93878×
        let certified = sa
93978×
            .sigs
94078×
            .first()
94178×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
94278×
        if certified {
9432×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
94476×
        }
94578×
        Ok(())
94684×
    }
947
948
    /// Record that this host accepted attestation `r` now, signed with its
949
    /// acceptor key (spec §14.7); nothing without one.
9503×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
9513×
        let Some(acceptor) = &self.acceptor else {
9522×
            return Ok(());
953
        };
9541×
        let (id, sk) = (&acceptor.0, &acceptor.1);
9551×
        let attest = Attest {
9561×
            repo: self.id()?,
9571×
            hlc: Hlc::now(),
9581×
            body: AttestBody::Accepted { attest: *r },
959
        };
9601×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
9611×
        self.store.put_identity(id)?;
9621×
        let a = self.store.put_attest(&attest)?;
9631×
        self.store.put_signature(&a, &sig)?;
9641×
        self.store.index_add_pub("accepted", r, &a)?;
9651×
        Ok(())
9663×
    }
967
968
    /// The host's acceptance of attestation `r`, if one was recorded.
969127×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
970127×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
971117×
            return Ok(None);
972
        };
973
        Ok(Some(SignedAttest {
97410×
            attest: self.store.get_attest(&a)?,
97510×
            sigs: self.store.signatures(&a)?,
976
        }))
977127×
    }
978
979
    /// When a certified signer's attestation `sa` is checked on a fetch: the
980
    /// host's acceptance time, if `accepted` is signed by the issuer of the
981
    /// signer's certificate and accepts `sa`; else the attestation's own
982
    /// time, which the signer chose.
98323×
    pub(crate) fn certified_time(
98423×
        &self,
98523×
        signer: &KeyId,
98623×
        sa: &SignedAttest,
98723×
        accepted: Option<&SignedAttest>,
98823×
    ) -> u64 {
98923×
        let own = sa.attest.hlc.wall_ms;
99023×
        let Some(acc) = accepted else {
99117×
            return own;
992
        };
9936×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
9940×
            return own;
995
        };
9966×
        let Ok(cert) = self.store.get_certificate(&c) else {
9970×
            return own;
998
        };
9996×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
10000×
            return own;
1001
        };
10026×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
10031×
            return own;
1004
        };
10055×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
10060×
            return own;
1007
        };
10085×
        if *attest == sa.attest.hash()
10094×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1010
        {
10114×
            acc.attest.hlc.wall_ms
1012
        } else {
10131×
            own
1014
        }
101523×
    }
1016
1017
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1018
    /// at `old_state`, is never the bookmark a non-bare repository has
1019
    /// checked out (a bare one's default is its host's to protect, see
1020
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1021
    /// an attestation by a key that may update it.
1022
    /// The deletion's attestation stays the bookmark's latest, so an older
1023
    /// one cannot be replayed to bring it back.
10243×
    fn apply_deletion(
10253×
        &self,
10263×
        view: &mut View,
10273×
        u: &RefUpdate,
10283×
        policy: Option<&crate::policy::Policy>,
10293×
    ) -> std::result::Result<(), String> {
10303×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
10310×
            return Err(format!("no bookmark {:?} to delete", u.name));
1032
        };
10333×
        if current != u.old_state {
10340×
            return Err("stale: the remote bookmark has moved; pull first".into());
10353×
        }
10363×
        if !self.is_bare() && u.name == self.config.bookmark {
10371×
            return Err(format!(
10381×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
10391×
                u.name
10401×
            ));
10412×
        }
10422×
        if let Some(p) = policy {
10430×
            let Some(sa) = &u.attestation else {
10440×
                return Err(format!(
10450×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
10460×
                    u.name
10470×
                ));
1048
            };
10490×
            let signer = sa
10500×
                .sigs
10510×
                .first()
10520×
                .map(|s| s.key)
10530×
                .ok_or("attestation carries no signature")?;
1054
            // Received now: the receiver's own clock is the trusted time.
10550×
            let now = Hlc::now().wall_ms;
10560×
            if !p.authorizes(&signer, &u.name)
10570×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
10580×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1059
            {
10600×
                return Err(format!(
10610×
                    "key {} may not delete {:?} under this repository's policy",
10620×
                    signer.short(12),
10630×
                    u.name
10640×
                ));
10650×
            }
10662×
        }
10672×
        if let Some(sa) = &u.attestation {
10681×
            self.record_update_attest(u, sa)?;
10691×
        }
10702×
        view.bookmarks.remove(&u.name);
10712×
        Ok(())
10723×
    }
1073
1074306×
    fn apply_update(
1075306×
        &self,
1076306×
        view: &mut View,
1077306×
        u: &RefUpdate,
1078306×
        policy: Option<&crate::policy::Policy>,
1079306×
    ) -> std::result::Result<(), String> {
1080306×
        if u.name == "policy" {
10810×
            return Err(
10820×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
10830×
            );
1084306×
        }
1085306×
        let empty = self
1086306×
            .store
1087306×
            .put_state(&StateObject::new(vec![]))
1088306×
            .map_err(|e| e.to_string())?;
1089306×
        if u.new_state.is_zero() {
10903×
            return self.apply_deletion(view, u, policy);
1091303×
        }
1092303×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1093303×
        if current != u.old_state {
10949×
            return Err("stale: the remote bookmark has moved; pull first".into());
1095294×
        }
1096294×
        let new_state = self
1097294×
            .store
1098294×
            .get_state(&u.new_state)
1099294×
            .map_err(|_| "new state object is missing".to_string())?;
1100574×
        for h in &new_state.heads {
1101574×
            if !self.store.has(h) {
11021×
                return Err(format!("head {} is missing", h.short(12)));
1103573×
            }
1104
        }
1105293×
        if !u.force {
1106292×
            let old_heads = self
1107292×
                .store
1108292×
                .get_state(&current)
1109292×
                .map_err(|e| e.to_string())?
1110
                .heads;
1111292×
            let closure = self
1112292×
                .closure_in_store(&new_state.heads)
1113292×
                .map_err(|e| e.to_string())?;
1114309×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
11151×
                return Err(format!(
11161×
                    "not a fast-forward: current head {} would be dropped (use --force)",
11171×
                    h.short(12)
11181×
                ));
1119291×
            }
11201×
        }
1121292×
        if let Some(p) = policy {
112238×
            let Some(sa) = &u.attestation else {
11231×
                return Err(format!(
11241×
                    "{:?} requires a signed reference attestation under this repository's policy",
11251×
                    u.name
11261×
                ));
1127
            };
112837×
            let signer = sa
112937×
                .sigs
113037×
                .first()
113137×
                .map(|s| s.key)
113237×
                .ok_or("attestation carries no signature")?;
1133
            // Received now: the receiver's own clock is the trusted time.
113437×
            let now = Hlc::now().wall_ms;
113537×
            if !p.authorizes(&signer, &u.name)
113611×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11379×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1138
            {
11397×
                return Err(format!(
11407×
                    "key {} may not update {:?} under this repository's policy",
11417×
                    signer.short(12),
11427×
                    u.name
11437×
                ));
114430×
            }
114530×
            let old_heads = self
114630×
                .store
114730×
                .get_state(&current)
114830×
                .map_err(|e| e.to_string())?
1149
                .heads;
115030×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1151254×
        }
1152284×
        if let Some(sa) = &u.attestation {
115383×
            self.record_update_attest(u, sa)?;
1154201×
        }
1155278×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1156278×
        Ok(())
1157306×
    }
1158
1159
    // ------------------------------------------------------------ client side
1160
11611342×
    fn remote_url(&self, name: &str) -> Result<String> {
11621342×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
11633×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
11643×
            RepoError::Msg(match names.as_slice() {
11653×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
11661×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1167
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
11681×
                    names.join(", "),
11691×
                    names[0],
11701×
                    names[0]
1171
                ),
11720×
                _ => format!(
1173
                    "no remote named {name:?}; this repository has {}",
11740×
                    names.join(", ")
1175
                ),
1176
            })
11773×
        })
11781342×
    }
1179
1180
    /// Refuse a remote that is another repository. An **unbound** remote
1181
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1182
    /// for pushes, which bind it to this repository's id (spec §16.1).
1183730×
    fn check_remote_id(
1184730×
        &self,
1185730×
        remote: &dyn crate::protocol::Remote,
1186730×
        remote_name: &str,
1187730×
        allow_unbound: bool,
1188730×
    ) -> Result<()> {
1189730×
        let theirs = remote.repo_id()?;
1190729×
        if theirs == self.id()? {
1191706×
            return Ok(());
119223×
        }
119323×
        if theirs == crate::protocol::UNBOUND_ID {
119420×
            if allow_unbound {
119519×
                return Ok(());
11961×
            }
11971×
            return fail(format!(
1198
                "remote {remote_name:?} is empty and unbound: push to it first"
1199
            ));
12003×
        }
12013×
        fail(format!(
1202
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1203
        ))
1204730×
    }
1205
1206
    /// Credentials and trust for a remote: `remote.<name>.token` and
1207
    /// `remote.<name>.ca`, else the defaults for its URL
1208
    /// ([`Repo::fill_credentials`]).
12091002×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
12101002×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
12111002×
        let mut options = RemoteOptions {
12121002×
            repo_id: self.id().ok(),
12131002×
            token: self.config.remote_tokens.get(name).cloned(),
12141002×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
12151002×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
12161002×
            ..RemoteOptions::default()
12171002×
        };
12181002×
        self.fill_credentials(&url, &mut options);
12191002×
        options
12201002×
    }
1221
1222
    /// The user's credential store (`credentials.toml` beside the user
1223
    /// configuration file).
12241021×
    pub fn credentials(&self) -> crate::credentials::Credentials {
12251021×
        crate::credentials::Credentials::at(
12261021×
            self.user_config
12271021×
                .parent()
12281021×
                .map(Path::to_path_buf)
12291021×
                .unwrap_or_else(default_home),
1230
        )
12311021×
    }
1232
1233
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1234
    /// then the user's credential store for its hub, then a remote on the
1235
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1236
    /// When the token is not this remote's own or the environment's, the
1237
    /// other tokens enclosing checkouts hold for the hub are kept to try
1238
    /// if it is refused: a stale stored login must not hide a parent's
1239
    /// good token (oxygen#112).
12401022×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
12411022×
        if options.token.is_some() && options.ca.is_some() {
12421×
            return;
12431021×
        }
12441021×
        let explicit =
12451021×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
12461021×
        let stored = self.credentials().options_for(url);
12471021×
        options.token = options.token.take().or(stored.token);
12481021×
        options.ca = options.ca.take().or(stored.ca);
12491021×
        let enclosing = self.enclosing_credentials(url);
12501021×
        if options.token.is_none() {
12511011×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
125210×
        }
12531021×
        if options.ca.is_none() {
1254974×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
125547×
        }
12561021×
        if !explicit {
12571014×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
12585×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
12592×
                    options.fallback_tokens.push(t);
12603×
                }
1261
            }
12627×
        }
12631022×
    }
1264
1265
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1266
    /// checkouts, nearest first.
12671021×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
12681021×
        let mut out = Vec::new();
12691021×
        let Some(hub) = crate::credentials::hub_of(url) else {
1270887×
            return out;
1271
        };
1272134×
        let mut at = self.root.parent();
1273544×
        while let Some(dir) = at {
1274410×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
12750×
                break;
1276
            };
1277410×
            for (key, remote_url) in &cfg {
127815×
                let Some(name) = key
127915×
                    .strip_prefix("remote.")
128015×
                    .and_then(|k| k.strip_suffix(".url"))
1281
                else {
12827×
                    continue;
1283
                };
12848×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
12851×
                    continue;
12867×
                }
12877×
                out.push((
12887×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
12897×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
12907×
                ));
1291
            }
1292410×
            at = dir.parent();
1293
        }
1294134×
        out
12951021×
    }
1296
1297
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1298
    /// no changes and no reference updates, which the receiver stores.
12990×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
13000×
        let remote = self.open_named_remote(remote_name)?;
13010×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13020×
        let mut bundle = Bundle::default();
13030×
        for r in seals {
13040×
            let attest = self.store.get_attest(r)?;
13050×
            let sigs = self.store.signatures(r)?;
13060×
            bundle
13070×
                .attests
13080×
                .push(crate::protocol::SignedAttest { attest, sigs });
1309
        }
13100×
        let results = remote.push(bundle, vec![], None, vec![])?;
13110×
        if let Some(r) = results.iter().find(|r| !r.ok) {
13120×
            return fail(format!("{}: {}", r.name, r.reason));
13130×
        }
13140×
        Ok(())
13150×
    }
1316
1317
    /// The remote whose URL starts with `base` (a hub), if configured.
13184×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
13194×
        let base = base.trim_end_matches('/');
13204×
        self.config
13214×
            .remotes
13224×
            .iter()
13234×
            .find(|(_, url)| url.trim_end_matches('/') == base)
13244×
            .map(|(name, _)| name.clone())
13254×
    }
1326
1327
    /// Open a remote by name or, failing that, by URL with the default
1328
    /// credentials (see [`Repo::credentials_for`]).
13290×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
13300×
        if let Some(name) = self.remote_for_url(url) {
13310×
            return Ok((name.clone(), self.open_named_remote(&name)?));
13320×
        }
13330×
        let options = RemoteOptions {
13340×
            repo_id: self.id().ok(),
13350×
            ..self.credentials_for(url)
13360×
        };
13370×
        Ok((url.to_string(), open_remote(url, &options)?))
13380×
    }
1339
1340
    /// Credentials for a URL: those of the configured remote with that
1341
    /// URL, else the environment's.
13424×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
13434×
        match self.remote_for_url(url) {
13444×
            Some(name) => self.remote_options(&name),
13450×
            None => RemoteOptions {
13460×
                repo_id: self.id().ok(),
13470×
                ..self.credentials_for(url)
13480×
            },
1349
        }
13504×
    }
1351
1352985×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1353985×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1354985×
    }
1355
1356124×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1357124×
        self.oxy
1358124×
            .join("remotes")
1359124×
            .join(remote)
1360124×
            .join(format!("{bookmark}.serial"))
1361124×
    }
1362
136330×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
136430×
        fs::read_to_string(self.serial_path(remote, bookmark))
136530×
            .ok()
136630×
            .and_then(|s| s.trim().parse().ok())
136730×
    }
1368
136994×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
137094×
        let p = self.serial_path(remote, bookmark);
137194×
        fs::create_dir_all(p.parent().unwrap())?;
137294×
        write_atomic(&p, serial.to_string().as_bytes())
137394×
    }
1374
1375399×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1376399×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1377399×
    }
1378
1379
    /// The highest policy serial `remote` has ever presented.
1380357×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1381357×
        fs::read_to_string(self.policy_serial_path(remote))
1382357×
            .ok()
1383357×
            .and_then(|s| s.trim().parse().ok())
1384357×
    }
1385
138642×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
138742×
        let p = self.policy_serial_path(remote);
138842×
        fs::create_dir_all(p.parent().unwrap())?;
138942×
        write_atomic(&p, serial.to_string().as_bytes())
139042×
    }
1391
139227×
    fn lazy_dir(&self) -> PathBuf {
139327×
        self.oxy.join("lazy")
139427×
    }
1395
1396
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
13974×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
13984×
        fs::create_dir_all(self.lazy_dir())?;
13994×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
14004×
    }
1401
1402
    /// Which remote promised an absent blob, if any.
140315×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
140415×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
140515×
            .ok()
140615×
            .map(|s| s.trim().to_string())
140715×
    }
1408
1409
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
14104×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
14114×
        let Some(remote_name) = self.lazy_remote(blob) else {
14120×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1413
        };
14144×
        let remote = self.open_named_remote(&remote_name)?;
14154×
        let objects = remote.objects(&[*blob])?;
14169×
        for (ty, body) in objects {
14179×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
14189×
                self.store.put(ty, &body)?;
14190×
            }
1420
        }
14214×
        if !self.store.has(blob) {
14220×
            return fail(format!(
1423
                "{remote_name} did not send blob {}",
14240×
                blob.short(12)
1425
            ));
14264×
        }
14274×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
14284×
        Ok(())
14294×
    }
1430
1431
    /// After importing from `remote`, record every blob the changes reference
1432
    /// that the store lacks as lazily available from that remote.
14334×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
14344×
        let mut n = 0;
14354×
        for h in changes {
14364×
            let c = self.store.get_change(h)?;
143713×
            for e in &c.edits {
143813×
                if let Edit::Replace { old, new, .. } = e {
14396×
                    for b in [old, new].into_iter().flatten() {
14406×
                        if !self.store.has(b) {
14414×
                            self.register_lazy(b, remote)?;
14424×
                            n += 1;
14432×
                        }
1444
                    }
14457×
                }
1446
            }
1447
        }
14484×
        Ok(n)
14494×
    }
1450
1451
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1452357×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1453357×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1454478×
        for st in view
1455357×
            .bookmarks
1456357×
            .values()
1457357×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1458
        {
1459478×
            if let Ok(s) = self.store.get_state(st) {
1460478×
                have.extend(s.heads);
1461478×
            }
1462
        }
1463357×
        have.extend(view.workspaces.values().copied());
1464357×
        Ok(have.into_iter().collect())
1465357×
    }
1466
1467
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1468363×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1469363×
        let remote = self.open_named_remote(remote_name)?;
1470360×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1471358×
        let resp = remote.refs()?;
1472
        // The host's transparency log (spec §14.8): a fork fails here.
1473357×
        let log_notes = self.check_log(
1474357×
            &self.remote_url(remote_name)?,
1475357×
            self.config.remote_cas.get(remote_name).map(Path::new),
1476357×
            &resp,
14770×
        )?;
1478
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1479
        // and signed by roots we trust, or on first contact. A remote that
1480
        // once presented a policy may never present none or an older one:
1481
        // that is a downgrade. A remote that never presented one is
1482
        // unverified, and this fetch is checked only as far as possible.
1483357×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1484357×
        let seen = self.remote_policy_serial(remote_name);
1485357×
        let mut unverified = false;
1486357×
        match &resp.policy {
148719×
            Some(sp) => {
148819×
                if seen.is_some_and(|s| sp.policy.serial < s) {
14890×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
149019×
                }
14918×
                match &local_policy {
14928×
                    Some(l) if sp.policy.serial < l.serial => {}
14938×
                    Some(l) if sp.policy.serial == l.serial => {
14944×
                        if sp.policy.hash() != l.hash() {
14950×
                            return fail(format!(
1496
                                "{remote_name} presents a different policy with the same serial {}",
1497
                                l.serial
1498
                            ));
14994×
                        }
1500
                    }
1501
                    _ => {
150215×
                        self.adopt_policy_chain(
150315×
                            &resp.history,
150415×
                            sp,
150515×
                            &format!("oxy fetch {remote_name}"),
1506
                        )
150715×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1508
                    }
1509
                }
151019×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1511
            }
1512
            None => {
1513338×
                if seen.is_some() {
15140×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1515338×
                }
1516338×
                unverified = true;
1517
            }
1518
        }
1519357×
        let policy = if unverified {
1520338×
            None
1521
        } else {
152219×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1523
        };
1524357×
        let (op_ref, op) = self.head_op()?;
1525357×
        let mut view = op.view.clone();
1526357×
        let have = self.known_heads(&view)?;
1527357×
        let mut report = Vec::new();
1528357×
        let max_blob = self.config.max_blob;
1529365×
        for r in resp.refs {
1530365×
            let needed = {
1531365×
                let _t = crate::timing::phase("fetch: negotiate");
1532365×
                remote.negotiate(&have, &r.heads)?
1533
            };
1534365×
            let bundle = {
1535365×
                let _t = crate::timing::phase("fetch: bundle");
1536365×
                remote.fetch(&needed, max_blob)?
1537
            };
1538
            // Changes are not individually re-verified here: the bookmark's
1539
            // attestation (checked below) binds its whole state, and the
1540
            // receiver of the push verified the added changes at that time.
1541365×
            let imported = {
1542365×
                let _t = crate::timing::phase("fetch: import");
1543365×
                self.import_bundle(&bundle, false)?
1544
            };
1545365×
            if max_blob.is_some() {
15464×
                self.register_missing_blobs(&imported, remote_name)?;
1547361×
            }
1548499×
            for h in &r.heads {
1549499×
                if !self.store.has(h) {
15500×
                    return fail(format!("remote did not send head {}", h.short(12)));
1551499×
                }
1552
            }
1553365×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1554365×
            if state != r.state {
15550×
                return fail(format!(
1556
                    "remote state {} does not match its heads",
15570×
                    r.state.short(12)
1558
                ));
1559365×
            }
1560365×
            if let Some(p) = &policy {
156119×
                let Some(sa) = &r.attestation else {
15620×
                    return fail(format!(
1563
                        "{remote_name}/{} has no attestation, which its policy requires",
1564
                        r.name
1565
                    ));
1566
                };
156719×
                let signer = sa
156819×
                    .sigs
156919×
                    .first()
157019×
                    .map(|s| s.key)
157119×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1572
                // A certified signer is checked at the host's acceptance,
1573
                // when it countersigned one; else at the attestation's time.
157419×
                let at = self.certified_time(&signer, sa, r.accepted.as_ref());
157519×
                if !p.authorizes(&signer, &r.name)
15768×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
15778×
                    && !self.certified_authorized(p, &signer, &r.name, Scope::REFS, at)
1578
                {
15790×
                    return fail(format!(
1580
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1581
                        r.name,
15820×
                        signer.short(12)
1583
                    ));
158419×
                }
1585346×
            }
1586365×
            if let Some(sa) = &r.attestation {
1587
                let AttestBody::Ref {
158830×
                    old_state,
158930×
                    new_state,
1590
                    ..
159130×
                } = &sa.attest.body
1592
                else {
15930×
                    return fail("remote sent a non-ref attestation for a bookmark");
1594
                };
159530×
                let (old_state, new_state) = (*old_state, *new_state);
159630×
                let serial = self
159730×
                    .check_ref_attest(
159830×
                        sa,
159930×
                        &r.name,
160030×
                        &old_state,
160130×
                        &new_state,
160230×
                        self.last_seen_serial(remote_name, &r.name),
1603
                        true,
1604
                    )
160530×
                    .map_err(|e| {
16060×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
16070×
                    })?;
160830×
                if new_state != r.state {
16090×
                    return fail(format!(
1610
                        "attestation for {}/{} does not cover its current state",
1611
                        remote_name, r.name
1612
                    ));
161330×
                }
161430×
                let ar = self.store.put_attest(&sa.attest)?;
161530×
                for sig in &sa.sigs {
161630×
                    self.store.put_signature(&ar, sig)?;
1617
                }
161830×
                self.record_serial(remote_name, &r.name, serial)?;
1619335×
            }
1620365×
            view.remotes
1621365×
                .entry(remote_name.to_string())
1622365×
                .or_default()
1623365×
                .insert(r.name.clone(), state);
1624365×
            report.push((r.name, r.heads, imported.len()));
1625
        }
1626357×
        let mut new_tags = 0;
1627357×
        for t in &resp.tags {
162813×
            if view.tags.contains_key(&t.name) {
16294×
                continue;
16309×
            }
1631
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
16329×
            let missing: Vec<ChangeHash> = t
16339×
                .heads
16349×
                .iter()
16359×
                .filter(|h| !self.store.has(h))
16369×
                .copied()
16379×
                .collect();
16389×
            if !missing.is_empty() {
16390×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
16400×
                let bundle = remote.fetch(&needed, max_blob)?;
16410×
                self.import_bundle(&bundle, false)?;
16429×
            }
16439×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
16449×
            self.adopt_tag(&mut view, t, policy.as_ref())
16459×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
16469×
            new_tags += 1;
1647
        }
1648357×
        if view != op.view {
1649346×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
165011×
        }
1651357×
        let _ = self.run_hook(
1652357×
            "post-fetch",
1653357×
            &format!(
1654
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1655357×
                json_str(remote_name),
1656365×
                json_array(report.iter().map(|(n, heads, _)| format!(
1657
                    "{{\"name\":{},\"heads\":{}}}",
1658365×
                    json_str(n),
1659499×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1660
                )))
1661
            ),
1662
        );
1663357×
        Ok(FetchReport {
1664357×
            refs: report,
1665357×
            unverified,
1666357×
            new_tags,
1667357×
            log_notes,
1668357×
        })
1669363×
    }
1670
1671
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1672
    /// the changes within `depth` steps of its heads, and the boundary below.
16731×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
16741×
        let remote = self.open_named_remote(remote_name)?;
16751×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
16761×
        let resp = remote.refs()?;
16771×
        let bookmark = self.config.bookmark.clone();
16781×
        if let Some(sp) = &resp.policy {
16790×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
16800×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
16810×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
16821×
        }
16831×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
16840×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1685
        };
16861×
        if r.heads.is_empty() {
16870×
            return Ok(0);
16881×
        }
1689
        // Base: the remote's checkpoint of exactly these heads.
16901×
        let cp_bundle = remote.checkpoint(&r.heads)?;
16911×
        let mut cp_ref = None;
16923×
        for (ty, body) in &cp_bundle.objects {
16933×
            let put = self.store.put(*ty, body)?;
16943×
            if *ty == ObjectType::Checkpoint {
16951×
                cp_ref = Some(put);
16962×
            }
1697
        }
16981×
        let Some(cp_ref) = cp_ref else {
16990×
            return fail(format!("{remote_name} sent no checkpoint"));
1700
        };
17011×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1702
        // History window.
17031×
        let wanted = remote.shallow(&r.heads, depth)?;
17041×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
17051×
        let imported = self.import_bundle_shallow(&bundle, false)?;
17061×
        if self.config.max_blob.is_some() {
17070×
            self.register_missing_blobs(&imported, remote_name)?;
17081×
        }
17091×
        self.refresh_boundary(&imported)?;
17101×
        if let Some(sa) = &r.attestation {
17110×
            let ar = self.store.put_attest(&sa.attest)?;
17120×
            for sig in &sa.sigs {
17130×
                self.store.put_signature(&ar, sig)?;
1714
            }
17150×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
17160×
                self.record_serial(remote_name, &r.name, serial)?;
17170×
            }
17181×
        }
17191×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
17201×
        let (op_ref, op) = self.head_op()?;
17211×
        let mut view = op.view.clone();
17221×
        view.remotes
17231×
            .entry(remote_name.to_string())
17241×
            .or_default()
17251×
            .insert(r.name.clone(), state);
17261×
        self.record_op(
17271×
            &[op_ref],
17281×
            &format!("oxy fetch {remote_name} --depth {depth}"),
17291×
            view,
17300×
        )?;
17311×
        Ok(imported.len())
17321×
    }
1733
1734
    /// Fetch, then take the union of the local bookmark's state with the
1735
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1736104×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1737104×
        let _wc = self.lock_working_copy()?;
1738104×
        self.fetch(remote_name)?;
1739101×
        let (op_ref, op) = self.head_op()?;
1740101×
        let current = self.config.bookmark.clone();
1741101×
        let mut local_current = self.heads_of(&op.view, &current)?;
1742101×
        local_current.sort();
1743101×
        let mut view = op.view.clone();
1744101×
        let mut current_heads = local_current.clone();
1745101×
        let mut changed = false;
1746101×
        let mut others = Vec::new();
1747101×
        let tracked = op
1748101×
            .view
1749101×
            .remotes
1750101×
            .get(remote_name)
1751101×
            .cloned()
1752101×
            .unwrap_or_default();
1753105×
        for (name, remote_state) in tracked {
1754
            // Every local bookmark tracks the remote's of the same name;
1755
            // the current one may be new here.
1756105×
            let local_state = op.view.bookmarks.get(&name).copied();
1757105×
            if local_state.is_none() && name != current {
17580×
                continue;
1759105×
            }
1760105×
            if local_state == Some(remote_state) {
17619×
                continue;
176296×
            }
176396×
            let local = self.heads_of(&op.view, &name)?;
176496×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1765126×
            if remote_heads.iter().all(|h| local.contains(h)) {
17660×
                continue;
176796×
            }
176896×
            let mut all = local.clone();
176996×
            all.extend(remote_heads);
177096×
            let st = self.load_state_history(&all)?;
177196×
            let mut heads = st.maximal(&all);
177296×
            heads.sort();
177396×
            let mut sorted_local = local;
177496×
            sorted_local.sort();
177596×
            if heads == sorted_local {
17761×
                continue;
177795×
            }
177895×
            view.bookmarks.insert(
177995×
                name.clone(),
178095×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1781
            );
178295×
            if name == current {
178393×
                changed = true;
178493×
                current_heads = heads;
178593×
            } else {
17862×
                others.push(name);
17872×
            }
1788
        }
1789101×
        if changed || !others.is_empty() {
179094×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
17917×
        }
1792
        // The working copy follows its bookmark whenever nothing would be
1793
        // lost, also when this pull brought nothing new but it had been
1794
        // left behind (oxygen#89).
1795101×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1796
        Ok(PullReport {
1797101×
            heads: if changed {
179893×
                current_heads
1799
            } else {
18008×
                local_current
1801
            },
1802101×
            changed,
1803101×
            checked_out,
1804101×
            others,
1805
        })
1806104×
    }
1807
1808
    /// How many changes the working copy's bookmark has that its base
1809
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1810
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1811
    /// the bookmark or holds changes the bookmark lacks. History is read
1812
    /// only when the base and the bookmark's heads differ (oxygen#89).
18137×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
18147×
        let (_, wc) = self.working_copy()?;
18157×
        let mut base = wc.deps.clone();
18167×
        base.sort();
18177×
        let mut heads = self.bookmark_heads()?;
18187×
        heads.sort();
18197×
        if base == heads || heads.is_empty() {
18206×
            return Ok(None);
18211×
        }
18221×
        let state = self.load_state_history(&heads)?;
18231×
        if !base.iter().all(|h| state.contains(h)) {
18240×
            return Ok(None);
18251×
        }
18261×
        let had = if base.is_empty() {
18270×
            0
1828
        } else {
18291×
            self.load_state_history(&base)?.len()
1830
        };
18311×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
18327×
    }
1833
1834
    /// Bring the working copy to `heads`, the state of its bookmark
1835
    /// `bookmark`, when nothing would be lost: its base is part of that
1836
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1837
    /// with uncommitted work, the work comes along when the new changes
1838
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1839
    /// it followed only from exactly the bookmark's old heads, so a working
1840
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1841
    /// or a pull from another workspace) never caught up, and nothing said
1842
    /// so (oxygen#74, #89). Returns whether it moved.
1843101×
    pub fn follow_bookmark(
1844101×
        &self,
1845101×
        heads: &[ChangeHash],
1846101×
        bookmark: &str,
1847101×
        command: &str,
1848101×
    ) -> Result<bool> {
1849101×
        let snap = self.snapshot(command)?;
1850101×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1851101×
        let mut base = snap.base.maximal(&snap.wc.deps);
1852101×
        base.sort();
1853101×
        let mut target = heads.to_vec();
1854101×
        target.sort();
1855101×
        if base == target {
18567×
            return Ok(false);
185794×
        }
185894×
        let state = self.load_state_history(heads)?;
1859179×
        if !base.iter().all(|h| state.contains(h)) {
1860
            // The working copy holds changes the bookmark lacks: not ours to move.
18610×
            return Ok(false);
186294×
        }
186394×
        if clean {
186494×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
186594×
            Ok(true)
1866
        } else {
18670×
            Ok(self
18680×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
18690×
                .is_ok())
1870
        }
1871101×
    }
1872
1873
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1874
    /// changes and attesting the reference when a key is available.
1875
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1876
    /// state, attested when we have an identity. The local bookmark, if
1877
    /// any, is kept; only the remote-tracking entry goes.
18785×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
18795×
        let remote = self.open_named_remote(remote_name)?;
18805×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
18815×
        let resp = remote.refs()?;
18827×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
18831×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1884
        };
18854×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
18860×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
18874×
        }
18884×
        let attestation = match self.secret_key()? {
18892×
            Some(_) => Some(self.sign_attest(&Attest {
18902×
                repo: self.id()?,
18912×
                hlc: Hlc::now(),
18922×
                body: AttestBody::Ref {
18932×
                    name: bookmark.to_string(),
18942×
                    old_state: r.state,
18952×
                    new_state: ObjectRef::ZERO,
18962×
                    serial: r.last_serial.unwrap_or(0) + 1,
18972×
                },
18980×
            })?),
18992×
            None => None,
1900
        };
19014×
        let results = remote.push(
19024×
            Bundle::default(),
19034×
            vec![RefUpdate {
19044×
                name: bookmark.to_string(),
19054×
                old_state: r.state,
19064×
                new_state: ObjectRef::ZERO,
19074×
                force: true,
19084×
                attestation,
19094×
            }],
19104×
            None,
19114×
            vec![],
19120×
        )?;
19134×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
19142×
            let (op_ref, op) = self.head_op()?;
19152×
            let mut view = op.view.clone();
19162×
            if let Some(m) = view.remotes.get_mut(remote_name) {
19172×
                m.remove(bookmark);
19182×
            }
19192×
            self.record_op(
19202×
                &[op_ref],
19212×
                &format!("oxy push {remote_name} --delete {bookmark}"),
19222×
                view,
19230×
            )?;
19242×
        }
19254×
        Ok(results)
19265×
    }
1927
1928
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1929
    /// repository's config (its URL, token, CA and store settings), its
1930
    /// tracking bookmarks in the view, and a store remote's mirror under
1931
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
19323×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
19333×
        if !self.config.remotes.contains_key(name) {
19341×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
19352×
        }
19362×
        let prefix = format!("remote.{name}.");
19372×
        let keys: Vec<String> = self
19382×
            .config
19392×
            .repo_layer()
19402×
            .keys()
19414×
            .filter(|k| k.starts_with(&prefix))
19422×
            .cloned()
19432×
            .collect();
19443×
        for k in keys {
19453×
            self.config.set(&k, "")?;
1946
        }
19472×
        self.config.remotes.remove(name);
19482×
        self.save_config()?;
19492×
        let (op_ref, op) = self.head_op()?;
19502×
        if op.view.remotes.contains_key(name) {
19511×
            let mut view = op.view.clone();
19521×
            view.remotes.remove(name);
19531×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
19541×
        }
19552×
        let mirror = self.oxy.join("remotes").join(name);
19562×
        if mirror.is_dir() {
19570×
            fs::remove_dir_all(&mirror)?;
19582×
        }
19592×
        Ok(())
19603×
    }
1961
1962
    /// `changes`, in dependency order, cut into batches of about
1963
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1964
    /// There is always one, perhaps empty.
1965286×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1966286×
        let blob_len = |r: &ObjectRef| -> u64 {
196729×
            self.store
196829×
                .get_typed(r, ObjectType::Blob)
196929×
                .ok()
197029×
                .and_then(|b| Blob::decode(&b).ok())
197129×
                .map_or(0, |b| b.length)
197229×
        };
1973286×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1974396×
        for h in changes {
1975396×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1976396×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1977396×
            let mut weight = raw.len() as u64;
1978494×
            for t in &texts {
1979494×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
198026×
                    weight += blob_len(r);
1981468×
                }
1982
            }
1983652×
            for e in &c.edits {
19843×
                if let Edit::Replace { new: Some(b), .. } = e {
19853×
                    weight += blob_len(b);
1986649×
                }
1987
            }
1988396×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
19895×
                out.push(std::mem::take(&mut batch));
19905×
                bytes = 0;
1991391×
            }
1992396×
            batch.push(*h);
1993396×
            bytes += weight;
1994
        }
1995286×
        out.push(batch);
1996286×
        Ok(out)
1997286×
    }
1998
1999349×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2000349×
        let bookmark = self.config.bookmark.clone();
2001349×
        self.push_bookmark(remote_name, &bookmark, force)
2002349×
    }
2003
2004
    /// `push` for a named bookmark (`oxy push -b NAME`).
2005357×
    pub fn push_bookmark(
2006357×
        &self,
2007357×
        remote_name: &str,
2008357×
        bookmark: &str,
2009357×
        force: bool,
2010357×
    ) -> Result<Vec<RefResult>> {
2011357×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2012357×
    }
2013
2014
    /// `push_bookmark`, saying how a long push is going: one line per
2015
    /// batch sent (oxygen#95).
2016365×
    pub fn push_bookmark_with(
2017365×
        &self,
2018365×
        remote_name: &str,
2019365×
        bookmark: &str,
2020365×
        force: bool,
2021365×
        progress: crate::store::Progress,
2022365×
    ) -> Result<Vec<RefResult>> {
2023365×
        let (op_ref, op) = self.head_op()?;
2024365×
        if !op.view.bookmarks.contains_key(bookmark) {
20250×
            return fail(format!("no bookmark {bookmark}"));
2026365×
        }
2027365×
        let bookmark = bookmark.to_string();
2028365×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2029
        // pre-push hook: may veto before the remote is contacted.
2030365×
        self.run_hook(
2031365×
            "pre-push",
2032365×
            &format!(
2033
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2034365×
                json_str(remote_name),
2035365×
                json_str(&bookmark),
2036738×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2037
            ),
20381×
        )?;
2039364×
        let remote = self.open_named_remote(remote_name)?;
2040364×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2041361×
        let resp = remote.refs()?;
2042361×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2043361×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2044361×
        let policy_to_send = match (&local_policy, &resp.policy) {
204529×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
204610×
            (Some(l), None) => Some(l.clone()),
204716×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
20481×
                return fail(format!(
2049
                    "{remote_name} has a newer policy (serial {}); fetch first",
2050
                    r.policy.serial
2051
                ));
2052
            }
2053337×
            _ => None,
2054
        };
2055360×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2056360×
        if remote_has_policy && self.secret_key()?.is_none() {
20571×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2058359×
        }
2059359×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2060359×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2061359×
            .tag_refs()?
2062359×
            .into_iter()
2063359×
            .filter(|t| !remote_tags.contains(&t.name))
2064359×
            .collect();
2065359×
        let refs = resp.refs;
2066359×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2067359×
        let (remote_state, remote_heads, last_serial) =
2068359×
            match refs.iter().find(|r| r.name == bookmark) {
2069342×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
207017×
                None => (empty, vec![], None),
2071
            };
2072359×
        let new_state = self
2073359×
            .store
2074359×
            .put_state(&StateObject::new(local_heads.clone()))?;
2075
        // A push that carries a policy re-attests the bookmark even when its
2076
        // state is unchanged, so the current attestation is always by a key
2077
        // the current policy authorizes (a revoked key's attestation would
2078
        // otherwise be refused by every later fetch).
2079359×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
20807×
            return Ok(vec![RefResult {
20817×
                name: bookmark,
20827×
                ok: true,
20837×
                reason: "already up to date".into(),
20847×
            }]);
2085352×
        }
2086396×
        for h in &remote_heads {
2087396×
            if !self.store.has(h) {
208865×
                return fail(format!(
2089
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
209065×
                    h.short(12)
2091
                ));
2092331×
            }
2093
        }
2094287×
        if !force {
2095287×
            let closure = self.closure_in_store(&local_heads)?;
2096308×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
20970×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2098287×
            }
20990×
        }
2100287×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2101287×
        let key = self.secret_key()?.map(|(k, _)| k);
2102287×
        if let Some(key) = key {
2103
            // Seal this author's changes that carry no valid authenticator,
2104
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2105
            // are stored, so each batch's bundle carries those it needs.
210687×
            let mut unsigned = Vec::new();
210787×
            for h in &to_send {
210879×
                let c = self.store.get_change_meta(h)?;
210979×
                if self.seals_for_author(&c.author, &key)
211076×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
211147×
                {
211247×
                    unsigned.push(*h);
211347×
                }
2114
            }
211587×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
211644×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2117
            }
2118200×
        }
2119
        // A long history goes in batches, in dependency order, so neither
2120
        // side holds it whole and no request passes the remote's limit:
2121
        // all but the last carry objects alone; the last moves the bookmark
2122
        // (oxygen#95).
2123286×
        let batches = self.push_batches(&to_send)?;
2124286×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2125286×
        for (i, batch) in earlier.iter().enumerate() {
21265×
            progress(&format!(
21275×
                "part {} of {}: {} changes",
21285×
                i + 1,
21295×
                batches.len(),
21305×
                batch.len()
21315×
            ));
21325×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
21335×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
21345×
                Some(r) if r.ok => {}
21350×
                Some(r) => {
21360×
                    return fail(format!(
2137
                        "{remote_name} refused part {} of the push: {}",
21380×
                        i + 1,
2139
                        r.reason
2140
                    ))
2141
                }
2142
                None => {
21430×
                    return fail(format!(
2144
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2145
                    ))
2146
                }
2147
            }
2148
        }
2149286×
        if batches.len() > 1 {
21501×
            progress(&format!(
21511×
                "part {} of {}: {} changes",
21521×
                batches.len(),
21531×
                batches.len(),
21541×
                last.len()
21551×
            ));
2156285×
        }
2157286×
        let mut bundle = self.bundle_for(last)?;
2158286×
        bundle.objects.push((
2159286×
            ObjectType::State,
2160286×
            StateObject::new(local_heads.clone()).encode(),
2161286×
        ));
2162286×
        let attestation = match key {
216386×
            Some(_) => Some(self.sign_attest(&Attest {
216486×
                repo: self.id()?,
216586×
                hlc: Hlc::now(),
216686×
                body: AttestBody::Ref {
216786×
                    name: bookmark.clone(),
216886×
                    old_state: remote_state,
216986×
                    new_state,
217086×
                    serial: next_serial(last_serial),
217186×
                },
21721×
            })?),
2173200×
            None => None,
2174
        };
2175
        // Whoever signed the move, and whom a delegate acts for, travel with
2176
        // it: a receiver that has never seen a change by this delegate could
2177
        // not otherwise check its signature (oxygenhub#129).
2178285×
        if attestation.is_some() {
2179170×
            for k in [self.signing_key(), self.config.author_key]
218085×
                .into_iter()
218185×
                .flatten()
2182
            {
2183170×
                if let Ok(id) = self.identity(&k) {
2184170×
                    let body = id.encode();
2185170×
                    if !bundle
2186170×
                        .objects
2187170×
                        .iter()
2188199×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
218917×
                    {
219017×
                        bundle.objects.push((ObjectType::Identity, body));
2191153×
                    }
21920×
                }
2193
            }
2194
            // A short-lived signing key's certificate goes with it (§14.7).
219585×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
219685×
            self.attach_certificates_for(&mut bundle, &signers)?;
2197200×
        }
2198285×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
219985×
            AttestBody::Ref { serial, .. } => Some(serial),
22000×
            _ => None,
220185×
        });
2202285×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2203
        // Tag states must be present on the remote: bundle their changes too.
2204285×
        for t in &tags_to_send {
22056×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
22066×
            let extra: Vec<ChangeHash> =
22076×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
22086×
            if !extra.is_empty() {
22090×
                let more = self.bundle_for(&extra)?;
22100×
                bundle.changes.extend(more.changes);
22110×
                bundle.hashes.extend(more.hashes);
22120×
                bundle.attests.extend(more.attests);
22130×
                bundle.objects.extend(more.objects);
22146×
            }
22156×
            bundle.objects.push((
22166×
                ObjectType::State,
22176×
                StateObject::new(t.heads.clone()).encode(),
22186×
            ));
2219
        }
2220285×
        if let Some(l) = &policy_to_send {
222123×
            let remote_serial = resp_policy_serial;
222223×
            bundle.policies = self
222323×
                .policy_history()?
222423×
                .into_iter()
222550×
                .filter(|sp| {
222650×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
222725×
                        && sp.policy.serial < l.policy.serial
222850×
                })
222923×
                .collect();
2230262×
        }
2231285×
        let results = remote.push(
2232285×
            bundle,
2233285×
            vec![RefUpdate {
2234285×
                name: bookmark.clone(),
2235285×
                old_state: remote_state,
2236285×
                new_state,
2237285×
                force,
2238285×
                attestation,
2239285×
            }],
2240285×
            policy_to_send,
2241285×
            tags_to_send,
22427×
        )?;
224323×
        if let (Some(serial), true) = (
2244278×
            sent_serial,
2245284×
            results.iter().any(|r| r.ok && r.name == "policy"),
2246
        ) {
224723×
            self.record_policy_serial(remote_name, serial)?;
2248255×
        }
2249301×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2250255×
            let mut view = op.view.clone();
2251255×
            view.remotes
2252255×
                .entry(remote_name.to_string())
2253255×
                .or_default()
2254255×
                .insert(bookmark.clone(), new_state);
2255255×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2256252×
            if let Some(s) = serial {
225764×
                self.record_serial(remote_name, &bookmark, s)?;
2258188×
            }
225923×
        }
2260273×
        Ok(results)
2261365×
    }
2262
2263
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2264
    /// bookmark set to the remote's, working copy checked out.
2265235×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2266235×
        Self::clone_with(url, dest, None, &[])
2267235×
    }
2268
2269
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2270
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2271
    /// unless a size is given, so out-of-scope binaries are never fetched).
2272243×
    pub fn clone_with(
2273243×
        url: &str,
2274243×
        dest: &Path,
2275243×
        max_blob: Option<u64>,
2276243×
        sparse: &[String],
2277243×
    ) -> Result<Repo> {
2278243×
        Self::clone_full(url, dest, max_blob, sparse, None)
2279243×
    }
2280
2281
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2282
    /// changes within `depth` steps of them; the rest is the boundary.
22831×
    pub fn clone_shallow(
22841×
        url: &str,
22851×
        dest: &Path,
22861×
        depth: u32,
22871×
        max_blob: Option<u64>,
22881×
        sparse: &[String],
22891×
    ) -> Result<Repo> {
22901×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
22911×
    }
2292
2293244×
    fn clone_full(
2294244×
        url: &str,
2295244×
        dest: &Path,
2296244×
        max_blob: Option<u64>,
2297244×
        sparse: &[String],
2298244×
        depth: Option<u32>,
2299244×
    ) -> Result<Repo> {
2300244×
        let options = crate::credentials::Credentials::user().options_for(url);
2301244×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2302244×
    }
2303
2304
    /// Clone a subrepo with the credentials the parent would use for its
2305
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2306
    /// subrepo: it finds the same ones again through its parent.
23079×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
23089×
        let options = self.credentials_for(url);
23099×
        Self::clone_using(url, dest, None, &[], None, &options)
23109×
    }
2311
2312
    /// The name of a remote of this repository on the same hub (scheme,
2313
    /// host and port) as `url`.
231421×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
231525×
        let origin = |u: &str| -> Option<String> {
231625×
            let (scheme, rest) = u.split_once("://")?;
23178×
            if !matches!(scheme, "http" | "https") {
23180×
                return None;
23198×
            }
23208×
            let host = rest.split('/').next()?;
23218×
            Some(format!(
23228×
                "{}://{}",
23238×
                scheme.to_ascii_lowercase(),
23248×
                host.to_ascii_lowercase()
23258×
            ))
232625×
        };
232721×
        let want = origin(url)?;
23284×
        self.config
23294×
            .remotes
23304×
            .iter()
23314×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
23324×
            .map(|(name, _)| name.clone())
233321×
    }
2334
2335
    /// The token and CA to reach `url` with: those of a remote of this
2336
    /// repository on the same hub (scheme, host and port), else the
2337
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2338
    /// and enclosing checkouts', as a clone would use them.
233921×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
234021×
        match self.remote_on_same_hub(url) {
23411×
            Some(name) => RemoteOptions {
23421×
                repo_id: None,
23431×
                cache_dir: None,
23441×
                ..self.remote_options(&name)
23451×
            },
2346
            None => {
234720×
                let mut options = RemoteOptions::default();
234820×
                self.fill_credentials(url, &mut options);
234920×
                options
2350
            }
2351
        }
235221×
    }
2353
2354253×
    fn clone_using(
2355253×
        url: &str,
2356253×
        dest: &Path,
2357253×
        max_blob: Option<u64>,
2358253×
        sparse: &[String],
2359253×
        depth: Option<u32>,
2360253×
        options: &RemoteOptions,
2361253×
    ) -> Result<Repo> {
2362253×
        let remote = open_remote(url, options)?;
2363253×
        let id = remote.repo_id()?;
2364249×
        if id == crate::protocol::UNBOUND_ID {
23652×
            return fail(format!(
2366
                "{url} is empty and unbound: push a repository to it first"
2367
            ));
2368247×
        }
2369247×
        let mut repo = Repo::init_with_id(dest, id)?;
2370247×
        repo.config
2371247×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2372247×
        if let Some(m) = max_blob {
23732×
            repo.config.set("filter.max-blob", &m.to_string())?;
2374245×
        } else if !sparse.is_empty() {
23751×
            repo.config.set("filter.max-blob", "0")?;
2376244×
        }
2377247×
        if !sparse.is_empty() {
23781×
            repo.config.set("filter.paths", &sparse.join(","))?;
2379246×
        }
2380247×
        repo.save_config()?;
2381247×
        if let Some(depth) = depth {
23821×
            repo.fetch_shallow("origin", depth)?;
2383
        } else {
2384246×
            repo.fetch("origin")?;
2385
        }
2386246×
        let (op_ref, op) = repo.head_op()?;
2387
        // The remote's default bookmark, else ours (main), else its only one.
2388246×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2389
        // Asked of the remote as now configured, so a store-backed one
2390
        // answers from the mirror the fetch just filled.
2391246×
        let advertised = repo
2392246×
            .open_named_remote("origin")
2393246×
            .ok()
2394246×
            .and_then(|r| r.refs().ok())
2395246×
            .and_then(|r| r.default_bookmark);
2396246×
        let bookmark = advertised
2397246×
            .filter(|b| theirs.contains_key(b))
2398246×
            .or_else(|| {
23997×
                theirs
24007×
                    .contains_key(&repo.config.bookmark)
24017×
                    .then(|| repo.config.bookmark.clone())
24027×
            })
2403246×
            .or_else(|| {
24040×
                (theirs.len() == 1)
24050×
                    .then(|| theirs.keys().next().cloned())
24060×
                    .flatten()
24070×
            })
2408246×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2409246×
        let initial = repo.config.bookmark.clone();
2410246×
        if bookmark != repo.config.bookmark {
24111×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
24121×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
24131×
            repo.config.bookmark = bookmark.clone();
2414245×
        }
2415246×
        if let Some(state) = theirs.get(&bookmark).copied() {
2416246×
            let heads = repo.store.get_state(&state)?.heads;
2417246×
            let mut view = op.view.clone();
2418
            // The empty bookmark `init` made goes when another is checked out.
2419246×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
24201×
                view.bookmarks.remove(&initial);
2421245×
            }
2422246×
            view.bookmarks.insert(bookmark, state);
2423246×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2424246×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
24250×
        }
2426246×
        Ok(repo)
2427253×
    }
2428
}
2429
2430
/// The serial of a reference's next attestation: one more than the last the
2431
/// remote reports, or, for a bookmark the remote does not have, the clock in
2432
/// milliseconds, so a bookmark created again after a deletion goes past the
2433
/// deletion's serial the remote keeps.
243486×
fn next_serial(last: Option<u64>) -> u64 {
243586×
    match last {
243656×
        Some(l) => l + 1,
243730×
        None => Hlc::now().wall_ms.max(1),
2438
    }
243986×
}