OXYGENHUB

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

1719 of 1928 lines run, 251 of 362 functions · run #318 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
541335×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551335×
        self.oxy.join("attest").join(name_file(bookmark))
561335×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591251×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601251×
        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
            }
721016×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751251×
    }
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
821026×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
831026×
        let view = self.view()?;
841026×
        let mut out = Vec::new();
851048×
        for (name, state) in &view.bookmarks {
861048×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
871048×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88136×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90136×
            });
911048×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
921048×
            let accepted = match &attestation {
93125×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
94923×
                None => None,
95
            };
961048×
            out.push(RemoteRef {
971048×
                name: name.clone(),
981048×
                state: *state,
991048×
                heads: self.store.get_state(state)?.heads,
1001048×
                attestation,
1011048×
                last_serial,
1021048×
                accepted,
103
            });
104
        }
1051026×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1061026×
        let history = self
1071026×
            .policy_history()?
1081026×
            .into_iter()
1091026×
            .filter(|sp| {
110126×
                policy
111126×
                    .as_ref()
112126×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
113126×
            })
1141026×
            .collect();
115
        Ok(RefsResponse {
1161026×
            refs: out,
1171026×
            policy,
1181026×
            tags: self.tag_refs()?,
1191026×
            history,
1201026×
            default_bookmark: Some(self.config.bookmark.clone()),
121
        })
1221026×
    }
123
124
    /// Every change reachable from `heads` that is in the store.
1251363×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1261363×
        let mut seen = BTreeSet::new();
1271363×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1284756×
        while let Some(h) = stack.pop() {
1293393×
            if seen.contains(&h) || !self.store.has(&h) {
1301002×
                continue;
1312391×
            }
1322391×
            seen.insert(h);
1332391×
            stack.extend(self.store.get_change_meta(&h)?.deps);
134
        }
1351363×
        Ok(seen)
1361363×
    }
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
1631953×
    fn shallow_path(&self) -> PathBuf {
1641953×
        self.oxy.join("shallow")
1651953×
    }
166
167
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1681950×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1691950×
        fs::read_to_string(self.shallow_path())
1701950×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1711950×
            .unwrap_or_default()
1721950×
    }
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).
223779×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
224779×
        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.
227779×
        let boundary = self.boundary();
228779×
        let mut out = Vec::new();
229779×
        let mut done: BTreeSet<ChangeHash> = have.clone();
230779×
        done.extend(boundary.iter().copied());
231
        // Iterative post-order DFS.
2321243×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2333303×
        while let Some((h, expanded)) = stack.pop() {
2342524×
            if done.contains(&h) {
235406×
                continue;
2362118×
            }
2372118×
            if !self.store.has(&h) {
2380×
                return fail(format!("change {} is not in this repository", h.short(12)));
2392118×
            }
2402118×
            if expanded {
2411059×
                done.insert(h);
2421059×
                out.push(h);
2431059×
                continue;
2441059×
            }
2451059×
            stack.push((h, true));
2461059×
            for d in self.store.get_change_meta(&h)?.deps {
247753×
                if !done.contains(&d) {
248222×
                    stack.push((d, false));
249531×
                }
250
            }
251
        }
252779×
        Ok(out)
253779×
    }
254
255
    /// Bundle changes (in the given dependency order) with their signatures,
256
    /// seals, identities, blobs, chunks.
257309×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
258309×
        self.bundle_for_filtered(changes, None)
259309×
    }
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).
284355×
    pub fn bundle_for_filtered(
285355×
        &self,
286355×
        changes: &[ChangeHash],
287355×
        max_blob: Option<u64>,
288355×
    ) -> Result<Bundle> {
289355×
        self.bundle_of(changes, max_blob, false)
290355×
    }
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.
296329×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
297329×
        self.bundle_of(changes, max_blob, true)
298329×
    }
299
300684×
    fn bundle_of(
301684×
        &self,
302684×
        changes: &[ChangeHash],
303684×
        max_blob: Option<u64>,
304684×
        raw: bool,
305684×
    ) -> Result<Bundle> {
306684×
        let mut bundle = Bundle::default();
307684×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
308684×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3091091×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3101091×
            if !r.is_zero() && self.store.has(r) {
311219×
                objects.insert(*r);
312872×
            }
3131091×
        };
