OXYGENHUB

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

1719 of 1928 lines run, 251 of 362 functions · run #314 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
}
34
35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub struct PullReport {
37
    /// The current bookmark's heads after the pull.
38
    pub heads: Vec<ChangeHash>,
39
    /// Whether the current bookmark changed.
40
    pub changed: bool,
41
    pub checked_out: bool,
42
    /// Other bookmarks the pull moved: each local bookmark tracks the
43
    /// remote's of the same name.
44
    pub others: Vec<String>,
45
}
46
47
/// The result a push of objects alone reports (a batch of a long history):
48
/// not a reference.
49
pub const OBJECTS_RESULT: &str = "objects";
50
51
impl Repo {
52
    // ------------------------------------------------------------ serving (spec §16)
53
541306×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551306×
        self.oxy.join("attest").join(name_file(bookmark))
561306×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591222×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601222×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61235×
            Ok(h) => {
62235×
                let r = ObjectRef::from_hex(h.trim())
63235×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65235×
                    r,
66
                    SignedAttest {
67235×
                        attest: self.store.get_attest(&r)?,
68235×
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
71
            }
72987×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751222×
    }
76
7784×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7884×
        fs::create_dir_all(self.oxy.join("attest"))?;
7984×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8084×
    }
81
82997×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
83997×
        let view = self.view()?;
84997×
        let mut out = Vec::new();
851019×
        for (name, state) in &view.bookmarks {
861019×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
871019×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88136×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90136×
            });
911019×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
921019×
            let accepted = match &attestation {
93125×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
94894×
                None => None,
95
            };
961019×
            out.push(RemoteRef {
971019×
                name: name.clone(),
981019×
                state: *state,
991019×
                heads: self.store.get_state(state)?.heads,
1001019×
                attestation,
1011019×
                last_serial,
1021019×
                accepted,
103
            });
104
        }
105997×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
106997×
        let history = self
107997×
            .policy_history()?
108997×
            .into_iter()
109997×
            .filter(|sp| {
110126×
                policy
111126×
                    .as_ref()
112126×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
113126×
            })
114997×
            .collect();
115
        Ok(RefsResponse {
116997×
            refs: out,
117997×
            policy,
118997×
            tags: self.tag_refs()?,
119997×
            history,
120997×
            default_bookmark: Some(self.config.bookmark.clone()),
121
        })
122997×
    }
123
124
    /// Every change reachable from `heads` that is in the store.
1251336×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1261336×
        let mut seen = BTreeSet::new();
1271336×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1284525×
        while let Some(h) = stack.pop() {
1293189×
            if seen.contains(&h) || !self.store.has(&h) {
130885×
                continue;
1312304×
            }
1322304×
            seen.insert(h);
1332304×
            stack.extend(self.store.get_change_meta(&h)?.deps);
134
        }
1351336×
        Ok(seen)
1361336×
    }
137
138
    /// The changes within `depth` dependency steps of `heads` (spec §17),
139
    /// nearest first; depth 1 is the heads themselves.
1403×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1413×
        let mut out = Vec::new();
1423×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1433×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1443×
        for _ in 0..depth.max(1) {
1458×
            let mut next = Vec::new();
14612×
            for h in layer {
14712×
                if !seen.insert(h) || !self.store.has(&h) {
1482×
                    continue;
14910×
                }
15010×
                let c = self.store.get_change(&h)?;
15110×
                next.extend(c.deps.iter().copied());
15210×
                out.push(h);
153
            }
1548×
            if next.is_empty() {
1551×
                break;
1567×
            }
1577×
            layer = next;
158
        }
1593×
        out.reverse();
1603×
        Ok(out)
1613×
    }
162
1631919×
    fn shallow_path(&self) -> PathBuf {
1641919×
        self.oxy.join("shallow")
1651919×
    }
166
167
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1681916×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1691916×
        fs::read_to_string(self.shallow_path())
1701916×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1711916×
            .unwrap_or_default()
1721916×
    }
173
174183×
    pub fn is_shallow(&self) -> bool {
175183×
        !self.boundary().is_empty()
176183×
    }
177
1783×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1793×
        if boundary.is_empty() {
1801×
            let _ = fs::remove_file(self.shallow_path());
1811×
            return Ok(());
1822×
        }
1832×
        let text: String = boundary
1842×
            .iter()
1852×
            .map(|h| format!("{}\n", h.to_hex()))
1862×
            .collect();
1872×
        write_atomic(&self.shallow_path(), text.as_bytes())
1883×
    }
189
190
    /// Recompute the boundary from what is stored: every dependency of a
191
    /// stored change that is not itself stored.
1923×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1933×
        let mut boundary = self.boundary();
1943×
        boundary.retain(|h| !self.store.has(h));
19510×
        for h in imported {
19613×
            for d in self.store.get_change_meta(h)?.deps {
19713×
                if !self.store.has(&d) {
1982×
                    boundary.insert(d);
19911×
                }
200
            }
201
        }
2023×
        self.write_boundary(&boundary)
2033×
    }
204
205
    /// Fetch `depth` more levels of history below the shallow boundary.
2062×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2072×
        let boundary = self.boundary();
2082×
        if boundary.is_empty() {
2090×
            return Ok(0);
2102×
        }
2112×
        let remote = self.open_named_remote(remote_name)?;
2122×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2132×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2142×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2152×
        if self.config.max_blob.is_some() {
2160×
            self.register_missing_blobs(&imported, remote_name)?;
2172×
        }
2182×
        self.refresh_boundary(&imported)?;
2192×
        Ok(imported.len())
2202×
    }
221
222
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
223762×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
224762×
        let have = self.closure_in_store(have)?;
225
        // In a shallow repository the walk stops at the boundary, whose
226
        // changes the remote is assumed to hold.
227762×
        let boundary = self.boundary();
228762×
        let mut out = Vec::new();
229762×
        let mut done: BTreeSet<ChangeHash> = have.clone();
230762×
        done.extend(boundary.iter().copied());
231
        // Iterative post-order DFS.
2321205×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2333139×
        while let Some((h, expanded)) = stack.pop() {
2342377×
            if done.contains(&h) {
235403×
                continue;
2361974×
            }
2371974×
            if !self.store.has(&h) {
2380×
                return fail(format!("change {} is not in this repository", h.short(12)));
2391974×
            }
2401974×
            if expanded {
241987×
                done.insert(h);
242987×
                out.push(h);
243987×
                continue;
244987×
            }
245987×
            stack.push((h, true));
246987×
            for d in self.store.get_change_meta(&h)?.deps {
247639×
                if !done.contains(&d) {
248185×
                    stack.push((d, false));
249454×
                }
250
            }
251
        }
252762×
        Ok(out)
253762×
    }
254
255
    /// Bundle changes (in the given dependency order) with their signatures,
256
    /// seals, identities, blobs, chunks.
257303×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
258303×
        self.bundle_for_filtered(changes, None)
259303×
    }
260
261
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2624×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2634×
        let mut out = Vec::new();
2644×
        for r in refs {
2654×
            let (ty, body) = match self.store.get(r) {
2664×
                Ok(x) => x,
2670×
                Err(StoreError::NotFound(_)) => continue,
2680×
                Err(e) => return Err(e.into()),
269
            };
2704×
            if ty == ObjectType::Blob {
2715×
                for c in Blob::decode(&body)?.chunks {
2725×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2735×
                        out.push((cty, cb));
2745×
                    }
275
                }
2760×
            }
2774×
            out.push((ty, body));
278
        }
2794×
        Ok(out)
2804×
    }
281
282
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
283
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
284352×
    pub fn bundle_for_filtered(
285352×
        &self,
286352×
        changes: &[ChangeHash],
287352×
        max_blob: Option<u64>,
288352×
    ) -> Result<Bundle> {
289352×
        self.bundle_of(changes, max_blob, false)
290352×
    }
291
292
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
293
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
294
    /// with their text blobs and chunks among the objects, so neither side
295
    /// decodes or encodes their text.
296315×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
297315×
        self.bundle_of(changes, max_blob, true)
298315×
    }
299
300667×
    fn bundle_of(
301667×
        &self,
302667×
        changes: &[ChangeHash],
303667×
        max_blob: Option<u64>,
304667×
        raw: bool,
305667×
    ) -> Result<Bundle> {
306667×
        let mut bundle = Bundle::default();
307667×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
308667×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3091019×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3101019×
            if !r.is_zero() && self.store.has(r) {
311219×
                objects.insert(*r);
312800×
            }
3131019×
        };
314912×
        for h in changes {
315
            // Raw: the stored bytes, and a skeleton for the rest.
316912×
            let (c, encoded) = if raw {
317475×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
318475×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3194905×
                for t in texts {
3204905×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3213×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3223×
                        objects.insert(r);
3233×
                        objects.extend(blob.chunks);
3244902×
                    }
325
                }
326475×
                (skel, Some(bytes))
327
            } else {
328437×
                (self.store.get_change(h)?, None)
329
            };
330912×
            let sigs = self.store.signatures(h)?;
331912×
            add_object(&c.author, &mut objects);
332912×
            for s in &sigs {
33322×
                add_object(&s.key, &mut objects);
33422×
            }
3355762×
            for e in &c.edits {
3365762×
                if let Edit::Replace { old, new, .. } = e {
33714×
                    for b in [old, new].into_iter().flatten() {
33814×
                        if self.store.has(b) {
33914×
                            if let Ok(blob) =
34014×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
341
                            {
34214×
                                if max_blob.is_some_and(|m| blob.length > m) {
3434×
                                    continue;
34410×
                                }
34510×
                                objects.insert(*b);
34610×
                                objects.extend(blob.chunks.iter().copied());
3470×
                            }
3480×
                        }
349
                    }
3505750×
                }
351
            }
352912×
            for s in self.store.seals_for(h)? {
35390×
                seals.insert(s);
35490×
            }
355912×
            match encoded {
356475×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
357437×
                None => {
358437×
                    bundle.changes.push((c, sigs));
359437×
                    bundle.hashes.push(*h);
360437×
                }
361
            }
362
        }
363667×
        for r in seals {
36485×
            let attest = self.store.get_attest(&r)?;
36585×
            let sigs = self.store.signatures(&r)?;
36685×
            for s in &sigs {
36785×
                add_object(&s.key, &mut objects);
36885×
            }
36985×
            bundle.attests.push(SignedAttest { attest, sigs });
370
        }
371667×
        for r in objects {
372134×
            let (ty, body) = self.store.get(&r)?;
373134×
            bundle.objects.push((ty, body));
374
        }
375667×
        self.attach_certificates(&mut bundle)?;
376667×
        Ok(bundle)
377667×
    }
378
379
    /// Add the certificates of short-lived keys that signed what `bundle`
380
    /// carries, and their issuers' identities, so a receiver can tell who
381
    /// they stand for (spec §14.7). `also` names more signers (a reference
382
    /// attestation sent beside the bundle).
383752×
    pub(crate) fn attach_certificates_for(
384752×
        &self,
385752×
        bundle: &mut Bundle,
386752×
        also: &[KeyId],
387752×
    ) -> Result<()> {
388752×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
389752×
        keys.extend(
390752×
            bundle
391752×
                .changes
392752×
                .iter()
393752×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
394
        );
395752×
        keys.extend(
396752×
            bundle
397752×
                .raw_changes
398752×
                .iter()
399752×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
400
        );
401752×
        keys.extend(
402752×
            bundle
403752×
                .attests
404752×
                .iter()
405752×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
406
        );
407752×
        for k in keys {
408193×
            let Some(r) = self.store.certificate_of(&k)? else {
409172×
                continue;
410
            };
41121×
            let cert = self.store.get_certificate(&r)?;
41221×
            if bundle
41321×
                .certificates
41421×
                .iter()
41521×
                .any(|c| c.cert.hash() == cert.cert.hash())
416
            {
4177×
                continue;
41814×
            }
41928×
            for id in [&k, &cert.cert.issuer] {
42028×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
42128×
                    if !bundle
42228×
                        .objects
42328×
                        .iter()
42440×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
42514×
                    {
42614×
                        bundle.objects.push((ObjectType::Identity, body));
42714×
                    }
4280×
                }
429
            }
43014×
            bundle.certificates.push(cert);
431
        }
432752×
        Ok(())
433752×
    }
434
435667×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
436667×
        self.attach_certificates_for(bundle, &[])
437667×
    }
438
439
    /// Keep the certificates a bundle brings once each verifies with the
440
    /// identity of the issuer it names; one that does not refuses the bundle.
441712×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
442712×
        for c in certs {
44314×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4440×
                RepoError::Msg(format!(
4450×
                    "a certificate names issuer {}, whose identity did not come with it",
4460×
                    c.cert.issuer.short(12)
4470×
                ))
4480×
            })?;
44914×
            c.verify(&issuer)
45014×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
45114×
            self.store.put_identity(&c.cert.key)?;
45214×
            self.store.put_certificate(c)?;
453
        }
454712×
        Ok(())
455712×
    }
456
457
    /// A signer authorized for `reference` by what an issuer certified it
458
    /// as (spec §14.7): a short-lived key with a kept certificate that
459
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
460
    /// signer did not choose) and names a subject the policy grants.
46118×
    pub(crate) fn certified_authorized(
46218×
        &self,
46318×
        p: &crate::policy::Policy,
46418×
        signer: &KeyId,
46518×
        reference: &str,
46618×
        scope: Scope,
46718×
        at_ms: u64,
46818×
    ) -> bool {
46918×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
4705×
            return false;
471
        };
47213×
        let Ok(c) = self.store.get_certificate(&r) else {
4730×
            return false;
474
        };
47513×
        let Some(issuer) = p
47613×
            .identity(&c.cert.issuer)
47713×
            .cloned()
47813×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
479
        else {
4800×
            return false;
481
        };
48213×
        c.verify(&issuer).is_ok()
48313×
            && c.cert.key_id() == *signer
48413×
            && c.cert.covers(scope, at_ms)
48512×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
48618×
    }
487
488
    /// Store a bundle's contents. With `strict`, every change must
489
    /// authenticate (signature or seal by its author or a delegate).
490709×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
491709×
        self.import_bundle_inner(bundle, strict, false)
492709×
    }
493
494
    /// Like `import_bundle`, accepting changes whose dependencies are absent
495
    /// (they join the shallow boundary).
4963×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
4973×
        self.import_bundle_inner(bundle, strict, true)
4983×
    }
499
500712×
    fn import_bundle_inner(
501712×
        &self,
502712×
        bundle: &Bundle,
503712×
        strict: bool,
504712×
        shallow: bool,
505712×
    ) -> Result<Vec<ChangeHash>> {
506712×
        let batch = self.store.begin_batch()?;
507712×
        let result = self.import_bundle_batched(bundle, strict, shallow);
508712×
        batch.finish()?;
509710×
        result
510712×
    }
511
512712×
    fn import_bundle_batched(
513712×
        &self,
514712×
        bundle: &Bundle,
515712×
        strict: bool,
516712×
        shallow: bool,
517712×
    ) -> Result<Vec<ChangeHash>> {
518712×
        for (ty, _) in &bundle.objects {
5190×
            if !matches!(
520525×
                ty,
521
                ObjectType::Chunk
522
                    | ObjectType::Blob
523
                    | ObjectType::Identity
524
                    | ObjectType::State
525
                    | ObjectType::Checkpoint
526
            ) {
5270×
                return fail(format!("bundle may not carry {} objects", ty.name()));
528525×
            }
529
        }
530
        // All at once: in a large batch they are compressed on every core.
531712×
        let objects: Vec<(ObjectType, &[u8])> = bundle
532712×
            .objects
533712×
            .iter()
534712×
            .map(|(ty, body)| (*ty, body.as_slice()))
535712×
            .collect();
536712×
        self.store.put_many(&objects)?;
537712×
        self.adopt_certificates(&bundle.certificates)?;
538712×
        for sa in &bundle.attests {
53988×
            let r = self.store.put_attest(&sa.attest)?;
54088×
            for sig in &sa.sigs {
54188×
                self.store.put_signature(&r, sig)?;
542
            }
54388×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
54493×
                for h in hashes {
54593×
                    self.store.index_seal(h, &r)?;
546
                }
5470×
            }
548
        }
549
        // Each change's hash: from the bundle when its maker knew it, else
550
        // worked out once (for a change adding a whole tree, hashing is
551
        // chunking all its text).
552712×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
553703×
            bundle.hashes.clone()
554
        } else {
5559×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
556
        };
557712×
        let raw_hashes: Vec<ChangeHash> = bundle
558712×
            .raw_changes
559712×
            .iter()
560712×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
561712×
            .collect();
562712×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
563712×
        let boundary = self.boundary();
564712×
        let mut imported = Vec::new();
565
        // Changes as stored: checked, then stored as they are, their text
566
        // blobs having come with the objects.
567712×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
568476×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
569476×
            for d in &skel.deps {
570330×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
571
                {
5720×
                    return fail(format!(
573
                        "change {} depends on {}, which is neither stored nor in the bundle",
5740×
                        h.short(12),
5750×
                        d.short(12)
576
                    ));
577330×
                }
578
            }
5794906×
            for t in texts {
5804906×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
5814×
                    if !self.store.has(&r) {
5821×
                        return fail(format!(
583
                            "change {} came without its text blob {}",
5841×
                            h.short(12),
5851×
                            r.short(12)
586
                        ));
5873×
                    }
5884902×
                }
589
            }
590475×
            self.store.put(ObjectType::Change, bytes)?;
591475×
            for sig in sigs {
5924×
                self.store.put_signature(&h, sig)?;
593
            }
594475×
            imported.push(h);
595
        }
596711×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
597465×
            for d in &c.deps {
598263×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
599
                {
6003×
                    return fail(format!(
601
                        "change {} depends on {}, which is neither stored nor in the bundle",
6023×
                        h.short(12),
6033×
                        d.short(12)
604
                    ));
605260×
                }
606
            }
607462×
            let stored = self.store.put_change(c)?;
608462×
            if stored != h {
6090×
                return fail(format!(
610
                    "change {} is not the change the bundle names",
6110×
                    h.short(12)
612
                ));
613462×
            }
614462×
            for sig in sigs {
61527×
                self.store.put_signature(&h, sig)?;
616
            }
617462×
            imported.push(h);
618
        }
619708×
        if strict {
62043×
            for h in &imported {
62130×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6224×
                    return fail(format!(
623
                        "change {} is not authenticated by its author",
6244×
                        h.short(12)
625
                    ));
62626×
                }
627
            }
628665×
        }
629704×
        Ok(imported)
630712×
    }
631
632
    /// Verify a reference attestation against an update it claims to describe.
633
    /// `allow_equal` lets a client re-read the attestation it already has; a
634
    /// server receiving a push requires a strictly greater serial.
635
    /// A reference attestation signed by a delegate of an identity the
636
    /// rule lists is authorized as that identity (spec §14.5): the identity
637
    /// named the delegate with the `refs` scope, still in force at `at_ms`
638
    /// (the attestation's wall time), and the policy names the identity.
639
    /// Revoked keys authorize nothing either way.
64022×
    pub(crate) fn delegate_authorized(
64122×
        &self,
64222×
        p: &crate::policy::Policy,
64322×
        signer: &KeyId,
64422×
        reference: &str,
64522×
        at_ms: u64,
64622×
    ) -> bool {
64722×
        if p.is_revoked(signer) {
6481×
            return false;
64921×
        }
65021×
        let Some(rule) = p.rule_for(reference) else {
6510×
            return false;
652
        };
65322×
        rule.keys.iter().any(|k| {
65422×
            !p.is_revoked(k)
65522×
                && p.identity(k)
65622×
                    .cloned()
65722×
                    .or_else(|| self.store.get_identity(k).ok())
65822×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
65922×
        })
66022×
    }
661
662
    /// A lasting attestation (a tag) signed by a key the policy has since
663
    /// rotated away from (spec §14.2) is authorized as the key that
664
    /// succeeded it: a key the rule lists reaches the signer through
665
    /// `previous` links, and the attestation is dated (`at_ms`) before the
666
    /// signer's successor was made, so a superseded key makes nothing new.