314984×
        for h in changes {
315
            // Raw: the stored bytes, and a skeleton for the rest.
316984×
            let (c, encoded) = if raw {
317527×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
318527×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3195016×
                for t in texts {
3205016×
                    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);
3245013×
                    }
325
                }
326527×
                (skel, Some(bytes))
327
            } else {
328457×
                (self.store.get_change(h)?, None)
329
            };
330984×
            let sigs = self.store.signatures(h)?;
331984×
            add_object(&c.author, &mut objects);
332984×
            for s in &sigs {
33322×
                add_object(&s.key, &mut objects);
33422×
            }
3356060×
            for e in &c.edits {
3366060×
                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
                    }
3506048×
                }
351
            }
352984×
            for s in self.store.seals_for(h)? {
35390×
                seals.insert(s);
35490×
            }
355984×
            match encoded {
356527×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
357457×
                None => {
358457×
                    bundle.changes.push((c, sigs));
359457×
                    bundle.hashes.push(*h);
360457×
                }
361
            }
362
        }
363684×
        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
        }
371684×
        for r in objects {
372134×
            let (ty, body) = self.store.get(&r)?;
373134×
            bundle.objects.push((ty, body));
374
        }
375684×
        self.attach_certificates(&mut bundle)?;
376684×
        Ok(bundle)
377684×
    }
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).
383769×
    pub(crate) fn attach_certificates_for(
384769×
        &self,
385769×
        bundle: &mut Bundle,
386769×
        also: &[KeyId],
387769×
    ) -> Result<()> {
388769×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
389769×
        keys.extend(
390769×
            bundle
391769×
                .changes
392769×
                .iter()
393769×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
394
        );
395769×
        keys.extend(
396769×
            bundle
397769×
                .raw_changes
398769×
                .iter()
399769×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
400
        );
401769×
        keys.extend(
402769×
            bundle
403769×
                .attests
404769×
                .iter()
405769×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
406
        );
407769×
        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()
42443×
                        .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
        }
432769×
        Ok(())
433769×
    }
434
435684×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
436684×
        self.attach_certificates_for(bundle, &[])
437684×
    }
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.
441729×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
442729×
        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
        }
454729×
        Ok(())
455729×
    }
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).
490726×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
491726×
        self.import_bundle_inner(bundle, strict, false)
492726×
    }
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
500729×
    fn import_bundle_inner(
501729×
        &self,
502729×
        bundle: &Bundle,
503729×
        strict: bool,
504729×
        shallow: bool,
505729×
    ) -> Result<Vec<ChangeHash>> {
506729×
        let batch = self.store.begin_batch()?;
507729×
        let result = self.import_bundle_batched(bundle, strict, shallow);
508729×
        batch.finish()?;
509727×
        result
510729×
    }
511
512729×
    fn import_bundle_batched(
513729×
        &self,
514729×
        bundle: &Bundle,
515729×
        strict: bool,
516729×
        shallow: bool,
517729×
    ) -> Result<Vec<ChangeHash>> {
518729×
        for (ty, _) in &bundle.objects {
5190×
            if !matches!(
520531×
                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()));
528531×
            }
529
        }
530
        // All at once: in a large batch they are compressed on every core.
531729×
        let objects: Vec<(ObjectType, &[u8])> = bundle
532729×
            .objects
533729×
            .iter()
534729×
            .map(|(ty, body)| (*ty, body.as_slice()))
535729×
            .collect();
536729×
        self.store.put_many(&objects)?;
537729×
        self.adopt_certificates(&bundle.certificates)?;
538729×
        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).
552729×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
553720×
            bundle.hashes.clone()
554
        } else {
5559×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
556
        };
557729×
        let raw_hashes: Vec<ChangeHash> = bundle
558729×
            .raw_changes
559729×
            .iter()
560729×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
561729×
            .collect();
562729×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
563729×
        let boundary = self.boundary();
564729×
        let mut imported = Vec::new();
565
        // Changes as stored: checked, then stored as they are, their text