667
    /// Revoked keys authorize nothing.
6686×
    pub(crate) fn predecessor_authorized(
6696×
        &self,
6706×
        p: &crate::policy::Policy,
6716×
        signer: &KeyId,
6726×
        reference: &str,
6736×
        at_ms: u64,
6746×
    ) -> bool {
6756×
        if p.is_revoked(signer) {
6760×
            return false;
6776×
        }
6786×
        let Some(rule) = p.rule_for(reference) else {
6790×
            return false;
680
        };
6817×
        let identity = |k: &KeyId| {
6827×
            p.identity(k)
6837×
                .cloned()
6847×
                .or_else(|| self.store.get_identity(k).ok())
6857×
        };
6866×
        rule.keys.iter().any(|k| {
6876×
            if p.is_revoked(k) {
6880×
                return false;
6896×
            }
6906×
            let mut cur = identity(k);
6916×
            for _ in 0..32 {
6927×
                let Some(id) = cur else {
6930×
                    return false;
694
                };
6951×
                match id.previous {
6966×
                    Some(prev) if prev == *signer => return at_ms < id.created,
6971×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
6981×
                    _ => return false,
699
                }
700
            }
7010×
            false
7026×
        })
7036×
    }
704
705114×
    fn check_ref_attest(
706114×
        &self,
707114×
        sa: &SignedAttest,
708114×
        name: &str,
709114×
        old_state: &ObjectRef,
710114×
        new_state: &ObjectRef,
711114×
        last_serial: Option<u64>,
712114×
        allow_equal: bool,
713114×
    ) -> std::result::Result<u64, String> {
714
        let AttestBody::Ref {
715114×
            name: n,
716114×
            old_state: o,
717114×
            new_state: nw,
718114×
            serial,
719114×
        } = &sa.attest.body
720
        else {
7210×
            return Err("attestation is not a ref attestation".into());
722
        };
723114×
        if n != name || o != old_state || nw != new_state {
7241×
            return Err("attestation does not describe this update".into());
725113×
        }
726113×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7270×
            return Err("attestation is for a different repository".into());
728113×
        }
729113×
        if let Some(last) = last_serial {
73068×
            if *serial < last || (*serial == last && !allow_equal) {
7311×
                return Err(format!(
7321×
                    "attestation serial {serial} is not greater than the last seen {last}"
7331×
                ));
73467×
            }
73545×
        }
736112×
        let r = sa.attest.hash();
737112×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
738112×
        let id = self
739112×
            .store
740112×
            .get_identity(&sig.key)
741112×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
742112×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
743112×
        Ok(*serial)
744114×
    }
745
746
    /// Accept a push (spec §16.4). Without a trust policy every repository
747
    /// is unverified, so unsigned changes and unattested updates are accepted;
748
    /// attestations that are present must still be valid. With a policy,
749
    /// every change and update is checked against it. A newer policy in the
750
    /// push is applied first when it is signed by the current roots.
751280×
    pub fn receive_push(
752280×
        &self,
753280×
        bundle: Bundle,
754280×
        updates: Vec<RefUpdate>,
755280×
        policy: Option<SignedPolicy>,
756280×
        tags: Vec<crate::protocol::TagRef>,
757280×
    ) -> Result<Vec<RefResult>> {
758280×
        Ok(self
759280×
            .receive_push_report(bundle, updates, policy, tags)?
760
            .results)
761280×
    }
762
763
    /// `receive_push` with what a host wants to log: each accepted
764
    /// reference's old and new state and heads, and the changes this push
765
    /// stored (hub spec §6.12).
766321×
    pub fn receive_push_report(
767321×
        &self,
768321×
        bundle: Bundle,
769321×
        updates: Vec<RefUpdate>,
770321×
        policy: Option<SignedPolicy>,
771321×
        tags: Vec<crate::protocol::TagRef>,
772321×
    ) -> Result<PushReport> {
773321×
        let mut report = PushReport::default();
774321×
        let results = &mut report.results;
775321×
        if let Some(sp) = policy {
77625×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
77723×
                Ok(()) => {
77823×
                    results.push(RefResult {
77923×
                        name: "policy".into(),
78023×
                        ok: true,
78123×
                        reason: format!("serial {}", sp.policy.serial),
78223×
                    });
78323×
                }
7842×
                Err(e) => {
7852×
                    results.push(RefResult {
7862×
                        name: "policy".into(),
7872×
                        ok: false,
7882×
                        reason: e,
7892×
                    });
7902×
                    for u in updates {
7910×
                        results.push(RefResult {
7920×
                            name: u.name,
7930×
                            ok: false,
7940×
                            reason: "policy update was rejected".into(),
7950×
                        });
7960×
                    }
7972×
                    return Ok(report);
798
                }
799
            }
800296×
        }
801319×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
802
        // A push of objects alone (one batch of a long history, oxygen#95)
803
        // names no reference: its outcome is reported as `objects`.
804319×
        let objects_only = updates.is_empty() && tags.is_empty();
805319×
        match self.import_bundle(&bundle, policy.is_some()) {
806313×
            Ok(imported) => {
807313×
                if objects_only {
8087×
                    results.push(RefResult {
8097×
                        name: OBJECTS_RESULT.into(),
8107×
                        ok: true,
8117×
                        reason: format!("{} changes stored", imported.len()),
8127×
                    });
813306×
                }
814313×
                report.imported = imported;
815
            }
8166×
            Err(e) => {
8176×
                if objects_only {
8180×
                    results.push(RefResult {
8190×
                        name: OBJECTS_RESULT.into(),
8200×
                        ok: false,
8210×
                        reason: e.to_string(),
8220×
                    });
8236×
                }
8246×
                for u in updates {
8256×
                    results.push(RefResult {
8266×
                        name: u.name,
8276×
                        ok: false,
8286×
                        reason: e.to_string(),
8296×
                    });
8306×
                }
8316×
                return Ok(report);
832
            }
833
        }
834313×
        let (op_ref, op) = self.head_op()?;
835313×
        let mut view = op.view.clone();
836313×
        let mut names = Vec::new();
837313×
        for u in updates {
838304×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
839304×
            let (ok, reason) = match outcome {
840277×
                Ok(()) => (true, String::new()),
84127×
                Err(e) => (false, e),
842
            };
843304×
            if ok {
844277×
                names.push(u.name.clone());
845277×
                let heads = self
846277×
                    .store
847277×
                    .get_state(&u.new_state)
848277×
                    .map(|s| s.heads)
849277×
                    .unwrap_or_default();
850277×
                report.updated.push(RefUpdated {
851277×
                    name: u.name.clone(),
852277×
                    old_state: u.old_state,
853277×
                    new_state: u.new_state,
854277×
                    heads,
855277×
                });
85627×
            }
857304×
            results.push(RefResult {
858304×
                name: u.name,
859304×
                ok,
860304×
                reason,
861304×
            });
862
        }
863313×
        for t in &tags {
8648×
            let name = format!("tags/{}", t.name);
8658×
            let new = !view.tags.contains_key(&t.name);
8668×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
867
                Ok(()) => {
868
                    // A tag new here is an update too, so a hub can start
869
                    // its pipeline's tag jobs (oxygenflow#24); one it
870
                    // already had, sent again, is not.
8716×
                    if new {
8726×
                        report.updated.push(RefUpdated {
8736×
                            name: name.clone(),
8746×
                            old_state: ObjectRef::ZERO,
8756×
                            new_state: t.state,
8766×
                            heads: t.heads.clone(),
8776×
                        });
8786×
                    }
8796×
                    names.push(name.clone());
8806×
                    results.push(RefResult {
8816×
                        name,
8826×
                        ok: true,
8836×
                        reason: String::new(),
8846×
                    });
885
                }
8862×
                Err(e) => results.push(RefResult {
8872×
                    name,
8882×
                    ok: false,
8892×
                    reason: e,
8902×
                }),
891
            }
892
        }
893313×
        if !names.is_empty() {
894277×
            self.record_op(
895277×
                &[op_ref],
896277×
                &format!("push received: {}", names.join(" ")),
897277×
                view,
8983×
            )?;
89936×
        }
900310×
        Ok(report)
901321×
    }
902
903
    /// Check an update's attestation against the latest one for its
904
    /// reference and store it as the new latest. Failures say what was
905
    /// being done, for which reference, so a refused push can be diagnosed
906
    /// from its reason alone.
90784×
    fn record_update_attest(
90884×
        &self,
90984×
        u: &RefUpdate,
91084×
        sa: &SignedAttest,
91184×
    ) -> std::result::Result<(), String> {
91284×
        let name = &u.name;
91384×
        let last = self
91484×
            .latest_ref_attest(name)
91584×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
91684×
            .and_then(|(_, a)| match a.attest.body {
91755×
                AttestBody::Ref { serial, .. } => Some(serial),
9180×
                _ => None,
91955×
            });
92084×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
92182×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
92282×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
92381×
        for sig in &sa.sigs {
92481×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
925
        }
92681×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
927
        // Signed by a short-lived key: a host records when it accepted it.
92878×
        let certified = sa
92978×
            .sigs
93078×
            .first()
93178×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
93278×
        if certified {
9332×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
93476×
        }
93578×
        Ok(())
93684×
    }
937
938
    /// Record that this host accepted attestation `r` now, signed with its
939
    /// acceptor key (spec §14.7); nothing without one.
9403×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
9413×
        let Some(acceptor) = &self.acceptor else {
9422×
            return Ok(());
943
        };
9441×
        let (id, sk) = (&acceptor.0, &acceptor.1);
9451×
        let attest = Attest {
9461×
            repo: self.id()?,
9471×
            hlc: Hlc::now(),
9481×
            body: AttestBody::Accepted { attest: *r },
949
        };
9501×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
9511×
        self.store.put_identity(id)?;
9521×
        let a = self.store.put_attest(&attest)?;
9531×
        self.store.put_signature(&a, &sig)?;
9541×
        self.store.index_add_pub("accepted", r, &a)?;
9551×
        Ok(())
9563×
    }
957
958
    /// The host's acceptance of attestation `r`, if one was recorded.
959127×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
960127×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
961117×
            return Ok(None);
962
        };
963
        Ok(Some(SignedAttest {
96410×
            attest: self.store.get_attest(&a)?,
96510×
            sigs: self.store.signatures(&a)?,
966
        }))
967127×
    }
968
969
    /// When a certified signer's attestation `sa` is checked on a fetch: the
970
    /// host's acceptance time, if `accepted` is signed by the issuer of the
971
    /// signer's certificate and accepts `sa`; else the attestation's own
972
    /// time, which the signer chose.
97323×
    pub(crate) fn certified_time(
97423×
        &self,
97523×
        signer: &KeyId,
97623×
        sa: &SignedAttest,
97723×
        accepted: Option<&SignedAttest>,
97823×
    ) -> u64 {
97923×
        let own = sa.attest.hlc.wall_ms;
98023×
        let Some(acc) = accepted else {
98117×
            return own;
982
        };
9836×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
9840×
            return own;
985
        };
9866×
        let Ok(cert) = self.store.get_certificate(&c) else {
9870×
            return own;
988
        };
9896×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
9900×
            return own;
991
        };
9926×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
9931×
            return own;
994
        };
9955×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
9960×
            return own;
997
        };
9985×
        if *attest == sa.attest.hash()
9994×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1000
        {
10014×
            acc.attest.hlc.wall_ms
1002
        } else {
10031×
            own
1004
        }
100523×
    }
1006
1007
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1008
    /// at `old_state`, is never the bookmark a non-bare repository has
1009
    /// checked out (a bare one's default is its host's to protect, see
1010
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1011
    /// an attestation by a key that may update it.
1012
    /// The deletion's attestation stays the bookmark's latest, so an older
1013
    /// one cannot be replayed to bring it back.
10143×
    fn apply_deletion(
10153×
        &self,
10163×
        view: &mut View,
10173×
        u: &RefUpdate,
10183×
        policy: Option<&crate::policy::Policy>,
10193×
    ) -> std::result::Result<(), String> {
10203×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
10210×
            return Err(format!("no bookmark {:?} to delete", u.name));
1022
        };
10233×
        if current != u.old_state {
10240×
            return Err("stale: the remote bookmark has moved; pull first".into());
10253×
        }
10263×
        if !self.is_bare() && u.name == self.config.bookmark {
10271×
            return Err(format!(
10281×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
10291×
                u.name
10301×
            ));
10312×
        }
10322×
        if let Some(p) = policy {
10330×
            let Some(sa) = &u.attestation else {
10340×
                return Err(format!(
10350×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
10360×
                    u.name
10370×
                ));
1038
            };
10390×
            let signer = sa
10400×
                .sigs
10410×
                .first()
10420×
                .map(|s| s.key)
10430×
                .ok_or("attestation carries no signature")?;
1044
            // Received now: the receiver's own clock is the trusted time.
10450×
            let now = Hlc::now().wall_ms;
10460×
            if !p.authorizes(&signer, &u.name)
10470×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
10480×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1049
            {
10500×
                return Err(format!(
10510×
                    "key {} may not delete {:?} under this repository's policy",
10520×
                    signer.short(12),
10530×
                    u.name
10540×
                ));
10550×
            }
10562×
        }
10572×
        if let Some(sa) = &u.attestation {
10581×
            self.record_update_attest(u, sa)?;
10591×
        }
10602×
        view.bookmarks.remove(&u.name);
10612×
        Ok(())
10623×
    }
1063
1064304×
    fn apply_update(
1065304×
        &self,
1066304×
        view: &mut View,
1067304×
        u: &RefUpdate,
1068304×
        policy: Option<&crate::policy::Policy>,
1069304×
    ) -> std::result::Result<(), String> {
1070304×
        if u.name == "policy" {
10710×
            return Err(
10720×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
10730×
            );
1074304×
        }
1075304×
        let empty = self
1076304×
            .store
1077304×
            .put_state(&StateObject::new(vec![]))
1078304×
            .map_err(|e| e.to_string())?;
1079304×
        if u.new_state.is_zero() {
10803×
            return self.apply_deletion(view, u, policy);
1081301×
        }
1082301×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1083301×
        if current != u.old_state {
108410×
            return Err("stale: the remote bookmark has moved; pull first".into());
1085291×
        }
1086291×
        let new_state = self
1087291×
            .store
1088291×
            .get_state(&u.new_state)
1089291×
            .map_err(|_| "new state object is missing".to_string())?;
1090562×
        for h in &new_state.heads {
1091562×
            if !self.store.has(h) {
10921×
                return Err(format!("head {} is missing", h.short(12)));
1093561×
            }
1094
        }
1095290×
        if !u.force {
1096289×
            let old_heads = self
1097289×
                .store
1098289×
                .get_state(&current)
1099289×
                .map_err(|e| e.to_string())?
1100
                .heads;
1101289×
            let closure = self
1102289×
                .closure_in_store(&new_state.heads)
1103289×
                .map_err(|e| e.to_string())?;
1104303×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
11051×
                return Err(format!(
11061×
                    "not a fast-forward: current head {} would be dropped (use --force)",
11071×
                    h.short(12)
11081×
                ));
1109288×
            }
11101×
        }
1111289×
        if let Some(p) = policy {
111238×
            let Some(sa) = &u.attestation else {
11131×
                return Err(format!(
11141×
                    "{:?} requires a signed reference attestation under this repository's policy",
11151×
                    u.name
11161×
                ));
1117
            };
111837×
            let signer = sa
111937×
                .sigs
112037×
                .first()
112137×
                .map(|s| s.key)
112237×
                .ok_or("attestation carries no signature")?;
1123
            // Received now: the receiver's own clock is the trusted time.
112437×
            let now = Hlc::now().wall_ms;
112537×
            if !p.authorizes(&signer, &u.name)
112611×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11279×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1128
            {
11297×
                return Err(format!(
11307×
                    "key {} may not update {:?} under this repository's policy",
11317×
                    signer.short(12),
11327×
                    u.name
11337×
                ));
113430×
            }
113530×
            let old_heads = self
113630×
                .store
113730×
                .get_state(&current)
113830×
                .map_err(|e| e.to_string())?
1139
                .heads;
114030×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1141251×
        }
1142281×
        if let Some(sa) = &u.attestation {
114383×
            self.record_update_attest(u, sa)?;
1144198×
        }
1145275×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1146275×
        Ok(())
1147304×
    }
1148
1149
    // ------------------------------------------------------------ client side
1150
1151974×
    fn remote_url(&self, name: &str) -> Result<String> {
1152974×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
11533×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
11543×
            RepoError::Msg(match names.as_slice() {
11553×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
11561×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1157
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
11581×
                    names.join(", "),
11591×
                    names[0],
11601×
                    names[0]
1161
                ),
11620×
                _ => format!(
1163
                    "no remote named {name:?}; this repository has {}",
11640×
                    names.join(", ")
1165
                ),
1166
            })
11673×
        })
1168974×
    }
1169
1170
    /// Refuse a remote that is another repository. An **unbound** remote
1171
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1172
    /// for pushes, which bind it to this repository's id (spec §16.1).
1173723×
    fn check_remote_id(
1174723×
        &self,
1175723×
        remote: &dyn crate::protocol::Remote,
1176723×
        remote_name: &str,
1177723×
        allow_unbound: bool,
1178723×
    ) -> Result<()> {
1179723×
        let theirs = remote.repo_id()?;
1180722×
        if theirs == self.id()? {
1181699×
            return Ok(());
118223×
        }
118323×
        if theirs == crate::protocol::UNBOUND_ID {
118420×
            if allow_unbound {
118519×
                return Ok(());
11861×
            }
11871×
            return fail(format!(
1188
                "remote {remote_name:?} is empty and unbound: push to it first"
1189
            ));
11903×
        }
11913×
        fail(format!(
1192
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1193
        ))
1194723×
    }
1195
1196
    /// Credentials and trust for a remote: `remote.<name>.token` and
1197
    /// `remote.<name>.ca`, else the defaults for its URL
1198
    /// ([`Repo::fill_credentials`]).
1199991×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
1200991×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
1201991×
        let mut options = RemoteOptions {
1202991×
            repo_id: self.id().ok(),
1203991×
            token: self.config.remote_tokens.get(name).cloned(),
1204991×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
1205991×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
1206991×
            ..RemoteOptions::default()
1207991×
        };
1208991×
        self.fill_credentials(&url, &mut options);
1209991×
        options
1210991×
    }
1211
1212
    /// The user's credential store (`credentials.toml` beside the user
1213
    /// configuration file).
12141010×
    pub fn credentials(&self) -> crate::credentials::Credentials {
12151010×
        crate::credentials::Credentials::at(
12161010×
            self.user_config
12171010×
                .parent()
12181010×
                .map(Path::to_path_buf)
12191010×
                .unwrap_or_else(default_home),
1220
        )
12211010×
    }
1222
1223
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1224
    /// then the user's credential store for its hub, then a remote on the
1225
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1226
    /// When the token is not this remote's own or the environment's, the
1227
    /// other tokens enclosing checkouts hold for the hub are kept to try
1228
    /// if it is refused: a stale stored login must not hide a parent's
1229
    /// good token (oxygen#112).
12301011×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
12311011×
        if options.token.is_some() && options.ca.is_some() {
12321×
            return;
12331010×
        }
12341010×
        let explicit =
12351010×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
12361010×
        let stored = self.credentials().options_for(url);
12371010×
        options.token = options.token.take().or(stored.token);
12381010×
        options.ca = options.ca.take().or(stored.ca);
12391010×
        let enclosing = self.enclosing_credentials(url);
12401010×
        if options.token.is_none() {
12411000×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
124210×
        }
12431010×
        if options.ca.is_none() {
1244945×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
124565×
        }
12461010×
        if !explicit {
12471003×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
12485×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
12492×
                    options.fallback_tokens.push(t);
12503×
                }
1251
            }
12527×
        }
12531011×
    }
1254
1255
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1256
    /// checkouts, nearest first.
12571010×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
12581010×
        let mut out = Vec::new();
12591010×
        let Some(hub) = crate::credentials::hub_of(url) else {
1260870×
            return out;
1261
        };