566
        // blobs having come with the objects.
567729×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
568528×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
569528×
            for d in &skel.deps {
570406×
                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
                    ));
577406×
                }
578
            }
5795017×
            for t in texts {
5805017×
                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×
                    }
5885013×
                }
589
            }
590527×
            self.store.put(ObjectType::Change, bytes)?;
591527×
            for sig in sigs {
5924×
                self.store.put_signature(&h, sig)?;
593
            }
594527×
            imported.push(h);
595
        }
596728×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
597485×
            for d in &c.deps {
598301×
                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
                    ));
605298×
                }
606
            }
607482×
            let stored = self.store.put_change(c)?;
608482×
            if stored != h {
6090×
                return fail(format!(
610
                    "change {} is not the change the bundle names",
6110×
                    h.short(12)
612
                ));
613482×
            }
614482×
            for sig in sigs {
61527×
                self.store.put_signature(&h, sig)?;
616
            }
617482×
            imported.push(h);
618
        }
619725×
        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
            }
628682×
        }
629721×
        Ok(imported)
630729×
    }
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.
751284×
    pub fn receive_push(
752284×
        &self,
753284×
        bundle: Bundle,
754284×
        updates: Vec<RefUpdate>,
755284×
        policy: Option<SignedPolicy>,
756284×
        tags: Vec<crate::protocol::TagRef>,
757284×
    ) -> Result<Vec<RefResult>> {
758284×
        Ok(self
759284×
            .receive_push_report(bundle, updates, policy, tags)?
760
            .results)
761284×
    }
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).
766327×
    pub fn receive_push_report(
767327×
        &self,
768327×
        bundle: Bundle,
769327×
        updates: Vec<RefUpdate>,
770327×
        policy: Option<SignedPolicy>,
771327×
        tags: Vec<crate::protocol::TagRef>,
772327×
    ) -> Result<PushReport> {
773327×
        let mut report = PushReport::default();
774327×
        let results = &mut report.results;
775327×
        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
            }
800302×
        }