1262140×
        let mut at = self.root.parent();
1263568×
        while let Some(dir) = at {
1264428×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
12650×
                break;
1266
            };
1267428×
            for (key, remote_url) in &cfg {
126815×
                let Some(name) = key
126915×
                    .strip_prefix("remote.")
127015×
                    .and_then(|k| k.strip_suffix(".url"))
1271
                else {
12727×
                    continue;
1273
                };
12748×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
12751×
                    continue;
12767×
                }
12777×
                out.push((
12787×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
12797×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
12807×
                ));
1281
            }
1282428×
            at = dir.parent();
1283
        }
1284140×
        out
12851010×
    }
1286
1287
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1288
    /// no changes and no reference updates, which the receiver stores.
12890×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
12900×
        let remote = self.open_named_remote(remote_name)?;
12910×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
12920×
        let mut bundle = Bundle::default();
12930×
        for r in seals {
12940×
            let attest = self.store.get_attest(r)?;
12950×
            let sigs = self.store.signatures(r)?;
12960×
            bundle
12970×
                .attests
12980×
                .push(crate::protocol::SignedAttest { attest, sigs });
1299
        }
13000×
        let results = remote.push(bundle, vec![], None, vec![])?;
13010×
        if let Some(r) = results.iter().find(|r| !r.ok) {
13020×
            return fail(format!("{}: {}", r.name, r.reason));
13030×
        }
13040×
        Ok(())
13050×
    }
1306
1307
    /// The remote whose URL starts with `base` (a hub), if configured.
13084×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
13094×
        let base = base.trim_end_matches('/');
13104×
        self.config
13114×
            .remotes
13124×
            .iter()
13134×
            .find(|(_, url)| url.trim_end_matches('/') == base)
13144×
            .map(|(name, _)| name.clone())
13154×
    }
1316
1317
    /// Open a remote by name or, failing that, by URL with the default
1318
    /// credentials (see [`Repo::credentials_for`]).
13190×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
13200×
        if let Some(name) = self.remote_for_url(url) {
13210×
            return Ok((name.clone(), self.open_named_remote(&name)?));
13220×
        }
13230×
        let options = RemoteOptions {
13240×
            repo_id: self.id().ok(),
13250×
            ..self.credentials_for(url)
13260×
        };
13270×
        Ok((url.to_string(), open_remote(url, &options)?))
13280×
    }
1329
1330
    /// Credentials for a URL: those of the configured remote with that
1331
    /// URL, else the environment's.
13324×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
13334×
        match self.remote_for_url(url) {
13344×
            Some(name) => self.remote_options(&name),
13350×
            None => RemoteOptions {
13360×
                repo_id: self.id().ok(),
13370×
                ..self.credentials_for(url)
13380×
            },
1339
        }
13404×
    }
1341
1342974×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1343974×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1344974×
    }
1345
1346124×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1347124×
        self.oxy
1348124×
            .join("remotes")
1349124×
            .join(remote)
1350124×
            .join(format!("{bookmark}.serial"))
1351124×
    }
1352
135330×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
135430×
        fs::read_to_string(self.serial_path(remote, bookmark))
135530×
            .ok()
135630×
            .and_then(|s| s.trim().parse().ok())
135730×
    }
1358
135994×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
136094×
        let p = self.serial_path(remote, bookmark);
136194×
        fs::create_dir_all(p.parent().unwrap())?;
136294×
        write_atomic(&p, serial.to_string().as_bytes())
136394×
    }
1364
1365395×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1366395×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1367395×
    }
1368
1369
    /// The highest policy serial `remote` has ever presented.
1370353×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1371353×
        fs::read_to_string(self.policy_serial_path(remote))
1372353×
            .ok()
1373353×
            .and_then(|s| s.trim().parse().ok())
1374353×
    }
1375
137642×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
137742×
        let p = self.policy_serial_path(remote);
137842×
        fs::create_dir_all(p.parent().unwrap())?;
137942×
        write_atomic(&p, serial.to_string().as_bytes())
138042×
    }
1381
138227×
    fn lazy_dir(&self) -> PathBuf {
138327×
        self.oxy.join("lazy")
138427×
    }
1385
1386
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
13874×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
13884×
        fs::create_dir_all(self.lazy_dir())?;
13894×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
13904×
    }
1391
1392
    /// Which remote promised an absent blob, if any.
139315×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
139415×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
139515×
            .ok()
139615×
            .map(|s| s.trim().to_string())
139715×
    }
1398
1399
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
14004×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
14014×
        let Some(remote_name) = self.lazy_remote(blob) else {
14020×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1403
        };
14044×
        let remote = self.open_named_remote(&remote_name)?;
14054×
        let objects = remote.objects(&[*blob])?;
14069×
        for (ty, body) in objects {
14079×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
14089×
                self.store.put(ty, &body)?;
14090×
            }
1410
        }
14114×
        if !self.store.has(blob) {
14120×
            return fail(format!(
1413
                "{remote_name} did not send blob {}",
14140×
                blob.short(12)
1415
            ));
14164×
        }
14174×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
14184×
        Ok(())
14194×
    }
1420
1421
    /// After importing from `remote`, record every blob the changes reference
1422
    /// that the store lacks as lazily available from that remote.
14234×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
14244×
        let mut n = 0;
14254×
        for h in changes {
14264×
            let c = self.store.get_change(h)?;
142713×
            for e in &c.edits {
142813×
                if let Edit::Replace { old, new, .. } = e {
14296×
                    for b in [old, new].into_iter().flatten() {
14306×
                        if !self.store.has(b) {
14314×
                            self.register_lazy(b, remote)?;
14324×
                            n += 1;
14332×
                        }
1434
                    }
14357×
                }
1436
            }
1437
        }
14384×
        Ok(n)
14394×
    }
1440
1441
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1442353×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1443353×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1444474×
        for st in view
1445353×
            .bookmarks
1446353×
            .values()
1447353×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1448
        {
1449474×
            if let Ok(s) = self.store.get_state(st) {
1450474×
                have.extend(s.heads);
1451474×
            }
1452
        }
1453353×
        have.extend(view.workspaces.values().copied());
1454353×
        Ok(have.into_iter().collect())
1455353×
    }
1456
1457
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1458359×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1459359×
        let remote = self.open_named_remote(remote_name)?;
1460356×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1461354×
        let resp = remote.refs()?;
1462
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1463
        // and signed by roots we trust, or on first contact. A remote that
1464
        // once presented a policy may never present none or an older one:
1465
        // that is a downgrade. A remote that never presented one is
1466
        // unverified, and this fetch is checked only as far as possible.
1467353×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1468353×
        let seen = self.remote_policy_serial(remote_name);
1469353×
        let mut unverified = false;
1470353×
        match &resp.policy {
147119×
            Some(sp) => {
147219×
                if seen.is_some_and(|s| sp.policy.serial < s) {
14730×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
147419×
                }
14758×
                match &local_policy {
14768×
                    Some(l) if sp.policy.serial < l.serial => {}
14778×
                    Some(l) if sp.policy.serial == l.serial => {
14784×
                        if sp.policy.hash() != l.hash() {
14790×
                            return fail(format!(
1480
                                "{remote_name} presents a different policy with the same serial {}",
1481
                                l.serial
1482
                            ));
14834×
                        }
1484
                    }
1485
                    _ => {
148615×
                        self.adopt_policy_chain(
148715×
                            &resp.history,
148815×
                            sp,
148915×
                            &format!("oxy fetch {remote_name}"),
1490
                        )
149115×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1492
                    }
1493
                }
149419×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1495
            }
1496
            None => {
1497334×
                if seen.is_some() {
14980×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1499334×
                }
1500334×
                unverified = true;
1501
            }
1502
        }
1503353×
        let policy = if unverified {
1504334×
            None
1505
        } else {
150619×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1507
        };
1508353×
        let (op_ref, op) = self.head_op()?;
1509353×
        let mut view = op.view.clone();
1510353×
        let have = self.known_heads(&view)?;
1511353×
        let mut report = Vec::new();
1512353×
        let max_blob = self.config.max_blob;
1513360×
        for r in resp.refs {
1514360×
            let needed = {
1515360×
                let _t = crate::timing::phase("fetch: negotiate");
1516360×
                remote.negotiate(&have, &r.heads)?
1517
            };
1518360×
            let bundle = {
1519360×
                let _t = crate::timing::phase("fetch: bundle");
1520360×
                remote.fetch(&needed, max_blob)?
1521
            };
1522
            // Changes are not individually re-verified here: the bookmark's
1523
            // attestation (checked below) binds its whole state, and the
1524
            // receiver of the push verified the added changes at that time.
1525360×
            let imported = {
1526360×
                let _t = crate::timing::phase("fetch: import");
1527360×
                self.import_bundle(&bundle, false)?
1528
            };
1529360×
            if max_blob.is_some() {
15304×
                self.register_missing_blobs(&imported, remote_name)?;
1531356×
            }
1532494×
            for h in &r.heads {
1533494×
                if !self.store.has(h) {
15340×
                    return fail(format!("remote did not send head {}", h.short(12)));
1535494×
                }
1536
            }
1537360×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1538360×
            if state != r.state {
15390×
                return fail(format!(
1540
                    "remote state {} does not match its heads",
15410×
                    r.state.short(12)
1542
                ));
1543360×
            }
1544360×
            if let Some(p) = &policy {
154519×
                let Some(sa) = &r.attestation else {
15460×
                    return fail(format!(
1547
                        "{remote_name}/{} has no attestation, which its policy requires",
1548
                        r.name
1549
                    ));
1550
                };
155119×
                let signer = sa
155219×
                    .sigs
155319×
                    .first()
155419×
                    .map(|s| s.key)
155519×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1556
                // A certified signer is checked at the host's acceptance,
1557
                // when it countersigned one; else at the attestation's time.
155819×
                let at = self.certified_time(&signer, sa, r.accepted.as_ref());
155919×
                if !p.authorizes(&signer, &r.name)
15608×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
15618×
                    && !self.certified_authorized(p, &signer, &r.name, Scope::REFS, at)
1562
                {
15630×
                    return fail(format!(
1564
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1565
                        r.name,
15660×
                        signer.short(12)
1567
                    ));
156819×
                }
1569341×
            }
1570360×
            if let Some(sa) = &r.attestation {
1571
                let AttestBody::Ref {
157230×
                    old_state,
157330×
                    new_state,
1574
                    ..
157530×
                } = &sa.attest.body
1576
                else {
15770×
                    return fail("remote sent a non-ref attestation for a bookmark");
1578
                };
157930×
                let (old_state, new_state) = (*old_state, *new_state);
158030×
                let serial = self
158130×
                    .check_ref_attest(
158230×
                        sa,
158330×
                        &r.name,
158430×
                        &old_state,
158530×
                        &new_state,
158630×
                        self.last_seen_serial(remote_name, &r.name),
1587
                        true,
1588
                    )
158930×
                    .map_err(|e| {
15900×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
15910×
                    })?;
159230×
                if new_state != r.state {
15930×
                    return fail(format!(
1594
                        "attestation for {}/{} does not cover its current state",
1595
                        remote_name, r.name
1596
                    ));
159730×
                }
159830×
                let ar = self.store.put_attest(&sa.attest)?;
159930×
                for sig in &sa.sigs {
160030×
                    self.store.put_signature(&ar, sig)?;
1601
                }
160230×
                self.record_serial(remote_name, &r.name, serial)?;
1603330×
            }
1604360×
            view.remotes
1605360×
                .entry(remote_name.to_string())
1606360×
                .or_default()
1607360×
                .insert(r.name.clone(), state);
1608360×
            report.push((r.name, r.heads, imported.len()));
1609
        }