801325×
        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`.
804325×
        let objects_only = updates.is_empty() && tags.is_empty();
805325×
        match self.import_bundle(&bundle, policy.is_some()) {
806319×
            Ok(imported) => {
807319×
                if objects_only {
8087×
                    results.push(RefResult {
8097×
                        name: OBJECTS_RESULT.into(),
8107×
                        ok: true,
8117×
                        reason: format!("{} changes stored", imported.len()),
8127×
                    });
813312×
                }
814319×
                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
        }
834319×
        let (op_ref, op) = self.head_op()?;
835319×
        let mut view = op.view.clone();
836319×
        let mut names = Vec::new();
837319×
        for u in updates {
838310×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
839310×
            let (ok, reason) = match outcome {
840281×
                Ok(()) => (true, String::new()),
84129×
                Err(e) => (false, e),
842
            };
843310×
            if ok {
844281×
                names.push(u.name.clone());
845281×
                let heads = self
846281×
                    .store
847281×
                    .get_state(&u.new_state)
848281×
                    .map(|s| s.heads)
849281×
                    .unwrap_or_default();
850281×
                report.updated.push(RefUpdated {
851281×
                    name: u.name.clone(),
852281×
                    old_state: u.old_state,
853281×
                    new_state: u.new_state,
854281×
                    heads,
855281×
                });
85629×
            }
857310×
            results.push(RefResult {
858310×
                name: u.name,
859310×
                ok,
860310×
                reason,
861310×
            });
862
        }
863319×
        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
        }
893319×
        if !names.is_empty() {
894281×
            self.record_op(
895281×
                &[op_ref],
896281×
                &format!("push received: {}", names.join(" ")),
897281×
                view,
8983×
            )?;
89938×
        }
900316×
        Ok(report)
901327×
    }
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
1064310×
    fn apply_update(
1065310×
        &self,
1066310×
        view: &mut View,
1067310×
        u: &RefUpdate,
1068310×
        policy: Option<&crate::policy::Policy>,
1069310×
    ) -> std::result::Result<(), String> {
1070310×
        if u.name == "policy" {
10710×
            return Err(
10720×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
10730×
            );
1074310×
        }
1075310×
        let empty = self
1076310×
            .store
1077310×
            .put_state(&StateObject::new(vec![]))
1078310×
            .map_err(|e| e.to_string())?;
1079310×
        if u.new_state.is_zero() {
10803×
            return self.apply_deletion(view, u, policy);
1081307×
        }
1082307×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1083307×
        if current != u.old_state {
108412×
            return Err("stale: the remote bookmark has moved; pull first".into());
1085295×
        }
1086295×
        let new_state = self
1087295×
            .store
1088295×
            .get_state(&u.new_state)
1089295×
            .map_err(|_| "new state object is missing".to_string())?;
1090559×
        for h in &new_state.heads {
1091559×
            if !self.store.has(h) {
10921×
                return Err(format!("head {} is missing", h.short(12)));
1093558×
            }
1094
        }
1095294×
        if !u.force {
1096293×
            let old_heads = self
1097293×
                .store
1098293×
                .get_state(&current)
1099293×
                .map_err(|e| e.to_string())?
1100
                .heads;
1101293×
            let closure = self
1102293×
                .closure_in_store(&new_state.heads)
1103293×
                .map_err(|e| e.to_string())?;
1104295×
            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×
                ));
1109292×
            }
11101×
        }
1111293×
        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)?;
1141255×
        }
1142285×
        if let Some(sa) = &u.attestation {
114383×
            self.record_update_attest(u, sa)?;
1144202×
        }
1145279×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1146279×
        Ok(())
1147310×
    }
1148
1149
    // ------------------------------------------------------------ client side
1150
11511003×
    fn remote_url(&self, name: &str) -> Result<String> {
11521003×
        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×
        })
11681003×
    }
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).
1173745×
    fn check_remote_id(
1174745×
        &self,
1175745×
        remote: &dyn crate::protocol::Remote,
1176745×
        remote_name: &str,
1177745×
        allow_unbound: bool,
1178745×
    ) -> Result<()> {
1179745×
        let theirs = remote.repo_id()?;
1180744×
        if theirs == self.id()? {
1181721×
            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
        ))
1194745×
    }
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`]).
11991020×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
12001020×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
12011020×
        let mut options = RemoteOptions {
12021020×
            repo_id: self.id().ok(),
12031020×
            token: self.config.remote_tokens.get(name).cloned(),
12041020×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
12051020×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
12061020×
            ..RemoteOptions::default()
12071020×
        };
12081020×
        self.fill_credentials(&url, &mut options);
12091020×
        options
12101020×
    }
1211
1212
    /// The user's credential store (`credentials.toml` beside the user
1213
    /// configuration file).
12141039×
    pub fn credentials(&self) -> crate::credentials::Credentials {
12151039×
        crate::credentials::Credentials::at(
12161039×
            self.user_config
12171039×
                .parent()
12181039×
                .map(Path::to_path_buf)
12191039×
                .unwrap_or_else(default_home),
1220
        )
12211039×
    }
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).
12301040×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
12311040×
        if options.token.is_some() && options.ca.is_some() {
12321×
            return;
12331039×
        }
12341039×
        let explicit =
12351039×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
12361039×
        let stored = self.credentials().options_for(url);
12371039×
        options.token = options.token.take().or(stored.token);
12381039×
        options.ca = options.ca.take().or(stored.ca);
12391039×
        let enclosing = self.enclosing_credentials(url);
12401039×
        if options.token.is_none() {
12411029×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
124210×
        }
12431039×
        if options.ca.is_none() {
1244996×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
124543×
        }
12461039×
        if !explicit {
12471032×
            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×
        }
12531040×
    }
1254
1255
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1256
    /// checkouts, nearest first.
12571039×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
12581039×
        let mut out = Vec::new();
12591039×
        let Some(hub) = crate::credentials::hub_of(url) else {
1260905×
            return out;
1261
        };
1262134×
        let mut at = self.root.parent();
1263544×
        while let Some(dir) = at {
1264410×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
12650×
                break;
1266
            };
1267410×
            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
            }
1282410×
            at = dir.parent();
1283
        }
1284134×
        out
12851039×
    }
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
13421003×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
13431003×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
13441003×
    }
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
1365406×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1366406×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1367406×
    }
1368
1369
    /// The highest policy serial `remote` has ever presented.
1370364×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1371364×
        fs::read_to_string(self.policy_serial_path(remote))
1372364×
            .ok()
1373364×
            .and_then(|s| s.trim().parse().ok())
1374364×
    }
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.
1442364×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1443364×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1444489×
        for st in view
1445364×
            .bookmarks
1446364×
            .values()
1447364×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1448
        {
1449489×
            if let Ok(s) = self.store.get_state(st) {
1450489×
                have.extend(s.heads);
1451489×
            }
1452
        }
1453364×
        have.extend(view.workspaces.values().copied());
1454364×
        Ok(have.into_iter().collect())
1455364×
    }
1456
1457
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1458370×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1459370×
        let remote = self.open_named_remote(remote_name)?;
1460367×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1461365×
        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.
1467364×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1468364×
        let seen = self.remote_policy_serial(remote_name);
1469364×
        let mut unverified = false;
1470364×
        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 => {
1497345×
                if seen.is_some() {
14980×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1499345×
                }
1500345×
                unverified = true;
1501
            }
1502
        }
1503364×
        let policy = if unverified {
1504345×
            None
1505
        } else {
150619×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1507
        };
1508364×
        let (op_ref, op) = self.head_op()?;
1509364×
        let mut view = op.view.clone();
1510364×
        let have = self.known_heads(&view)?;
1511364×
        let mut report = Vec::new();
1512364×
        let max_blob = self.config.max_blob;
1513371×
        for r in resp.refs {
1514371×
            let needed = {
1515371×
                let _t = crate::timing::phase("fetch: negotiate");
1516371×
                remote.negotiate(&have, &r.heads)?
1517
            };
1518371×
            let bundle = {
1519371×
                let _t = crate::timing::phase("fetch: bundle");
1520371×
                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.
1525371×
            let imported = {
1526371×
                let _t = crate::timing::phase("fetch: import");
1527371×
                self.import_bundle(&bundle, false)?
1528
            };
1529371×
            if max_blob.is_some() {
15304×
                self.register_missing_blobs(&imported, remote_name)?;
1531367×
            }
1532516×
            for h in &r.heads {
1533516×
                if !self.store.has(h) {
15340×
                    return fail(format!("remote did not send head {}", h.short(12)));
1535516×
                }
1536
            }
1537371×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1538371×
            if state != r.state {
15390×
                return fail(format!(
1540
                    "remote state {} does not match its heads",
15410×
                    r.state.short(12)
1542
                ));
1543371×
            }
1544371×
            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×
                }
1569352×
            }
1570371×
            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)?;
1603341×
            }
1604371×
            view.remotes
1605371×
                .entry(remote_name.to_string())
1606371×
                .or_default()
1607371×
                .insert(r.name.clone(), state);
1608371×
            report.push((r.name, r.heads, imported.len()));
1609
        }
1610364×
        let mut new_tags = 0;
1611364×
        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
        }
1632364×
        if view != op.view {
1633353×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
163411×
        }
1635364×
        let _ = self.run_hook(
1636364×
            "post-fetch",
1637364×
            &format!(
1638
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1639364×
                json_str(remote_name),
1640371×
                json_array(report.iter().map(|(n, heads, _)| format!(
1641
                    "{{\"name\":{},\"heads\":{}}}",
1642371×
                    json_str(n),
1643516×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1644
                )))
1645
            ),
1646
        );
1647364×
        Ok(FetchReport {
1648364×
            refs: report,
1649364×
            unverified,
1650364×
            new_tags,
1651364×
        })
1652370×
    }
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).
1719108×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1720108×
        let _wc = self.lock_working_copy()?;
1721108×
        self.fetch(remote_name)?;
1722105×
        let (op_ref, op) = self.head_op()?;
1723105×
        let current = self.config.bookmark.clone();
1724105×
        let mut local_current = self.heads_of(&op.view, &current)?;
1725105×
        local_current.sort();
1726105×
        let mut view = op.view.clone();
1727105×
        let mut current_heads = local_current.clone();