1610353×
        let mut new_tags = 0;
1611353×
        for t in &resp.tags {
161213×
            if view.tags.contains_key(&t.name) {
16134×
                continue;
16149×
            }
1615
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
16169×
            let missing: Vec<ChangeHash> = t
16179×
                .heads
16189×
                .iter()
16199×
                .filter(|h| !self.store.has(h))
16209×
                .copied()
16219×
                .collect();
16229×
            if !missing.is_empty() {
16230×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
16240×
                let bundle = remote.fetch(&needed, max_blob)?;
16250×
                self.import_bundle(&bundle, false)?;
16269×
            }
16279×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
16289×
            self.adopt_tag(&mut view, t, policy.as_ref())
16299×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
16309×
            new_tags += 1;
1631
        }
1632353×
        if view != op.view {
1633342×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
163411×
        }
1635353×
        let _ = self.run_hook(
1636353×
            "post-fetch",
1637353×
            &format!(
1638
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1639353×
                json_str(remote_name),
1640360×
                json_array(report.iter().map(|(n, heads, _)| format!(
1641
                    "{{\"name\":{},\"heads\":{}}}",
1642360×
                    json_str(n),
1643494×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1644
                )))
1645
            ),
1646
        );
1647353×
        Ok(FetchReport {
1648353×
            refs: report,
1649353×
            unverified,
1650353×
            new_tags,
1651353×
        })
1652359×
    }
1653
1654
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1655
    /// the changes within `depth` steps of its heads, and the boundary below.
16561×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
16571×
        let remote = self.open_named_remote(remote_name)?;
16581×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
16591×
        let resp = remote.refs()?;
16601×
        let bookmark = self.config.bookmark.clone();
16611×
        if let Some(sp) = &resp.policy {
16620×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
16630×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
16640×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
16651×
        }
16661×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
16670×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1668
        };
16691×
        if r.heads.is_empty() {
16700×
            return Ok(0);
16711×
        }
1672
        // Base: the remote's checkpoint of exactly these heads.
16731×
        let cp_bundle = remote.checkpoint(&r.heads)?;
16741×
        let mut cp_ref = None;
16753×
        for (ty, body) in &cp_bundle.objects {
16763×
            let put = self.store.put(*ty, body)?;
16773×
            if *ty == ObjectType::Checkpoint {
16781×
                cp_ref = Some(put);
16792×
            }
1680
        }
16811×
        let Some(cp_ref) = cp_ref else {
16820×
            return fail(format!("{remote_name} sent no checkpoint"));
1683
        };
16841×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1685
        // History window.
16861×
        let wanted = remote.shallow(&r.heads, depth)?;
16871×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
16881×
        let imported = self.import_bundle_shallow(&bundle, false)?;
16891×
        if self.config.max_blob.is_some() {
16900×
            self.register_missing_blobs(&imported, remote_name)?;
16911×
        }
16921×
        self.refresh_boundary(&imported)?;
16931×
        if let Some(sa) = &r.attestation {
16940×
            let ar = self.store.put_attest(&sa.attest)?;
16950×
            for sig in &sa.sigs {
16960×
                self.store.put_signature(&ar, sig)?;
1697
            }
16980×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
16990×
                self.record_serial(remote_name, &r.name, serial)?;
17000×
            }
17011×
        }
17021×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
17031×
        let (op_ref, op) = self.head_op()?;
17041×
        let mut view = op.view.clone();
17051×
        view.remotes
17061×
            .entry(remote_name.to_string())
17071×
            .or_default()
17081×
            .insert(r.name.clone(), state);
17091×
        self.record_op(
17101×
            &[op_ref],
17111×
            &format!("oxy fetch {remote_name} --depth {depth}"),
17121×
            view,
17130×
        )?;
17141×
        Ok(imported.len())
17151×
    }
1716
1717
    /// Fetch, then take the union of the local bookmark's state with the
1718
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1719104×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1720104×
        let _wc = self.lock_working_copy()?;
1721104×
        self.fetch(remote_name)?;
1722101×
        let (op_ref, op) = self.head_op()?;
1723101×
        let current = self.config.bookmark.clone();
1724101×
        let mut local_current = self.heads_of(&op.view, &current)?;
1725101×
        local_current.sort();
1726101×
        let mut view = op.view.clone();
1727101×
        let mut current_heads = local_current.clone();
1728101×
        let mut changed = false;
1729101×
        let mut others = Vec::new();
1730101×
        let tracked = op
1731101×
            .view
1732101×
            .remotes
1733101×
            .get(remote_name)
1734101×
            .cloned()
1735101×
            .unwrap_or_default();
1736105×
        for (name, remote_state) in tracked {
1737
            // Every local bookmark tracks the remote's of the same name;
1738
            // the current one may be new here.
1739105×
            let local_state = op.view.bookmarks.get(&name).copied();
1740105×
            if local_state.is_none() && name != current {
17410×
                continue;
1742105×
            }
1743105×
            if local_state == Some(remote_state) {
17449×
                continue;
174596×
            }
174696×
            let local = self.heads_of(&op.view, &name)?;
174796×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1748121×
            if remote_heads.iter().all(|h| local.contains(h)) {
17490×
                continue;
175096×
            }
175196×
            let mut all = local.clone();
175296×
            all.extend(remote_heads);
175396×
            let st = self.load_state_history(&all)?;
175496×
            let mut heads = st.maximal(&all);
175596×
            heads.sort();
175696×
            let mut sorted_local = local;
175796×
            sorted_local.sort();
175896×
            if heads == sorted_local {
17591×
                continue;
176095×
            }
176195×
            view.bookmarks.insert(
176295×
                name.clone(),
176395×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1764
            );
176595×
            if name == current {
176693×
                changed = true;
176793×
                current_heads = heads;
176893×
            } else {
17692×
                others.push(name);
17702×
            }
1771
        }
1772101×
        if changed || !others.is_empty() {
177394×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
17747×
        }
1775
        // The working copy follows its bookmark whenever nothing would be
1776
        // lost, also when this pull brought nothing new but it had been
1777
        // left behind (oxygen#89).
1778101×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1779
        Ok(PullReport {
1780101×
            heads: if changed {
178193×
                current_heads
1782
            } else {
17838×
                local_current
1784
            },
1785101×
            changed,
1786101×
            checked_out,
1787101×
            others,
1788
        })
1789104×
    }
1790
1791
    /// How many changes the working copy's bookmark has that its base
1792
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1793
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1794
    /// the bookmark or holds changes the bookmark lacks. History is read
1795
    /// only when the base and the bookmark's heads differ (oxygen#89).
17967×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
17977×
        let (_, wc) = self.working_copy()?;
17987×
        let mut base = wc.deps.clone();
17997×
        base.sort();
18007×
        let mut heads = self.bookmark_heads()?;
18017×
        heads.sort();
18027×
        if base == heads || heads.is_empty() {
18036×
            return Ok(None);
18041×
        }
18051×
        let state = self.load_state_history(&heads)?;
18061×
        if !base.iter().all(|h| state.contains(h)) {
18070×
            return Ok(None);
18081×
        }
18091×
        let had = if base.is_empty() {
18100×
            0
1811
        } else {
18121×
            self.load_state_history(&base)?.len()
1813
        };
18141×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
18157×
    }
1816
1817
    /// Bring the working copy to `heads`, the state of its bookmark
1818
    /// `bookmark`, when nothing would be lost: its base is part of that
1819
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1820
    /// with uncommitted work, the work comes along when the new changes
1821
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1822
    /// it followed only from exactly the bookmark's old heads, so a working
1823
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1824
    /// or a pull from another workspace) never caught up, and nothing said
1825
    /// so (oxygen#74, #89). Returns whether it moved.
1826101×
    pub fn follow_bookmark(
1827101×
        &self,
1828101×
        heads: &[ChangeHash],
1829101×
        bookmark: &str,
1830101×
        command: &str,
1831101×
    ) -> Result<bool> {
1832101×
        let snap = self.snapshot(command)?;
1833101×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1834101×
        let mut base = snap.base.maximal(&snap.wc.deps);
1835101×
        base.sort();
1836101×
        let mut target = heads.to_vec();
1837101×
        target.sort();
1838101×
        if base == target {
18397×
            return Ok(false);
184094×
        }
184194×
        let state = self.load_state_history(heads)?;
1842178×
        if !base.iter().all(|h| state.contains(h)) {
1843
            // The working copy holds changes the bookmark lacks: not ours to move.
18440×
            return Ok(false);
184594×
        }
184694×
        if clean {
184794×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
184894×
            Ok(true)
1849
        } else {
18500×
            Ok(self
18510×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
18520×
                .is_ok())
1853
        }
1854101×
    }