1728105×
        let mut changed = false;
1729105×
        let mut others = Vec::new();
1730105×
        let tracked = op
1731105×
            .view
1732105×
            .remotes
1733105×
            .get(remote_name)
1734105×
            .cloned()
1735105×
            .unwrap_or_default();
1736109×
        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.
1739109×
            let local_state = op.view.bookmarks.get(&name).copied();
1740109×
            if local_state.is_none() && name != current {
17410×
                continue;
1742109×
            }
1743109×
            if local_state == Some(remote_state) {
17449×
                continue;
1745100×
            }
1746100×
            let local = self.heads_of(&op.view, &name)?;
1747100×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1748135×
            if remote_heads.iter().all(|h| local.contains(h)) {
17490×
                continue;
1750100×
            }
1751100×
            let mut all = local.clone();
1752100×
            all.extend(remote_heads);
1753100×
            let st = self.load_state_history(&all)?;
1754100×
            let mut heads = st.maximal(&all);
1755100×
            heads.sort();
1756100×
            let mut sorted_local = local;
1757100×
            sorted_local.sort();
1758100×
            if heads == sorted_local {
17591×
                continue;
176099×
            }
176199×
            view.bookmarks.insert(
176299×
                name.clone(),
176399×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1764
            );
176599×
            if name == current {
176697×
                changed = true;
176797×
                current_heads = heads;
176897×
            } else {
17692×
                others.push(name);
17702×
            }
1771
        }
1772105×
        if changed || !others.is_empty() {
177398×
            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).
1778105×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1779
        Ok(PullReport {
1780105×
            heads: if changed {
178197×
                current_heads
1782
            } else {
17838×
                local_current
1784
            },
1785105×
            changed,
1786105×
            checked_out,
1787105×
            others,
1788
        })
1789108×
    }
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.
1826105×
    pub fn follow_bookmark(
1827105×
        &self,
1828105×
        heads: &[ChangeHash],
1829105×
        bookmark: &str,
1830105×
        command: &str,
1831105×
    ) -> Result<bool> {
1832105×
        let snap = self.snapshot(command)?;
1833105×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1834105×
        let mut base = snap.base.maximal(&snap.wc.deps);
1835105×
        base.sort();
1836105×
        let mut target = heads.to_vec();
1837105×
        target.sort();
1838105×
        if base == target {
18397×
            return Ok(false);
184098×
        }
184198×
        let state = self.load_state_history(heads)?;
1842180×
        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);
184598×
        }
184698×
        if clean {
184798×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
184898×
            Ok(true)
1849
        } else {
18500×
            Ok(self
18510×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
18520×
                .is_ok())
1853
        }
1854105×
    }
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.
1948290×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1949290×
        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×
        };
1956290×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1957405×
        for h in changes {
1958405×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1959405×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1960405×
            let mut weight = raw.len() as u64;
1961533×
            for t in &texts {
1962533×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
196326×
                    weight += blob_len(r);
1964507×
                }
1965
            }
1966700×
            for e in &c.edits {
19673×
                if let Edit::Replace { new: Some(b), .. } = e {
19683×
                    weight += blob_len(b);
1969697×
                }
1970
            }
1971405×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
19725×
                out.push(std::mem::take(&mut batch));
19735×
                bytes = 0;
1974400×
            }
1975405×
            batch.push(*h);
1976405×
            bytes += weight;
1977
        }
1978290×
        out.push(batch);
1979290×
        Ok(out)
1980290×
    }
1981
1982357×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1983357×
        let bookmark = self.config.bookmark.clone();
1984357×
        self.push_bookmark(remote_name, &bookmark, force)
1985357×
    }
1986
1987
    /// `push` for a named bookmark (`oxy push -b NAME`).
1988365×
    pub fn push_bookmark(
1989365×
        &self,
1990365×
        remote_name: &str,
1991365×
        bookmark: &str,
1992365×
        force: bool,
1993365×
    ) -> Result<Vec<RefResult>> {
1994365×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1995365×
    }
1996
1997
    /// `push_bookmark`, saying how a long push is going: one line per
1998
    /// batch sent (oxygen#95).