1855
1856
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1857
    /// changes and attesting the reference when a key is available.
1858
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1859
    /// state, attested when we have an identity. The local bookmark, if
1860
    /// any, is kept; only the remote-tracking entry goes.
18615×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
18625×
        let remote = self.open_named_remote(remote_name)?;
18635×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
18645×
        let resp = remote.refs()?;
18657×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
18661×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1867
        };
18684×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
18690×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
18704×
        }
18714×
        let attestation = match self.secret_key()? {
18722×
            Some(_) => Some(self.sign_attest(&Attest {
18732×
                repo: self.id()?,
18742×
                hlc: Hlc::now(),
18752×
                body: AttestBody::Ref {
18762×
                    name: bookmark.to_string(),
18772×
                    old_state: r.state,
18782×
                    new_state: ObjectRef::ZERO,
18792×
                    serial: r.last_serial.unwrap_or(0) + 1,
18802×
                },
18810×
            })?),
18822×
            None => None,
1883
        };
18844×
        let results = remote.push(
18854×
            Bundle::default(),
18864×
            vec![RefUpdate {
18874×
                name: bookmark.to_string(),
18884×
                old_state: r.state,
18894×
                new_state: ObjectRef::ZERO,
18904×
                force: true,
18914×
                attestation,
18924×
            }],
18934×
            None,
18944×
            vec![],
18950×
        )?;
18964×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
18972×
            let (op_ref, op) = self.head_op()?;
18982×
            let mut view = op.view.clone();
18992×
            if let Some(m) = view.remotes.get_mut(remote_name) {
19002×
                m.remove(bookmark);
19012×
            }
19022×
            self.record_op(
19032×
                &[op_ref],
19042×
                &format!("oxy push {remote_name} --delete {bookmark}"),
19052×
                view,
19060×
            )?;
19072×
        }
19084×
        Ok(results)
19095×
    }
1910
1911
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1912
    /// repository's config (its URL, token, CA and store settings), its
1913
    /// tracking bookmarks in the view, and a store remote's mirror under
1914
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
19153×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
19163×
        if !self.config.remotes.contains_key(name) {
19171×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
19182×
        }
19192×
        let prefix = format!("remote.{name}.");
19202×
        let keys: Vec<String> = self
19212×
            .config
19222×
            .repo_layer()
19232×
            .keys()
19244×
            .filter(|k| k.starts_with(&prefix))
19252×
            .cloned()
19262×
            .collect();
19273×
        for k in keys {
19283×
            self.config.set(&k, "")?;
1929
        }
19302×
        self.config.remotes.remove(name);
19312×
        self.save_config()?;
19322×
        let (op_ref, op) = self.head_op()?;
19332×
        if op.view.remotes.contains_key(name) {
19341×
            let mut view = op.view.clone();
19351×
            view.remotes.remove(name);
19361×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
19371×
        }
19382×
        let mirror = self.oxy.join("remotes").join(name);
19392×
        if mirror.is_dir() {
19400×
            fs::remove_dir_all(&mirror)?;
19412×
        }
19422×
        Ok(())
19433×
    }
1944
1945
    /// `changes`, in dependency order, cut into batches of about
1946
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1947
    /// There is always one, perhaps empty.
1948284×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1949284×
        let blob_len = |r: &ObjectRef| -> u64 {
195029×
            self.store
195129×
                .get_typed(r, ObjectType::Blob)
195229×
                .ok()
195329×
                .and_then(|b| Blob::decode(&b).ok())
195429×
                .map_or(0, |b| b.length)
195529×
        };
1956284×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1957385×
        for h in changes {
1958385×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1959385×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1960385×
            let mut weight = raw.len() as u64;
1961485×
            for t in &texts {
1962485×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
196326×
                    weight += blob_len(r);
1964459×
                }
1965
            }
1966601×
            for e in &c.edits {
19673×
                if let Edit::Replace { new: Some(b), .. } = e {
19683×
                    weight += blob_len(b);
1969598×
                }
1970
            }
1971385×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
19725×
                out.push(std::mem::take(&mut batch));
19735×
                bytes = 0;
1974380×
            }
1975385×
            batch.push(*h);
1976385×
            bytes += weight;
1977
        }
1978284×
        out.push(batch);
1979284×
        Ok(out)
1980284×
    }
1981
1982346×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1983346×
        let bookmark = self.config.bookmark.clone();
1984346×
        self.push_bookmark(remote_name, &bookmark, force)
1985346×
    }
1986
1987
    /// `push` for a named bookmark (`oxy push -b NAME`).
1988354×
    pub fn push_bookmark(
1989354×
        &self,
1990354×
        remote_name: &str,
1991354×
        bookmark: &str,
1992354×
        force: bool,
1993354×
    ) -> Result<Vec<RefResult>> {
1994354×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1995354×
    }
1996
1997
    /// `push_bookmark`, saying how a long push is going: one line per
1998
    /// batch sent (oxygen#95).
1999362×
    pub fn push_bookmark_with(
2000362×
        &self,
2001362×
        remote_name: &str,
2002362×
        bookmark: &str,
2003362×
        force: bool,
2004362×
        progress: crate::store::Progress,
2005362×
    ) -> Result<Vec<RefResult>> {
2006362×
        let (op_ref, op) = self.head_op()?;
2007362×
        if !op.view.bookmarks.contains_key(bookmark) {
20080×
            return fail(format!("no bookmark {bookmark}"));
2009362×
        }
2010362×
        let bookmark = bookmark.to_string();
2011362×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2012
        // pre-push hook: may veto before the remote is contacted.
2013362×
        self.run_hook(
2014362×
            "pre-push",
2015362×
            &format!(
2016
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2017362×
                json_str(remote_name),
2018362×
                json_str(&bookmark),
2019725×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2020
            ),
20211×
        )?;
2022361×
        let remote = self.open_named_remote(remote_name)?;
2023361×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2024358×
        let resp = remote.refs()?;
2025358×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2026358×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2027358×
        let policy_to_send = match (&local_policy, &resp.policy) {
202829×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
202910×
            (Some(l), None) => Some(l.clone()),
203016×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
20311×
                return fail(format!(
2032
                    "{remote_name} has a newer policy (serial {}); fetch first",
2033
                    r.policy.serial
2034
                ));
2035
            }
2036334×
            _ => None,
2037
        };
2038357×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2039357×
        if remote_has_policy && self.secret_key()?.is_none() {
20401×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2041356×
        }
2042356×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2043356×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2044356×
            .tag_refs()?
2045356×
            .into_iter()
2046356×
            .filter(|t| !remote_tags.contains(&t.name))
2047356×
            .collect();
2048356×
        let refs = resp.refs;
2049356×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2050356×
        let (remote_state, remote_heads, last_serial) =
2051356×
            match refs.iter().find(|r| r.name == bookmark) {
2052339×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
205317×
                None => (empty, vec![], None),
2054
            };
2055356×
        let new_state = self
2056356×
            .store
2057356×
            .put_state(&StateObject::new(local_heads.clone()))?;
2058
        // A push that carries a policy re-attests the bookmark even when its
2059
        // state is unchanged, so the current attestation is always by a key
2060
        // the current policy authorizes (a revoked key's attestation would
2061
        // otherwise be refused by every later fetch).
2062356×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
20637×
            return Ok(vec![RefResult {
20647×
                name: bookmark,
20657×
                ok: true,
20667×
                reason: "already up to date".into(),
20677×
            }]);
2068349×
        }
2069383×
        for h in &remote_heads {
2070383×
            if !self.store.has(h) {
207164×
                return fail(format!(
2072
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
207364×
                    h.short(12)
2074
                ));
2075319×
            }
2076
        }
2077285×
        if !force {
2078285×
            let closure = self.closure_in_store(&local_heads)?;
2079300×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
20800×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2081285×
            }
20820×
        }
2083285×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2084285×
        let key = self.secret_key()?.map(|(k, _)| k);
2085285×
        if let Some(key) = key {
2086
            // Seal this author's changes that carry no valid authenticator,
2087
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2088
            // are stored, so each batch's bundle carries those it needs.
208987×
            let mut unsigned = Vec::new();
209087×
            for h in &to_send {
209179×
                let c = self.store.get_change_meta(h)?;
209279×
                if self.seals_for_author(&c.author, &key)
209376×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
209447×
                {
209547×
                    unsigned.push(*h);
209647×
                }
2097
            }
209887×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
209944×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2100
            }
2101198×
        }
2102
        // A long history goes in batches, in dependency order, so neither
2103
        // side holds it whole and no request passes the remote's limit:
2104
        // all but the last carry objects alone; the last moves the bookmark
2105
        // (oxygen#95).
2106284×
        let batches = self.push_batches(&to_send)?;
2107284×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2108284×
        for (i, batch) in earlier.iter().enumerate() {
21095×
            progress(&format!(
21105×
                "part {} of {}: {} changes",
21115×
                i + 1,
21125×
                batches.len(),
21135×
                batch.len()
21145×
            ));
21155×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
21165×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
21175×
                Some(r) if r.ok => {}
21180×
                Some(r) => {
21190×
                    return fail(format!(
2120
                        "{remote_name} refused part {} of the push: {}",
21210×
                        i + 1,
2122
                        r.reason
2123
                    ))
2124
                }
2125
                None => {
21260×
                    return fail(format!(
2127
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2128
                    ))
2129
                }
2130
            }
2131
        }
2132284×
        if batches.len() > 1 {
21331×
            progress(&format!(
21341×
                "part {} of {}: {} changes",
21351×
                batches.len(),
21361×
                batches.len(),
21371×
                last.len()
21381×
            ));
2139283×
        }
2140284×
        let mut bundle = self.bundle_for(last)?;
2141284×
        bundle.objects.push((
2142284×
            ObjectType::State,
2143284×
            StateObject::new(local_heads.clone()).encode(),
2144284×
        ));