1999373×
    pub fn push_bookmark_with(
2000373×
        &self,
2001373×
        remote_name: &str,
2002373×
        bookmark: &str,
2003373×
        force: bool,
2004373×
        progress: crate::store::Progress,
2005373×
    ) -> Result<Vec<RefResult>> {
2006373×
        let (op_ref, op) = self.head_op()?;
2007373×
        if !op.view.bookmarks.contains_key(bookmark) {
20080×
            return fail(format!("no bookmark {bookmark}"));
2009373×
        }
2010373×
        let bookmark = bookmark.to_string();
2011373×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2012
        // pre-push hook: may veto before the remote is contacted.
2013373×
        self.run_hook(
2014373×
            "pre-push",
2015373×
            &format!(
2016
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2017373×
                json_str(remote_name),
2018373×
                json_str(&bookmark),
2019760×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2020
            ),
20211×
        )?;
2022372×
        let remote = self.open_named_remote(remote_name)?;
2023372×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2024369×
        let resp = remote.refs()?;
2025369×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2026369×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2027369×
        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
            }
2036345×
            _ => None,
2037
        };
2038368×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2039368×
        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`)"));
2041367×
        }
2042367×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2043367×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2044367×
            .tag_refs()?
2045367×
            .into_iter()
2046367×
            .filter(|t| !remote_tags.contains(&t.name))
2047367×
            .collect();
2048367×
        let refs = resp.refs;
2049367×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2050367×
        let (remote_state, remote_heads, last_serial) =
2051367×
            match refs.iter().find(|r| r.name == bookmark) {
2052350×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
205317×
                None => (empty, vec![], None),
2054
            };
2055367×
        let new_state = self
2056367×
            .store
2057367×
            .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).
2062367×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
206310×
            return Ok(vec![RefResult {
206410×
                name: bookmark,
206510×
                ok: true,
206610×
                reason: "already up to date".into(),
206710×
            }]);
2068357×
        }
2069393×
        for h in &remote_heads {
2070393×
            if !self.store.has(h) {
207166×
                return fail(format!(
2072
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
207366×
                    h.short(12)
2074
                ));
2075327×
            }
2076
        }
2077291×
        if !force {
2078291×
            let closure = self.closure_in_store(&local_heads)?;
2079309×
            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)));
2081291×
            }
20820×
        }
2083291×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2084291×
        let key = self.secret_key()?.map(|(k, _)| k);
2085291×
        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
            }
2101204×
        }
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).
2106290×
        let batches = self.push_batches(&to_send)?;
2107290×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2108290×
        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
        }
2132290×
        if batches.len() > 1 {
21331×
            progress(&format!(
21341×
                "part {} of {}: {} changes",
21351×
                batches.len(),
21361×
                batches.len(),
21371×
                last.len()
21381×
            ));
2139289×
        }
2140290×
        let mut bundle = self.bundle_for(last)?;
2141290×
        bundle.objects.push((
2142290×
            ObjectType::State,
2143290×
            StateObject::new(local_heads.clone()).encode(),
2144290×
        ));
2145290×
        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×
            })?),
2156204×
            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).
2161289×
        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)?;
2180204×
        }
2181289×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
218285×
            AttestBody::Ref { serial, .. } => Some(serial),
21830×
            _ => None,
218485×
        });
2185289×
        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.
2187289×
        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
        }
2203289×
        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();
2213266×
        }
2214289×
        let results = remote.push(
2215289×
            bundle,
2216289×
            vec![RefUpdate {
2217289×
                name: bookmark.clone(),
2218289×
                old_state: remote_state,
2219289×
                new_state,
2220289×
                force,
2221289×
                attestation,
2222289×
            }],
2223289×
            policy_to_send,
2224289×
            tags_to_send,
22257×
        )?;
222623×
        if let (Some(serial), true) = (
2227282×
            sent_serial,
2228288×
            results.iter().any(|r| r.ok && r.name == "policy"),
2229
        ) {
223023×
            self.record_policy_serial(remote_name, serial)?;
2231259×
        }
2232305×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2233256×
            let mut view = op.view.clone();
2234256×
            view.remotes
2235256×
                .entry(remote_name.to_string())
2236256×
                .or_default()
2237256×
                .insert(bookmark.clone(), new_state);
2238256×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2239253×
            if let Some(s) = serial {
224064×
                self.record_serial(remote_name, &bookmark, s)?;
2241189×
            }
224226×
        }
2243277×
        Ok(results)
2244373×
    }
2245
2246
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2247
    /// bookmark set to the remote's, working copy checked out.
2248238×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2249238×
        Self::clone_with(url, dest, None, &[])
2250238×
    }
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).
2255246×
    pub fn clone_with(
2256246×
        url: &str,
2257246×
        dest: &Path,
2258246×
        max_blob: Option<u64>,
2259246×
        sparse: &[String],
2260246×
    ) -> Result<Repo> {
2261246×
        Self::clone_full(url, dest, max_blob, sparse, None)
2262246×
    }
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
2276247×
    fn clone_full(
2277247×
        url: &str,
2278247×
        dest: &Path,
2279247×
        max_blob: Option<u64>,
2280247×
        sparse: &[String],
2281247×
        depth: Option<u32>,
2282247×
    ) -> Result<Repo> {
2283247×
        let options = crate::credentials::Credentials::user().options_for(url);
2284247×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2285247×
    }
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
2337256×
    fn clone_using(
2338256×
        url: &str,
2339256×
        dest: &Path,
2340256×
        max_blob: Option<u64>,
2341256×
        sparse: &[String],
2342256×
        depth: Option<u32>,
2343256×
        options: &RemoteOptions,
2344256×
    ) -> Result<Repo> {
2345256×
        let remote = open_remote(url, options)?;
2346256×
        let id = remote.repo_id()?;
2347252×
        if id == crate::protocol::UNBOUND_ID {
23482×
            return fail(format!(
2349
                "{url} is empty and unbound: push a repository to it first"
2350
            ));
2351250×
        }
2352250×
        let mut repo = Repo::init_with_id(dest, id)?;
2353250×
        repo.config
2354250×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2355250×
        if let Some(m) = max_blob {
23562×
            repo.config.set("filter.max-blob", &m.to_string())?;
2357248×
        } else if !sparse.is_empty() {
23581×
            repo.config.set("filter.max-blob", "0")?;
2359247×
        }
2360250×
        if !sparse.is_empty() {
23611×
            repo.config.set("filter.paths", &sparse.join(","))?;
2362249×
        }
2363250×
        repo.save_config()?;
2364250×
        if let Some(depth) = depth {
23651×
            repo.fetch_shallow("origin", depth)?;
2366
        } else {
2367249×
            repo.fetch("origin")?;
2368
        }
2369249×
        let (op_ref, op) = repo.head_op()?;
2370
        // The remote's default bookmark, else ours (main), else its only one.
2371249×
        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.
2374249×
        let advertised = repo
2375249×
            .open_named_remote("origin")
2376249×
            .ok()
2377249×
            .and_then(|r| r.refs().ok())
2378249×
            .and_then(|r| r.default_bookmark);
2379249×
        let bookmark = advertised
2380249×
            .filter(|b| theirs.contains_key(b))
2381249×
            .or_else(|| {
23827×
                theirs
23837×
                    .contains_key(&repo.config.bookmark)
23847×
                    .then(|| repo.config.bookmark.clone())
23857×
            })
2386249×
            .or_else(|| {
23870×
                (theirs.len() == 1)
23880×
                    .then(|| theirs.keys().next().cloned())
23890×
                    .flatten()
23900×
            })
2391249×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2392249×
        let initial = repo.config.bookmark.clone();
2393249×
        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();
2397248×
        }
2398249×
        if let Some(state) = theirs.get(&bookmark).copied() {
2399249×
            let heads = repo.store.get_state(&state)?.heads;
2400249×
            let mut view = op.view.clone();
2401
            // The empty bookmark `init` made goes when another is checked out.
2402249×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
24031×
                view.bookmarks.remove(&initial);
2404248×
            }
2405249×
            view.bookmarks.insert(bookmark, state);
2406249×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2407249×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
24080×
        }
2409249×
        Ok(repo)
2410256×
    }
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×
}