2145284×
        let attestation = match key {
214686×
            Some(_) => Some(self.sign_attest(&Attest {
214786×
                repo: self.id()?,
214886×
                hlc: Hlc::now(),
214986×
                body: AttestBody::Ref {
215086×
                    name: bookmark.clone(),
215186×
                    old_state: remote_state,
215286×
                    new_state,
215386×
                    serial: next_serial(last_serial),
215486×
                },
21551×
            })?),
2156198×
            None => None,
2157
        };
2158
        // Whoever signed the move, and whom a delegate acts for, travel with
2159
        // it: a receiver that has never seen a change by this delegate could
2160
        // not otherwise check its signature (oxygenhub#129).
2161283×
        if attestation.is_some() {
2162170×
            for k in [self.signing_key(), self.config.author_key]
216385×
                .into_iter()
216485×
                .flatten()
2165
            {
2166170×
                if let Ok(id) = self.identity(&k) {
2167170×
                    let body = id.encode();
2168170×
                    if !bundle
2169170×
                        .objects
2170170×
                        .iter()
2171197×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
217217×
                    {
217317×
                        bundle.objects.push((ObjectType::Identity, body));
2174153×
                    }
21750×
                }
2176
            }
2177
            // A short-lived signing key's certificate goes with it (§14.7).
217885×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
217985×
            self.attach_certificates_for(&mut bundle, &signers)?;
2180198×
        }
2181283×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
218285×
            AttestBody::Ref { serial, .. } => Some(serial),
21830×
            _ => None,
218485×
        });
2185283×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2186
        // Tag states must be present on the remote: bundle their changes too.
2187283×
        for t in &tags_to_send {
21886×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
21896×
            let extra: Vec<ChangeHash> =
21906×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
21916×
            if !extra.is_empty() {
21920×
                let more = self.bundle_for(&extra)?;
21930×
                bundle.changes.extend(more.changes);
21940×
                bundle.hashes.extend(more.hashes);
21950×
                bundle.attests.extend(more.attests);
21960×
                bundle.objects.extend(more.objects);
21976×
            }
21986×
            bundle.objects.push((
21996×
                ObjectType::State,
22006×
                StateObject::new(t.heads.clone()).encode(),
22016×
            ));
2202
        }
2203283×
        if let Some(l) = &policy_to_send {
220423×
            let remote_serial = resp_policy_serial;
220523×
            bundle.policies = self
220623×
                .policy_history()?
220723×
                .into_iter()
220850×
                .filter(|sp| {
220950×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
221025×
                        && sp.policy.serial < l.policy.serial
221150×
                })
221223×
                .collect();
2213260×
        }
2214283×
        let results = remote.push(
2215283×
            bundle,
2216283×
            vec![RefUpdate {
2217283×
                name: bookmark.clone(),
2218283×
                old_state: remote_state,
2219283×
                new_state,
2220283×
                force,
2221283×
                attestation,
2222283×
            }],
2223283×
            policy_to_send,
2224283×
            tags_to_send,
22257×
        )?;
222623×
        if let (Some(serial), true) = (
2227276×
            sent_serial,
2228282×
            results.iter().any(|r| r.ok && r.name == "policy"),
2229
        ) {
223023×
            self.record_policy_serial(remote_name, serial)?;
2231253×
        }
2232299×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2233252×
            let mut view = op.view.clone();
2234252×
            view.remotes
2235252×
                .entry(remote_name.to_string())
2236252×
                .or_default()
2237252×
                .insert(bookmark.clone(), new_state);
2238252×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2239249×
            if let Some(s) = serial {
224064×
                self.record_serial(remote_name, &bookmark, s)?;
2241185×
            }
224224×
        }
2243271×
        Ok(results)
2244362×
    }
2245
2246
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2247
    /// bookmark set to the remote's, working copy checked out.
2248231×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2249231×
        Self::clone_with(url, dest, None, &[])
2250231×
    }
2251
2252
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2253
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2254
    /// unless a size is given, so out-of-scope binaries are never fetched).
2255239×
    pub fn clone_with(
2256239×
        url: &str,
2257239×
        dest: &Path,
2258239×
        max_blob: Option<u64>,
2259239×
        sparse: &[String],
2260239×
    ) -> Result<Repo> {
2261239×
        Self::clone_full(url, dest, max_blob, sparse, None)
2262239×
    }
2263
2264
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2265
    /// changes within `depth` steps of them; the rest is the boundary.
22661×
    pub fn clone_shallow(
22671×
        url: &str,
22681×
        dest: &Path,
22691×
        depth: u32,
22701×
        max_blob: Option<u64>,
22711×
        sparse: &[String],
22721×
    ) -> Result<Repo> {
22731×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
22741×
    }
2275
2276240×
    fn clone_full(
2277240×
        url: &str,
2278240×
        dest: &Path,
2279240×
        max_blob: Option<u64>,
2280240×
        sparse: &[String],
2281240×
        depth: Option<u32>,
2282240×
    ) -> Result<Repo> {
2283240×
        let options = crate::credentials::Credentials::user().options_for(url);
2284240×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2285240×
    }
2286
2287
    /// Clone a subrepo with the credentials the parent would use for its
2288
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2289
    /// subrepo: it finds the same ones again through its parent.
22909×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
22919×
        let options = self.credentials_for(url);
22929×
        Self::clone_using(url, dest, None, &[], None, &options)
22939×
    }
2294
2295
    /// The name of a remote of this repository on the same hub (scheme,
2296
    /// host and port) as `url`.
229721×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
229825×
        let origin = |u: &str| -> Option<String> {
229925×
            let (scheme, rest) = u.split_once("://")?;
23008×
            if !matches!(scheme, "http" | "https") {
23010×
                return None;
23028×
            }
23038×
            let host = rest.split('/').next()?;
23048×
            Some(format!(
23058×
                "{}://{}",
23068×
                scheme.to_ascii_lowercase(),
23078×
                host.to_ascii_lowercase()
23088×
            ))
230925×
        };
231021×
        let want = origin(url)?;
23114×
        self.config
23124×
            .remotes
23134×
            .iter()
23144×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
23154×
            .map(|(name, _)| name.clone())
231621×
    }
2317
2318
    /// The token and CA to reach `url` with: those of a remote of this
2319
    /// repository on the same hub (scheme, host and port), else the
2320
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2321
    /// and enclosing checkouts', as a clone would use them.
232221×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
232321×
        match self.remote_on_same_hub(url) {
23241×
            Some(name) => RemoteOptions {
23251×
                repo_id: None,
23261×
                cache_dir: None,
23271×
                ..self.remote_options(&name)
23281×
            },
2329
            None => {
233020×
                let mut options = RemoteOptions::default();
233120×
                self.fill_credentials(url, &mut options);
233220×
                options
2333
            }
2334
        }
233521×
    }
2336
2337249×
    fn clone_using(
2338249×
        url: &str,
2339249×
        dest: &Path,
2340249×
        max_blob: Option<u64>,
2341249×
        sparse: &[String],
2342249×
        depth: Option<u32>,
2343249×
        options: &RemoteOptions,
2344249×
    ) -> Result<Repo> {
2345249×
        let remote = open_remote(url, options)?;
2346249×
        let id = remote.repo_id()?;
2347245×
        if id == crate::protocol::UNBOUND_ID {
23482×
            return fail(format!(
2349
                "{url} is empty and unbound: push a repository to it first"
2350
            ));
2351243×
        }
2352243×
        let mut repo = Repo::init_with_id(dest, id)?;
2353243×
        repo.config
2354243×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2355243×
        if let Some(m) = max_blob {
23562×
            repo.config.set("filter.max-blob", &m.to_string())?;
2357241×
        } else if !sparse.is_empty() {
23581×
            repo.config.set("filter.max-blob", "0")?;
2359240×
        }
2360243×
        if !sparse.is_empty() {
23611×
            repo.config.set("filter.paths", &sparse.join(","))?;
2362242×
        }
2363243×
        repo.save_config()?;
2364243×
        if let Some(depth) = depth {
23651×
            repo.fetch_shallow("origin", depth)?;
2366
        } else {
2367242×
            repo.fetch("origin")?;
2368
        }
2369242×
        let (op_ref, op) = repo.head_op()?;
2370
        // The remote's default bookmark, else ours (main), else its only one.
2371242×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2372
        // Asked of the remote as now configured, so a store-backed one
2373
        // answers from the mirror the fetch just filled.
2374242×
        let advertised = repo
2375242×
            .open_named_remote("origin")
2376242×
            .ok()
2377242×
            .and_then(|r| r.refs().ok())
2378242×
            .and_then(|r| r.default_bookmark);
2379242×
        let bookmark = advertised
2380242×
            .filter(|b| theirs.contains_key(b))
2381242×
            .or_else(|| {
23827×
                theirs
23837×
                    .contains_key(&repo.config.bookmark)
23847×
                    .then(|| repo.config.bookmark.clone())
23857×
            })
2386242×
            .or_else(|| {
23870×
                (theirs.len() == 1)
23880×
                    .then(|| theirs.keys().next().cloned())
23890×
                    .flatten()
23900×
            })
2391242×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2392242×
        let initial = repo.config.bookmark.clone();
2393242×
        if bookmark != repo.config.bookmark {
23941×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
23951×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
23961×
            repo.config.bookmark = bookmark.clone();
2397241×
        }
2398242×
        if let Some(state) = theirs.get(&bookmark).copied() {
2399242×
            let heads = repo.store.get_state(&state)?.heads;
2400242×
            let mut view = op.view.clone();
2401
            // The empty bookmark `init` made goes when another is checked out.
2402242×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
24031×
                view.bookmarks.remove(&initial);
2404241×
            }
2405242×
            view.bookmarks.insert(bookmark, state);
2406242×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2407242×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
24080×
        }
2409242×
        Ok(repo)
2410249×
    }
2411
}
2412
2413
/// The serial of a reference's next attestation: one more than the last the
2414
/// remote reports, or, for a bookmark the remote does not have, the clock in
2415
/// milliseconds, so a bookmark created again after a deletion goes past the
2416
/// deletion's serial the remote keeps.
241786×
fn next_serial(last: Option<u64>) -> u64 {
241886×
    match last {
241956×
        Some(l) => l + 1,
242030×
        None => Hlc::now().wall_ms.max(1),
2421
    }
242286×
}