OXYGENHUB

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

1726 of 1936 lines run, 251 of 362 functions · run #322 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
    /// What checking the host's transparency log found short of a fork
34
    /// (spec §14.8): attestations not logged yet, a log that could not be
35
    /// read. A fork fails the fetch instead.
36
    pub log_notes: Vec<String>,
37
}
38
39
#[derive(Debug, Clone, PartialEq, Eq)]
40
pub struct PullReport {
41
    /// The current bookmark's heads after the pull.
42
    pub heads: Vec<ChangeHash>,
43
    /// Whether the current bookmark changed.
44
    pub changed: bool,
45
    pub checked_out: bool,
46
    /// Other bookmarks the pull moved: each local bookmark tracks the
47
    /// remote's of the same name.
48
    pub others: Vec<String>,
49
}
50
51
/// The result a push of objects alone reports (a batch of a long history):
52
/// not a reference.
53
pub const OBJECTS_RESULT: &str = "objects";
54
55
impl Repo {
56
    // ------------------------------------------------------------ serving (spec §16)
57
581308×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
591308×
        self.oxy.join("attest").join(name_file(bookmark))
601308×
    }
61
62
    /// The latest reference attestation stored for a bookmark.
631224×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
641224×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
65235×
            Ok(h) => {
66235×
                let r = ObjectRef::from_hex(h.trim())
67235×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
68
                Ok(Some((
69235×
                    r,
70
                    SignedAttest {
71235×
                        attest: self.store.get_attest(&r)?,
72235×
                        sigs: self.store.signatures(&r)?,
73
                    },
74
                )))
75
            }
76989×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
770×
            Err(e) => Err(e.into()),
78
        }
791224×
    }
80
8184×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
8284×
        fs::create_dir_all(self.oxy.join("attest"))?;
8384×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8484×
    }
85
86999×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
87999×
        let view = self.view()?;
88999×
        let mut out = Vec::new();
891021×
        for (name, state) in &view.bookmarks {
901021×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
911021×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
92136×
                AttestBody::Ref { serial, .. } => Some(serial),
930×
                _ => None,
94136×
            });
951021×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
961021×
            let accepted = match &attestation {
97125×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
98896×
                None => None,
99
            };
1001021×
            out.push(RemoteRef {
1011021×
                name: name.clone(),
1021021×
                state: *state,
1031021×
                heads: self.store.get_state(state)?.heads,
1041021×
                attestation,
1051021×
                last_serial,
1061021×
                accepted,
1071021×
                logged: None,
108
            });
109
        }
110999×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
111999×
        let history = self
112999×
            .policy_history()?
113999×
            .into_iter()
114999×
            .filter(|sp| {
115126×
                policy
116126×
                    .as_ref()
117126×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
118126×
            })
119999×
            .collect();
120
        Ok(RefsResponse {
121999×
            refs: out,
122999×
            policy,
123999×
            tags: self.tag_refs()?,
124999×
            history,
125999×
            default_bookmark: Some(self.config.bookmark.clone()),
126999×
            log: None,
127
        })
128999×
    }
129
130
    /// Every change reachable from `heads` that is in the store.
1311334×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1321334×
        let mut seen = BTreeSet::new();
1331334×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1344560×
        while let Some(h) = stack.pop() {
1353226×
            if seen.contains(&h) || !self.store.has(&h) {
136953×
                continue;
1372273×
            }
1382273×
            seen.insert(h);
1392273×
            stack.extend(self.store.get_change_meta(&h)?.deps);
140
        }
1411334×
        Ok(seen)
1421334×
    }
143
144
    /// The changes within `depth` dependency steps of `heads` (spec §17),
145
    /// nearest first; depth 1 is the heads themselves.
1463×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1473×
        let mut out = Vec::new();
1483×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1493×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1503×
        for _ in 0..depth.max(1) {
1518×
            let mut next = Vec::new();
15212×
            for h in layer {
15312×
                if !seen.insert(h) || !self.store.has(&h) {
1542×
                    continue;
15510×
                }
15610×
                let c = self.store.get_change(&h)?;
15710×
                next.extend(c.deps.iter().copied());
15810×
                out.push(h);
159
            }
1608×
            if next.is_empty() {
1611×
                break;
1627×
            }
1637×
            layer = next;
164
        }
1653×
        out.reverse();
1663×
        Ok(out)
1673×
    }
168
1691917×
    fn shallow_path(&self) -> PathBuf {
1701917×
        self.oxy.join("shallow")
1711917×
    }
172
173
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1741914×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1751914×
        fs::read_to_string(self.shallow_path())
1761914×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1771914×
            .unwrap_or_default()
1781914×
    }
179
180183×
    pub fn is_shallow(&self) -> bool {
181183×
        !self.boundary().is_empty()
182183×
    }
183
1843×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1853×
        if boundary.is_empty() {
1861×
            let _ = fs::remove_file(self.shallow_path());
1871×
            return Ok(());
1882×
        }
1892×
        let text: String = boundary
1902×
            .iter()
1912×
            .map(|h| format!("{}\n", h.to_hex()))
1922×
            .collect();
1932×
        write_atomic(&self.shallow_path(), text.as_bytes())
1943×
    }
195
196
    /// Recompute the boundary from what is stored: every dependency of a
197
    /// stored change that is not itself stored.
1983×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1993×
        let mut boundary = self.boundary();
2003×
        boundary.retain(|h| !self.store.has(h));
20110×
        for h in imported {
20213×
            for d in self.store.get_change_meta(h)?.deps {
20313×
                if !self.store.has(&d) {
2042×
                    boundary.insert(d);
20511×
                }
206
            }
207
        }
2083×
        self.write_boundary(&boundary)
2093×
    }
210
211
    /// Fetch `depth` more levels of history below the shallow boundary.
2122×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2132×
        let boundary = self.boundary();
2142×
        if boundary.is_empty() {
2150×
            return Ok(0);
2162×
        }
2172×
        let remote = self.open_named_remote(remote_name)?;
2182×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2192×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2202×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2212×
        if self.config.max_blob.is_some() {
2220×
            self.register_missing_blobs(&imported, remote_name)?;
2232×
        }
2242×
        self.refresh_boundary(&imported)?;
2252×
        Ok(imported.len())
2262×
    }
227
228
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
229761×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
230761×
        let have = self.closure_in_store(have)?;
231
        // In a shallow repository the walk stops at the boundary, whose
232
        // changes the remote is assumed to hold.
233761×
        let boundary = self.boundary();
234761×
        let mut out = Vec::new();
235761×
        let mut done: BTreeSet<ChangeHash> = have.clone();
236761×
        done.extend(boundary.iter().copied());
237
        // Iterative post-order DFS.
2381168×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2393141×
        while let Some((h, expanded)) = stack.pop() {
2402380×
            if done.contains(&h) {
241372×
                continue;
2422008×
            }
2432008×
            if !self.store.has(&h) {
2440×
                return fail(format!("change {} is not in this repository", h.short(12)));
2452008×
            }
2462008×
            if expanded {
2471004×
                done.insert(h);
2481004×
                out.push(h);
2491004×
                continue;
2501004×
            }
2511004×
            stack.push((h, true));
2521004×
            for d in self.store.get_change_meta(&h)?.deps {
253712×
                if !done.contains(&d) {
254208×
                    stack.push((d, false));
255504×
                }
256
            }
257
        }
258761×
        Ok(out)
259761×
    }
260
261
    /// Bundle changes (in the given dependency order) with their signatures,
262
    /// seals, identities, blobs, chunks.
263302×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
264302×
        self.bundle_for_filtered(changes, None)
265302×
    }
266
267
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2684×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2694×
        let mut out = Vec::new();
2704×
        for r in refs {
2714×
            let (ty, body) = match self.store.get(r) {
2724×
                Ok(x) => x,
2730×
                Err(StoreError::NotFound(_)) => continue,
2740×
                Err(e) => return Err(e.into()),
275
            };
2764×
            if ty == ObjectType::Blob {
2775×
                for c in Blob::decode(&body)?.chunks {
2785×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2795×
                        out.push((cty, cb));
2805×
                    }
281
                }
2820×
            }
2834×
            out.push((ty, body));
284
        }
2854×
        Ok(out)
2864×
    }
287
288
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
289
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
290348×
    pub fn bundle_for_filtered(
291348×
        &self,
292348×
        changes: &[ChangeHash],
293348×
        max_blob: Option<u64>,
294348×
    ) -> Result<Bundle> {
295348×
        self.bundle_of(changes, max_blob, false)
296348×
    }
297
298
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
299
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
300
    /// with their text blobs and chunks among the objects, so neither side
301
    /// decodes or encodes their text.
302318×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
303318×
        self.bundle_of(changes, max_blob, true)
304318×
    }
305
306666×
    fn bundle_of(
307666×
        &self,
308666×
        changes: &[ChangeHash],
309666×
        max_blob: Option<u64>,
310666×
        raw: bool,
311666×
    ) -> Result<Bundle> {
312666×
        let mut bundle = Bundle::default();
313666×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
314666×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3151036×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3161036×
            if !r.is_zero() && self.store.has(r) {
317219×
                objects.insert(*r);
318817×
            }
3191036×
        };
320929×
        for h in changes {
321
            // Raw: the stored bytes, and a skeleton for the rest.
322929×
            let (c, encoded) = if raw {
323490×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
324490×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3254981×
                for t in texts {
3264981×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3273×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3283×
                        objects.insert(r);
3293×
                        objects.extend(blob.chunks);
3304978×
                    }
331
                }
332490×
                (skel, Some(bytes))
333
            } else {
334439×
                (self.store.get_change(h)?, None)
335
            };
336929×
            let sigs = self.store.signatures(h)?;
337929×
            add_object(&c.author, &mut objects);
338929×
            for s in &sigs {
33922×
                add_object(&s.key, &mut objects);
34022×
            }
3415945×
            for e in &c.edits {
3425945×
                if let Edit::Replace { old, new, .. } = e {
34314×
                    for b in [old, new].into_iter().flatten() {
34414×
                        if self.store.has(b) {
34514×
                            if let Ok(blob) =
34614×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
347
                            {
34814×
                                if max_blob.is_some_and(|m| blob.length > m) {
3494×
                                    continue;
35010×
                                }
35110×
                                objects.insert(*b);
35210×
                                objects.extend(blob.chunks.iter().copied());
3530×
                            }
3540×
                        }
355
                    }
3565933×
                }
357
            }
358929×
            for s in self.store.seals_for(h)? {
35990×
                seals.insert(s);
36090×
            }
361929×
            match encoded {
362490×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
363439×
                None => {
364439×
                    bundle.changes.push((c, sigs));
365439×
                    bundle.hashes.push(*h);
366439×
                }
367
            }
368
        }
369666×
        for r in seals {
37085×
            let attest = self.store.get_attest(&r)?;
37185×
            let sigs = self.store.signatures(&r)?;
37285×
            for s in &sigs {
37385×
                add_object(&s.key, &mut objects);
37485×
            }
37585×
            bundle.attests.push(SignedAttest { attest, sigs });
376
        }
377666×
        for r in objects {
378134×
            let (ty, body) = self.store.get(&r)?;
379134×
            bundle.objects.push((ty, body));
380
        }
381666×
        self.attach_certificates(&mut bundle)?;
382666×
        Ok(bundle)
383666×
    }
384
385
    /// Add the certificates of short-lived keys that signed what `bundle`
386
    /// carries, and their issuers' identities, so a receiver can tell who
387
    /// they stand for (spec §14.7). `also` names more signers (a reference
388
    /// attestation sent beside the bundle).
389751×
    pub(crate) fn attach_certificates_for(
390751×
        &self,
391751×
        bundle: &mut Bundle,
392751×
        also: &[KeyId],
393751×
    ) -> Result<()> {
394751×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
395751×
        keys.extend(
396751×
            bundle
397751×
                .changes
398751×
                .iter()
399751×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
400
        );
401751×
        keys.extend(
402751×
            bundle
403751×
                .raw_changes
404751×
                .iter()
405751×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
406
        );
407751×
        keys.extend(
408751×
            bundle
409751×
                .attests
410751×
                .iter()
411751×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
412
        );
413751×
        for k in keys {
414193×
            let Some(r) = self.store.certificate_of(&k)? else {
415172×
                continue;
416
            };
41721×
            let cert = self.store.get_certificate(&r)?;
41821×
            if bundle
41921×
                .certificates
42021×
                .iter()
42121×
                .any(|c| c.cert.hash() == cert.cert.hash())
422
            {
4237×
                continue;
42414×
            }
42528×
            for id in [&k, &cert.cert.issuer] {
42628×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
42728×
                    if !bundle
42828×
                        .objects
42928×
                        .iter()
43042×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
43114×
                    {
43214×
                        bundle.objects.push((ObjectType::Identity, body));
43314×
                    }
4340×
                }
435
            }
43614×
            bundle.certificates.push(cert);
437
        }
438751×
        Ok(())
439751×
    }
440
441666×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
442666×
        self.attach_certificates_for(bundle, &[])
443666×
    }
444
445
    /// Keep the certificates a bundle brings once each verifies with the
446
    /// identity of the issuer it names; one that does not refuses the bundle.
447711×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
448711×
        for c in certs {
44914×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4500×
                RepoError::Msg(format!(
4510×
                    "a certificate names issuer {}, whose identity did not come with it",
4520×
                    c.cert.issuer.short(12)
4530×
                ))
4540×
            })?;
45514×
            c.verify(&issuer)
45614×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
45714×
            self.store.put_identity(&c.cert.key)?;
45814×
            self.store.put_certificate(c)?;
459
        }
460711×
        Ok(())
461711×
    }
462
463
    /// A signer authorized for `reference` by what an issuer certified it
464
    /// as (spec §14.7): a short-lived key with a kept certificate that
465
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
466
    /// signer did not choose) and names a subject the policy grants.
46718×
    pub(crate) fn certified_authorized(
46818×
        &self,
46918×
        p: &crate::policy::Policy,
47018×
        signer: &KeyId,
47118×
        reference: &str,
47218×
        scope: Scope,
47318×
        at_ms: u64,
47418×
    ) -> bool {
47518×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
4765×
            return false;
477
        };
47813×
        let Ok(c) = self.store.get_certificate(&r) else {
4790×
            return false;
480
        };
48113×
        let Some(issuer) = p
48213×
            .identity(&c.cert.issuer)
48313×
            .cloned()
48413×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
485
        else {
4860×
            return false;
487
        };
48813×
        c.verify(&issuer).is_ok()
48913×
            && c.cert.key_id() == *signer
49013×
            && c.cert.covers(scope, at_ms)
49112×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
49218×
    }
493
494
    /// Store a bundle's contents. With `strict`, every change must
495
    /// authenticate (signature or seal by its author or a delegate).
496708×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
497708×
        self.import_bundle_inner(bundle, strict, false)
498708×
    }
499
500
    /// Like `import_bundle`, accepting changes whose dependencies are absent
501
    /// (they join the shallow boundary).
5023×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5033×
        self.import_bundle_inner(bundle, strict, true)
5043×
    }
505
506711×
    fn import_bundle_inner(
507711×
        &self,
508711×
        bundle: &Bundle,
509711×
        strict: bool,
510711×
        shallow: bool,
511711×
    ) -> Result<Vec<ChangeHash>> {
512711×
        let batch = self.store.begin_batch()?;
513711×
        let result = self.import_bundle_batched(bundle, strict, shallow);
514711×
        batch.finish()?;
515709×
        result
516711×
    }
517
518711×
    fn import_bundle_batched(
519711×
        &self,
520711×
        bundle: &Bundle,
521711×
        strict: bool,
522711×
        shallow: bool,
523711×
    ) -> Result<Vec<ChangeHash>> {
524711×
        for (ty, _) in &bundle.objects {
5250×
            if !matches!(
526524×
                ty,
527
                ObjectType::Chunk
528
                    | ObjectType::Blob
529
                    | ObjectType::Identity
530
                    | ObjectType::State
531
                    | ObjectType::Checkpoint
532
            ) {
5330×
                return fail(format!("bundle may not carry {} objects", ty.name()));
534524×
            }
535
        }
536
        // All at once: in a large batch they are compressed on every core.
537711×
        let objects: Vec<(ObjectType, &[u8])> = bundle
538711×
            .objects
539711×
            .iter()
540711×
            .map(|(ty, body)| (*ty, body.as_slice()))
541711×
            .collect();
542711×
        self.store.put_many(&objects)?;
543711×
        self.adopt_certificates(&bundle.certificates)?;
544711×
        for sa in &bundle.attests {
54588×
            let r = self.store.put_attest(&sa.attest)?;
54688×
            for sig in &sa.sigs {
54788×
                self.store.put_signature(&r, sig)?;
548
            }
54988×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
55093×
                for h in hashes {
55193×
                    self.store.index_seal(h, &r)?;
552
                }
5530×
            }
554
        }
555
        // Each change's hash: from the bundle when its maker knew it, else
556
        // worked out once (for a change adding a whole tree, hashing is
557
        // chunking all its text).
558711×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
559702×
            bundle.hashes.clone()
560
        } else {
5619×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
562
        };
563711×
        let raw_hashes: Vec<ChangeHash> = bundle
564711×
            .raw_changes
565711×
            .iter()
566711×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
567711×
            .collect();
568711×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
569711×
        let boundary = self.boundary();
570711×
        let mut imported = Vec::new();
571
        // Changes as stored: checked, then stored as they are, their text
572
        // blobs having come with the objects.
573711×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
574491×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
575491×
            for d in &skel.deps {
576379×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
577
                {
5780×
                    return fail(format!(
579
                        "change {} depends on {}, which is neither stored nor in the bundle",
5800×
                        h.short(12),
5810×
                        d.short(12)
582
                    ));
583379×
                }
584
            }
5854982×
            for t in texts {
5864982×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
5874×
                    if !self.store.has(&r) {
5881×
                        return fail(format!(
589
                            "change {} came without its text blob {}",
5901×
                            h.short(12),
5911×
                            r.short(12)
592
                        ));
5933×
                    }
5944978×
                }
595
            }
596490×
            self.store.put(ObjectType::Change, bytes)?;
597490×
            for sig in sigs {
5984×
                self.store.put_signature(&h, sig)?;
599
            }
600490×
            imported.push(h);
601
        }
602710×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
603467×
            for d in &c.deps {
604287×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
605
                {
6063×
                    return fail(format!(
607
                        "change {} depends on {}, which is neither stored nor in the bundle",
6083×
                        h.short(12),
6093×
                        d.short(12)
610
                    ));
611284×
                }
612
            }
613464×
            let stored = self.store.put_change(c)?;
614464×
            if stored != h {
6150×
                return fail(format!(
616
                    "change {} is not the change the bundle names",
6170×
                    h.short(12)
618
                ));
619464×
            }
620464×
            for sig in sigs {
62127×
                self.store.put_signature(&h, sig)?;
622
            }
623464×
            imported.push(h);
624
        }
625707×
        if strict {
62643×
            for h in &imported {
62730×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6284×
                    return fail(format!(
629
                        "change {} is not authenticated by its author",
6304×
                        h.short(12)
631
                    ));
63226×
                }
633
            }
634664×
        }
635703×
        Ok(imported)
636711×
    }
637
638
    /// Verify a reference attestation against an update it claims to describe.
639
    /// `allow_equal` lets a client re-read the attestation it already has; a
640
    /// server receiving a push requires a strictly greater serial.
641
    /// A reference attestation signed by a delegate of an identity the
642
    /// rule lists is authorized as that identity (spec §14.5): the identity
643
    /// named the delegate with the `refs` scope, still in force at `at_ms`
644
    /// (the attestation's wall time), and the policy names the identity.
645
    /// Revoked keys authorize nothing either way.
64622×
    pub(crate) fn delegate_authorized(
64722×
        &self,
64822×
        p: &crate::policy::Policy,
64922×
        signer: &KeyId,
65022×
        reference: &str,
65122×
        at_ms: u64,
65222×
    ) -> bool {
65322×
        if p.is_revoked(signer) {
6541×
            return false;
65521×
        }
65621×
        let Some(rule) = p.rule_for(reference) else {
6570×
            return false;
658
        };
65922×
        rule.keys.iter().any(|k| {
66022×
            !p.is_revoked(k)
66122×
                && p.identity(k)
66222×
                    .cloned()
66322×
                    .or_else(|| self.store.get_identity(k).ok())
66422×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
66522×
        })
66622×
    }
667
668
    /// A lasting attestation (a tag) signed by a key the policy has since
669
    /// rotated away from (spec §14.2) is authorized as the key that
670
    /// succeeded it: a key the rule lists reaches the signer through
671
    /// `previous` links, and the attestation is dated (`at_ms`) before the
672
    /// signer's successor was made, so a superseded key makes nothing new.
673
    /// Revoked keys authorize nothing.
6746×
    pub(crate) fn predecessor_authorized(
6756×
        &self,
6766×
        p: &crate::policy::Policy,
6776×
        signer: &KeyId,
6786×
        reference: &str,
6796×
        at_ms: u64,
6806×
    ) -> bool {
6816×
        if p.is_revoked(signer) {
6820×
            return false;
6836×
        }
6846×
        let Some(rule) = p.rule_for(reference) else {
6850×
            return false;
686
        };
6877×
        let identity = |k: &KeyId| {
6887×
            p.identity(k)
6897×
                .cloned()
6907×
                .or_else(|| self.store.get_identity(k).ok())
6917×
        };
6926×
        rule.keys.iter().any(|k| {
6936×
            if p.is_revoked(k) {
6940×
                return false;
6956×
            }
6966×
            let mut cur = identity(k);
6976×
            for _ in 0..32 {
6987×
                let Some(id) = cur else {
6990×
                    return false;
700
                };
7011×
                match id.previous {
7026×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7031×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
7041×
                    _ => return false,
705
                }
706
            }
7070×
            false
7086×
        })
7096×
    }
710
711114×
    fn check_ref_attest(
712114×
        &self,
713114×
        sa: &SignedAttest,
714114×
        name: &str,
715114×
        old_state: &ObjectRef,
716114×
        new_state: &ObjectRef,
717114×
        last_serial: Option<u64>,
718114×
        allow_equal: bool,
719114×
    ) -> std::result::Result<u64, String> {
720
        let AttestBody::Ref {
721114×
            name: n,
722114×
            old_state: o,
723114×
            new_state: nw,
724114×
            serial,
725114×
        } = &sa.attest.body
726
        else {
7270×
            return Err("attestation is not a ref attestation".into());
728
        };
729114×
        if n != name || o != old_state || nw != new_state {
7301×
            return Err("attestation does not describe this update".into());
731113×
        }
732113×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7330×
            return Err("attestation is for a different repository".into());
734113×
        }
735113×
        if let Some(last) = last_serial {
73668×
            if *serial < last || (*serial == last && !allow_equal) {
7371×
                return Err(format!(
7381×
                    "attestation serial {serial} is not greater than the last seen {last}"
7391×
                ));
74067×
            }
74145×
        }
742112×
        let r = sa.attest.hash();
743112×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
744112×
        let id = self
745112×
            .store
746112×
            .get_identity(&sig.key)
747112×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
748112×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
749112×
        Ok(*serial)
750114×
    }
751
752
    /// Accept a push (spec §16.4). Without a trust policy every repository
753
    /// is unverified, so unsigned changes and unattested updates are accepted;
754
    /// attestations that are present must still be valid. With a policy,
755
    /// every change and update is checked against it. A newer policy in the
756
    /// push is applied first when it is signed by the current roots.
757280×
    pub fn receive_push(
758280×
        &self,
759280×
        bundle: Bundle,
760280×
        updates: Vec<RefUpdate>,
761280×
        policy: Option<SignedPolicy>,
762280×
        tags: Vec<crate::protocol::TagRef>,
763280×
    ) -> Result<Vec<RefResult>> {
764280×
        Ok(self
765280×
            .receive_push_report(bundle, updates, policy, tags)?
766
            .results)
767280×
    }
768
769
    /// `receive_push` with what a host wants to log: each accepted
770
    /// reference's old and new state and heads, and the changes this push
771
    /// stored (hub spec §6.12).
772320×
    pub fn receive_push_report(
773320×
        &self,
774320×
        bundle: Bundle,
775320×
        updates: Vec<RefUpdate>,
776320×
        policy: Option<SignedPolicy>,
777320×
        tags: Vec<crate::protocol::TagRef>,
778320×
    ) -> Result<PushReport> {
779320×
        let mut report = PushReport::default();
780320×
        let results = &mut report.results;
781320×
        if let Some(sp) = policy {
78225×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
78323×
                Ok(()) => {
78423×
                    results.push(RefResult {
78523×
                        name: "policy".into(),
78623×
                        ok: true,
78723×
                        reason: format!("serial {}", sp.policy.serial),
78823×
                    });
78923×
                }
7902×
                Err(e) => {
7912×
                    results.push(RefResult {
7922×
                        name: "policy".into(),
7932×
                        ok: false,
7942×
                        reason: e,
7952×
                    });
7962×
                    for u in updates {
7970×
                        results.push(RefResult {
7980×
                            name: u.name,
7990×
                            ok: false,
8000×
                            reason: "policy update was rejected".into(),
8010×
                        });
8020×
                    }
8032×
                    return Ok(report);
804
                }
805
            }
806295×
        }
807318×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
808
        // A push of objects alone (one batch of a long history, oxygen#95)
809
        // names no reference: its outcome is reported as `objects`.
810318×
        let objects_only = updates.is_empty() && tags.is_empty();
811318×
        match self.import_bundle(&bundle, policy.is_some()) {
812312×
            Ok(imported) => {
813312×
                if objects_only {
8147×
                    results.push(RefResult {
8157×
                        name: OBJECTS_RESULT.into(),
8167×
                        ok: true,
8177×
                        reason: format!("{} changes stored", imported.len()),
8187×
                    });
819305×
                }
820312×
                report.imported = imported;
821
            }
8226×
            Err(e) => {
8236×
                if objects_only {
8240×
                    results.push(RefResult {
8250×
                        name: OBJECTS_RESULT.into(),
8260×
                        ok: false,
8270×
                        reason: e.to_string(),
8280×
                    });
8296×
                }
8306×
                for u in updates {
8316×
                    results.push(RefResult {
8326×
                        name: u.name,
8336×
                        ok: false,
8346×
                        reason: e.to_string(),
8356×
                    });
8366×
                }
8376×
                return Ok(report);
838
            }
839
        }
840312×
        let (op_ref, op) = self.head_op()?;
841312×
        let mut view = op.view.clone();
842312×
        let mut names = Vec::new();
843312×
        for u in updates {
844303×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
845303×
            let (ok, reason) = match outcome {
846277×
                Ok(()) => (true, String::new()),
84726×
                Err(e) => (false, e),
848
            };
849303×
            if ok {
850277×
                names.push(u.name.clone());
851277×
                let heads = self
852277×
                    .store
853277×
                    .get_state(&u.new_state)
854277×
                    .map(|s| s.heads)
855277×
                    .unwrap_or_default();
856277×
                report.updated.push(RefUpdated {
857277×
                    name: u.name.clone(),
858277×
                    old_state: u.old_state,
859277×
                    new_state: u.new_state,
860277×
                    heads,
861277×
                });
86226×
            }
863303×
            results.push(RefResult {
864303×
                name: u.name,
865303×
                ok,
866303×
                reason,
867303×
            });
868
        }
869312×
        for t in &tags {
8708×
            let name = format!("tags/{}", t.name);
8718×
            let new = !view.tags.contains_key(&t.name);
8728×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
873
                Ok(()) => {
874
                    // A tag new here is an update too, so a hub can start
875
                    // its pipeline's tag jobs (oxygenflow#24); one it
876
                    // already had, sent again, is not.
8776×
                    if new {
8786×
                        report.updated.push(RefUpdated {
8796×
                            name: name.clone(),
8806×
                            old_state: ObjectRef::ZERO,
8816×
                            new_state: t.state,
8826×
                            heads: t.heads.clone(),
8836×
                        });
8846×
                    }
8856×
                    names.push(name.clone());
8866×
                    results.push(RefResult {
8876×
                        name,
8886×
                        ok: true,
8896×
                        reason: String::new(),
8906×
                    });
891
                }
8922×
                Err(e) => results.push(RefResult {
8932×
                    name,
8942×
                    ok: false,
8952×
                    reason: e,
8962×
                }),
897
            }
898
        }
899312×
        if !names.is_empty() {
900277×
            self.record_op(
901277×
                &[op_ref],
902277×
                &format!("push received: {}", names.join(" ")),
903277×
                view,
9043×
            )?;
90535×
        }
906309×
        Ok(report)
907320×
    }
908
909
    /// Check an update's attestation against the latest one for its
910
    /// reference and store it as the new latest. Failures say what was
911
    /// being done, for which reference, so a refused push can be diagnosed
912
    /// from its reason alone.
91384×
    fn record_update_attest(
91484×
        &self,
91584×
        u: &RefUpdate,
91684×
        sa: &SignedAttest,
91784×
    ) -> std::result::Result<(), String> {
91884×
        let name = &u.name;
91984×
        let last = self
92084×
            .latest_ref_attest(name)
92184×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
92284×
            .and_then(|(_, a)| match a.attest.body {
92355×
                AttestBody::Ref { serial, .. } => Some(serial),
9240×
                _ => None,
92555×
            });
92684×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
92782×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
92882×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
92981×
        for sig in &sa.sigs {
93081×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
931
        }
93281×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
933
        // Signed by a short-lived key: a host records when it accepted it.
93478×
        let certified = sa
93578×
            .sigs
93678×
            .first()
93778×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
93878×
        if certified {
9392×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
94076×
        }
94178×
        Ok(())
94284×
    }
943
944
    /// Record that this host accepted attestation `r` now, signed with its
945
    /// acceptor key (spec §14.7); nothing without one.
9463×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
9473×
        let Some(acceptor) = &self.acceptor else {
9482×
            return Ok(());
949
        };
9501×
        let (id, sk) = (&acceptor.0, &acceptor.1);
9511×
        let attest = Attest {
9521×
            repo: self.id()?,
9531×
            hlc: Hlc::now(),
9541×
            body: AttestBody::Accepted { attest: *r },
955
        };
9561×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
9571×
        self.store.put_identity(id)?;
9581×
        let a = self.store.put_attest(&attest)?;
9591×
        self.store.put_signature(&a, &sig)?;
9601×
        self.store.index_add_pub("accepted", r, &a)?;
9611×
        Ok(())
9623×
    }
963
964
    /// The host's acceptance of attestation `r`, if one was recorded.
965127×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
966127×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
967117×
            return Ok(None);
968
        };
969
        Ok(Some(SignedAttest {
97010×
            attest: self.store.get_attest(&a)?,
97110×
            sigs: self.store.signatures(&a)?,
972
        }))
973127×
    }
974
975
    /// When a certified signer's attestation `sa` is checked on a fetch: the
976
    /// host's acceptance time, if `accepted` is signed by the issuer of the
977
    /// signer's certificate and accepts `sa`; else the attestation's own
978
    /// time, which the signer chose.
97923×
    pub(crate) fn certified_time(
98023×
        &self,
98123×
        signer: &KeyId,
98223×
        sa: &SignedAttest,
98323×
        accepted: Option<&SignedAttest>,
98423×
    ) -> u64 {
98523×
        let own = sa.attest.hlc.wall_ms;
98623×
        let Some(acc) = accepted else {
98717×
            return own;
988
        };
9896×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
9900×
            return own;
991
        };
9926×
        let Ok(cert) = self.store.get_certificate(&c) else {
9930×
            return own;
994
        };
9956×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
9960×
            return own;
997
        };
9986×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
9991×
            return own;
1000
        };
10015×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
10020×
            return own;
1003
        };
10045×
        if *attest == sa.attest.hash()
10054×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1006
        {
10074×
            acc.attest.hlc.wall_ms
1008
        } else {
10091×
            own
1010
        }
101123×
    }
1012
1013
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1014
    /// at `old_state`, is never the bookmark a non-bare repository has
1015
    /// checked out (a bare one's default is its host's to protect, see
1016
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1017
    /// an attestation by a key that may update it.
1018
    /// The deletion's attestation stays the bookmark's latest, so an older
1019
    /// one cannot be replayed to bring it back.
10203×
    fn apply_deletion(
10213×
        &self,
10223×
        view: &mut View,
10233×
        u: &RefUpdate,
10243×
        policy: Option<&crate::policy::Policy>,
10253×
    ) -> std::result::Result<(), String> {
10263×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
10270×
            return Err(format!("no bookmark {:?} to delete", u.name));
1028
        };
10293×
        if current != u.old_state {
10300×
            return Err("stale: the remote bookmark has moved; pull first".into());
10313×
        }
10323×
        if !self.is_bare() && u.name == self.config.bookmark {
10331×
            return Err(format!(
10341×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
10351×
                u.name
10361×
            ));
10372×
        }
10382×
        if let Some(p) = policy {
10390×
            let Some(sa) = &u.attestation else {
10400×
                return Err(format!(
10410×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
10420×
                    u.name
10430×
                ));
1044
            };
10450×
            let signer = sa
10460×
                .sigs
10470×
                .first()
10480×
                .map(|s| s.key)
10490×
                .ok_or("attestation carries no signature")?;
1050
            // Received now: the receiver's own clock is the trusted time.
10510×
            let now = Hlc::now().wall_ms;
10520×
            if !p.authorizes(&signer, &u.name)
10530×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
10540×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1055
            {
10560×
                return Err(format!(
10570×
                    "key {} may not delete {:?} under this repository's policy",
10580×
                    signer.short(12),
10590×
                    u.name
10600×
                ));
10610×
            }
10622×
        }
10632×
        if let Some(sa) = &u.attestation {
10641×
            self.record_update_attest(u, sa)?;
10651×
        }
10662×
        view.bookmarks.remove(&u.name);
10672×
        Ok(())
10683×
    }
1069
1070303×
    fn apply_update(
1071303×
        &self,
1072303×
        view: &mut View,
1073303×
        u: &RefUpdate,
1074303×
        policy: Option<&crate::policy::Policy>,
1075303×
    ) -> std::result::Result<(), String> {
1076303×
        if u.name == "policy" {
10770×
            return Err(
10780×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
10790×
            );
1080303×
        }
1081303×
        let empty = self
1082303×
            .store
1083303×
            .put_state(&StateObject::new(vec![]))
1084303×
            .map_err(|e| e.to_string())?;
1085303×
        if u.new_state.is_zero() {
10863×
            return self.apply_deletion(view, u, policy);
1087300×
        }
1088300×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1089300×
        if current != u.old_state {
10909×
            return Err("stale: the remote bookmark has moved; pull first".into());
1091291×
        }
1092291×
        let new_state = self
1093291×
            .store
1094291×
            .get_state(&u.new_state)
1095291×
            .map_err(|_| "new state object is missing".to_string())?;
1096538×
        for h in &new_state.heads {
1097538×
            if !self.store.has(h) {
10981×
                return Err(format!("head {} is missing", h.short(12)));
1099537×
            }
1100
        }
1101290×
        if !u.force {
1102289×
            let old_heads = self
1103289×
                .store
1104289×
                .get_state(&current)
1105289×
                .map_err(|e| e.to_string())?
1106
                .heads;
1107289×
            let closure = self
1108289×
                .closure_in_store(&new_state.heads)
1109289×
                .map_err(|e| e.to_string())?;
1110289×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
11111×
                return Err(format!(
11121×
                    "not a fast-forward: current head {} would be dropped (use --force)",
11131×
                    h.short(12)
11141×
                ));
1115288×
            }
11161×
        }
1117289×
        if let Some(p) = policy {
111838×
            let Some(sa) = &u.attestation else {
11191×
                return Err(format!(
11201×
                    "{:?} requires a signed reference attestation under this repository's policy",
11211×
                    u.name
11221×
                ));
1123
            };
112437×
            let signer = sa
112537×
                .sigs
112637×
                .first()
112737×
                .map(|s| s.key)
112837×
                .ok_or("attestation carries no signature")?;
1129
            // Received now: the receiver's own clock is the trusted time.
113037×
            let now = Hlc::now().wall_ms;
113137×
            if !p.authorizes(&signer, &u.name)
113211×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11339×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1134
            {
11357×
                return Err(format!(
11367×
                    "key {} may not update {:?} under this repository's policy",
11377×
                    signer.short(12),
11387×
                    u.name
11397×
                ));
114030×
            }
114130×
            let old_heads = self
114230×
                .store
114330×
                .get_state(&current)
114430×
                .map_err(|e| e.to_string())?
1145
                .heads;
114630×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1147251×
        }
1148281×
        if let Some(sa) = &u.attestation {
114983×
            self.record_update_attest(u, sa)?;
1150198×
        }
1151275×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1152275×
        Ok(())
1153303×
    }
1154
1155
    // ------------------------------------------------------------ client side
1156
11571329×
    fn remote_url(&self, name: &str) -> Result<String> {
11581329×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
11593×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
11603×
            RepoError::Msg(match names.as_slice() {
11613×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
11621×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1163
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
11641×
                    names.join(", "),
11651×
                    names[0],
11661×
                    names[0]
1167
                ),
11680×
                _ => format!(
1169
                    "no remote named {name:?}; this repository has {}",
11700×
                    names.join(", ")
1171
                ),
1172
            })
11733×
        })
11741329×
    }
1175
1176
    /// Refuse a remote that is another repository. An **unbound** remote
1177
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1178
    /// for pushes, which bind it to this repository's id (spec §16.1).
1179723×
    fn check_remote_id(
1180723×
        &self,
1181723×
        remote: &dyn crate::protocol::Remote,
1182723×
        remote_name: &str,
1183723×
        allow_unbound: bool,
1184723×
    ) -> Result<()> {
1185723×
        let theirs = remote.repo_id()?;
1186722×
        if theirs == self.id()? {
1187699×
            return Ok(());
118823×
        }
118923×
        if theirs == crate::protocol::UNBOUND_ID {
119020×
            if allow_unbound {
119119×
                return Ok(());
11921×
            }
11931×
            return fail(format!(
1194
                "remote {remote_name:?} is empty and unbound: push to it first"
1195
            ));
11963×
        }
11973×
        fail(format!(
1198
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1199
        ))
1200723×
    }
1201
1202
    /// Credentials and trust for a remote: `remote.<name>.token` and
1203
    /// `remote.<name>.ca`, else the defaults for its URL
1204
    /// ([`Repo::fill_credentials`]).
1205993×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
1206993×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
1207993×
        let mut options = RemoteOptions {
1208993×
            repo_id: self.id().ok(),
1209993×
            token: self.config.remote_tokens.get(name).cloned(),
1210993×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
1211993×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
1212993×
            ..RemoteOptions::default()
1213993×
        };
1214993×
        self.fill_credentials(&url, &mut options);
1215993×
        options
1216993×
    }
1217
1218
    /// The user's credential store (`credentials.toml` beside the user
1219
    /// configuration file).
12201012×
    pub fn credentials(&self) -> crate::credentials::Credentials {
12211012×
        crate::credentials::Credentials::at(
12221012×
            self.user_config
12231012×
                .parent()
12241012×
                .map(Path::to_path_buf)
12251012×
                .unwrap_or_else(default_home),
1226
        )
12271012×
    }
1228
1229
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1230
    /// then the user's credential store for its hub, then a remote on the
1231
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1232
    /// When the token is not this remote's own or the environment's, the
1233
    /// other tokens enclosing checkouts hold for the hub are kept to try
1234
    /// if it is refused: a stale stored login must not hide a parent's
1235
    /// good token (oxygen#112).
12361013×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
12371013×
        if options.token.is_some() && options.ca.is_some() {
12381×
            return;
12391012×
        }
12401012×
        let explicit =
12411012×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
12421012×
        let stored = self.credentials().options_for(url);
12431012×
        options.token = options.token.take().or(stored.token);
12441012×
        options.ca = options.ca.take().or(stored.ca);
12451012×
        let enclosing = self.enclosing_credentials(url);
12461012×
        if options.token.is_none() {
12471002×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
124810×
        }
12491012×
        if options.ca.is_none() {
1250981×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
125131×
        }
12521012×
        if !explicit {
12531005×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
12545×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
12552×
                    options.fallback_tokens.push(t);
12563×
                }
1257
            }
12587×
        }
12591013×
    }
1260
1261
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1262
    /// checkouts, nearest first.
12631012×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
12641012×
        let mut out = Vec::new();
12651012×
        let Some(hub) = crate::credentials::hub_of(url) else {
1266878×
            return out;
1267
        };
1268134×
        let mut at = self.root.parent();
1269544×
        while let Some(dir) = at {
1270410×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
12710×
                break;
1272
            };
1273410×
            for (key, remote_url) in &cfg {
127415×
                let Some(name) = key
127515×
                    .strip_prefix("remote.")
127615×
                    .and_then(|k| k.strip_suffix(".url"))
1277
                else {
12787×
                    continue;
1279
                };
12808×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
12811×
                    continue;
12827×
                }
12837×
                out.push((
12847×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
12857×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
12867×
                ));
1287
            }
1288410×
            at = dir.parent();
1289
        }
1290134×
        out
12911012×
    }
1292
1293
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1294
    /// no changes and no reference updates, which the receiver stores.
12950×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
12960×
        let remote = self.open_named_remote(remote_name)?;
12970×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
12980×
        let mut bundle = Bundle::default();
12990×
        for r in seals {
13000×
            let attest = self.store.get_attest(r)?;
13010×
            let sigs = self.store.signatures(r)?;
13020×
            bundle
13030×
                .attests
13040×
                .push(crate::protocol::SignedAttest { attest, sigs });
1305
        }
13060×
        let results = remote.push(bundle, vec![], None, vec![])?;
13070×
        if let Some(r) = results.iter().find(|r| !r.ok) {
13080×
            return fail(format!("{}: {}", r.name, r.reason));
13090×
        }
13100×
        Ok(())
13110×
    }
1312
1313
    /// The remote whose URL starts with `base` (a hub), if configured.
13144×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
13154×
        let base = base.trim_end_matches('/');
13164×
        self.config
13174×
            .remotes
13184×
            .iter()
13194×
            .find(|(_, url)| url.trim_end_matches('/') == base)
13204×
            .map(|(name, _)| name.clone())
13214×
    }
1322
1323
    /// Open a remote by name or, failing that, by URL with the default
1324
    /// credentials (see [`Repo::credentials_for`]).
13250×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
13260×
        if let Some(name) = self.remote_for_url(url) {
13270×
            return Ok((name.clone(), self.open_named_remote(&name)?));
13280×
        }
13290×
        let options = RemoteOptions {
13300×
            repo_id: self.id().ok(),
13310×
            ..self.credentials_for(url)
13320×
        };
13330×
        Ok((url.to_string(), open_remote(url, &options)?))
13340×
    }
1335
1336
    /// Credentials for a URL: those of the configured remote with that
1337
    /// URL, else the environment's.
13384×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
13394×
        match self.remote_for_url(url) {
13404×
            Some(name) => self.remote_options(&name),
13410×
            None => RemoteOptions {
13420×
                repo_id: self.id().ok(),
13430×
                ..self.credentials_for(url)
13440×
            },
1345
        }
13464×
    }
1347
1348976×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1349976×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1350976×
    }
1351
1352124×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1353124×
        self.oxy
1354124×
            .join("remotes")
1355124×
            .join(remote)
1356124×
            .join(format!("{bookmark}.serial"))
1357124×
    }
1358
135930×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
136030×
        fs::read_to_string(self.serial_path(remote, bookmark))
136130×
            .ok()
136230×
            .and_then(|s| s.trim().parse().ok())
136330×
    }
1364
136594×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
136694×
        let p = self.serial_path(remote, bookmark);
136794×
        fs::create_dir_all(p.parent().unwrap())?;
136894×
        write_atomic(&p, serial.to_string().as_bytes())
136994×
    }
1370
1371395×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1372395×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1373395×
    }
1374
1375
    /// The highest policy serial `remote` has ever presented.
1376353×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1377353×
        fs::read_to_string(self.policy_serial_path(remote))
1378353×
            .ok()
1379353×
            .and_then(|s| s.trim().parse().ok())
1380353×
    }
1381
138242×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
138342×
        let p = self.policy_serial_path(remote);
138442×
        fs::create_dir_all(p.parent().unwrap())?;
138542×
        write_atomic(&p, serial.to_string().as_bytes())
138642×
    }
1387
138827×
    fn lazy_dir(&self) -> PathBuf {
138927×
        self.oxy.join("lazy")
139027×
    }
1391
1392
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
13934×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
13944×
        fs::create_dir_all(self.lazy_dir())?;
13954×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
13964×
    }
1397
1398
    /// Which remote promised an absent blob, if any.
139915×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
140015×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
140115×
            .ok()
140215×
            .map(|s| s.trim().to_string())
140315×
    }
1404
1405
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
14064×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
14074×
        let Some(remote_name) = self.lazy_remote(blob) else {
14080×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1409
        };
14104×
        let remote = self.open_named_remote(&remote_name)?;
14114×
        let objects = remote.objects(&[*blob])?;
14129×
        for (ty, body) in objects {
14139×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
14149×
                self.store.put(ty, &body)?;
14150×
            }
1416
        }
14174×
        if !self.store.has(blob) {
14180×
            return fail(format!(
1419
                "{remote_name} did not send blob {}",
14200×
                blob.short(12)
1421
            ));
14224×
        }
14234×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
14244×
        Ok(())
14254×
    }
1426
1427
    /// After importing from `remote`, record every blob the changes reference
1428
    /// that the store lacks as lazily available from that remote.
14294×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
14304×
        let mut n = 0;
14314×
        for h in changes {
14324×
            let c = self.store.get_change(h)?;
143313×
            for e in &c.edits {
143413×
                if let Edit::Replace { old, new, .. } = e {
14356×
                    for b in [old, new].into_iter().flatten() {
14366×
                        if !self.store.has(b) {
14374×
                            self.register_lazy(b, remote)?;
14384×
                            n += 1;
14392×
                        }
1440
                    }
14417×
                }
1442
            }
1443
        }
14444×
        Ok(n)
14454×
    }
1446
1447
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1448353×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1449353×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1450472×
        for st in view
1451353×
            .bookmarks
1452353×
            .values()
1453353×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1454
        {
1455472×
            if let Ok(s) = self.store.get_state(st) {
1456472×
                have.extend(s.heads);
1457472×
            }
1458
        }
1459353×
        have.extend(view.workspaces.values().copied());
1460353×
        Ok(have.into_iter().collect())
1461353×
    }
1462
1463
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1464359×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1465359×
        let remote = self.open_named_remote(remote_name)?;
1466356×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1467354×
        let resp = remote.refs()?;
1468
        // The host's transparency log (spec §14.8): a fork fails here.
1469353×
        let log_notes = self.check_log(
1470353×
            &self.remote_url(remote_name)?,
1471353×
            self.config.remote_cas.get(remote_name).map(Path::new),
1472353×
            &resp,
14730×
        )?;
1474
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1475
        // and signed by roots we trust, or on first contact. A remote that
1476
        // once presented a policy may never present none or an older one:
1477
        // that is a downgrade. A remote that never presented one is
1478
        // unverified, and this fetch is checked only as far as possible.
1479353×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1480353×
        let seen = self.remote_policy_serial(remote_name);
1481353×
        let mut unverified = false;
1482353×
        match &resp.policy {
148319×
            Some(sp) => {
148419×
                if seen.is_some_and(|s| sp.policy.serial < s) {
14850×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
148619×
                }
14878×
                match &local_policy {
14888×
                    Some(l) if sp.policy.serial < l.serial => {}
14898×
                    Some(l) if sp.policy.serial == l.serial => {
14904×
                        if sp.policy.hash() != l.hash() {
14910×
                            return fail(format!(
1492
                                "{remote_name} presents a different policy with the same serial {}",
1493
                                l.serial
1494
                            ));
14954×
                        }
1496
                    }
1497
                    _ => {
149815×
                        self.adopt_policy_chain(
149915×
                            &resp.history,
150015×
                            sp,
150115×
                            &format!("oxy fetch {remote_name}"),
1502
                        )
150315×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1504
                    }
1505
                }
150619×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1507
            }
1508
            None => {
1509334×
                if seen.is_some() {
15100×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1511334×
                }
1512334×
                unverified = true;
1513
            }
1514
        }
1515353×
        let policy = if unverified {
1516334×
            None
1517
        } else {
151819×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1519
        };
1520353×
        let (op_ref, op) = self.head_op()?;
1521353×
        let mut view = op.view.clone();
1522353×
        let have = self.known_heads(&view)?;
1523353×
        let mut report = Vec::new();
1524353×
        let max_blob = self.config.max_blob;
1525360×
        for r in resp.refs {
1526360×
            let needed = {
1527360×
                let _t = crate::timing::phase("fetch: negotiate");
1528360×
                remote.negotiate(&have, &r.heads)?
1529
            };
1530360×
            let bundle = {
1531360×
                let _t = crate::timing::phase("fetch: bundle");
1532360×
                remote.fetch(&needed, max_blob)?
1533
            };
1534
            // Changes are not individually re-verified here: the bookmark's
1535
            // attestation (checked below) binds its whole state, and the
1536
            // receiver of the push verified the added changes at that time.
1537360×
            let imported = {
1538360×
                let _t = crate::timing::phase("fetch: import");
1539360×
                self.import_bundle(&bundle, false)?
1540
            };
1541360×
            if max_blob.is_some() {
15424×
                self.register_missing_blobs(&imported, remote_name)?;
1543356×
            }
1544485×
            for h in &r.heads {
1545485×
                if !self.store.has(h) {
15460×
                    return fail(format!("remote did not send head {}", h.short(12)));
1547485×
                }
1548
            }
1549360×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1550360×
            if state != r.state {
15510×
                return fail(format!(
1552
                    "remote state {} does not match its heads",
15530×
                    r.state.short(12)
1554
                ));
1555360×
            }
1556360×
            if let Some(p) = &policy {
155719×
                let Some(sa) = &r.attestation else {
15580×
                    return fail(format!(
1559
                        "{remote_name}/{} has no attestation, which its policy requires",
1560
                        r.name
1561
                    ));
1562
                };
156319×
                let signer = sa
156419×
                    .sigs
156519×
                    .first()
156619×
                    .map(|s| s.key)
156719×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1568
                // A certified signer is checked at the host's acceptance,
1569
                // when it countersigned one; else at the attestation's time.
157019×
                let at = self.certified_time(&signer, sa, r.accepted.as_ref());
157119×
                if !p.authorizes(&signer, &r.name)
15728×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
15738×
                    && !self.certified_authorized(p, &signer, &r.name, Scope::REFS, at)
1574
                {
15750×
                    return fail(format!(
1576
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1577
                        r.name,
15780×
                        signer.short(12)
1579
                    ));
158019×
                }
1581341×
            }
1582360×
            if let Some(sa) = &r.attestation {
1583
                let AttestBody::Ref {
158430×
                    old_state,
158530×
                    new_state,
1586
                    ..
158730×
                } = &sa.attest.body
1588
                else {
15890×
                    return fail("remote sent a non-ref attestation for a bookmark");
1590
                };
159130×
                let (old_state, new_state) = (*old_state, *new_state);
159230×
                let serial = self
159330×
                    .check_ref_attest(
159430×
                        sa,
159530×
                        &r.name,
159630×
                        &old_state,
159730×
                        &new_state,
159830×
                        self.last_seen_serial(remote_name, &r.name),
1599
                        true,
1600
                    )
160130×
                    .map_err(|e| {
16020×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
16030×
                    })?;
160430×
                if new_state != r.state {
16050×
                    return fail(format!(
1606
                        "attestation for {}/{} does not cover its current state",
1607
                        remote_name, r.name
1608
                    ));
160930×
                }
161030×
                let ar = self.store.put_attest(&sa.attest)?;
161130×
                for sig in &sa.sigs {
161230×
                    self.store.put_signature(&ar, sig)?;
1613
                }
161430×
                self.record_serial(remote_name, &r.name, serial)?;
1615330×
            }
1616360×
            view.remotes
1617360×
                .entry(remote_name.to_string())
1618360×
                .or_default()
1619360×
                .insert(r.name.clone(), state);
1620360×
            report.push((r.name, r.heads, imported.len()));
1621
        }
1622353×
        let mut new_tags = 0;
1623353×
        for t in &resp.tags {
162413×
            if view.tags.contains_key(&t.name) {
16254×
                continue;
16269×
            }
1627
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
16289×
            let missing: Vec<ChangeHash> = t
16299×
                .heads
16309×
                .iter()
16319×
                .filter(|h| !self.store.has(h))
16329×
                .copied()
16339×
                .collect();
16349×
            if !missing.is_empty() {
16350×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
16360×
                let bundle = remote.fetch(&needed, max_blob)?;
16370×
                self.import_bundle(&bundle, false)?;
16389×
            }
16399×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
16409×
            self.adopt_tag(&mut view, t, policy.as_ref())
16419×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
16429×
            new_tags += 1;
1643
        }
1644353×
        if view != op.view {
1645342×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
164611×
        }
1647353×
        let _ = self.run_hook(
1648353×
            "post-fetch",
1649353×
            &format!(
1650
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1651353×
                json_str(remote_name),
1652360×
                json_array(report.iter().map(|(n, heads, _)| format!(
1653
                    "{{\"name\":{},\"heads\":{}}}",
1654360×
                    json_str(n),
1655485×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1656
                )))
1657
            ),
1658
        );
1659353×
        Ok(FetchReport {
1660353×
            refs: report,
1661353×
            unverified,
1662353×
            new_tags,
1663353×
            log_notes,
1664353×
        })
1665359×
    }
1666
1667
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1668
    /// the changes within `depth` steps of its heads, and the boundary below.
16691×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
16701×
        let remote = self.open_named_remote(remote_name)?;
16711×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
16721×
        let resp = remote.refs()?;
16731×
        let bookmark = self.config.bookmark.clone();
16741×
        if let Some(sp) = &resp.policy {
16750×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
16760×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
16770×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
16781×
        }
16791×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
16800×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1681
        };
16821×
        if r.heads.is_empty() {
16830×
            return Ok(0);
16841×
        }
1685
        // Base: the remote's checkpoint of exactly these heads.
16861×
        let cp_bundle = remote.checkpoint(&r.heads)?;
16871×
        let mut cp_ref = None;
16883×
        for (ty, body) in &cp_bundle.objects {
16893×
            let put = self.store.put(*ty, body)?;
16903×
            if *ty == ObjectType::Checkpoint {
16911×
                cp_ref = Some(put);
16922×
            }
1693
        }
16941×
        let Some(cp_ref) = cp_ref else {
16950×
            return fail(format!("{remote_name} sent no checkpoint"));
1696
        };
16971×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1698
        // History window.
16991×
        let wanted = remote.shallow(&r.heads, depth)?;
17001×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
17011×
        let imported = self.import_bundle_shallow(&bundle, false)?;
17021×
        if self.config.max_blob.is_some() {
17030×
            self.register_missing_blobs(&imported, remote_name)?;
17041×
        }
17051×
        self.refresh_boundary(&imported)?;
17061×
        if let Some(sa) = &r.attestation {
17070×
            let ar = self.store.put_attest(&sa.attest)?;
17080×
            for sig in &sa.sigs {
17090×
                self.store.put_signature(&ar, sig)?;
1710
            }
17110×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
17120×
                self.record_serial(remote_name, &r.name, serial)?;
17130×
            }
17141×
        }
17151×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
17161×
        let (op_ref, op) = self.head_op()?;
17171×
        let mut view = op.view.clone();
17181×
        view.remotes
17191×
            .entry(remote_name.to_string())
17201×
            .or_default()
17211×
            .insert(r.name.clone(), state);
17221×
        self.record_op(
17231×
            &[op_ref],
17241×
            &format!("oxy fetch {remote_name} --depth {depth}"),
17251×
            view,
17260×
        )?;
17271×
        Ok(imported.len())
17281×
    }
1729
1730
    /// Fetch, then take the union of the local bookmark's state with the
1731
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1732102×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1733102×
        let _wc = self.lock_working_copy()?;
1734102×
        self.fetch(remote_name)?;
173599×
        let (op_ref, op) = self.head_op()?;
173699×
        let current = self.config.bookmark.clone();
173799×
        let mut local_current = self.heads_of(&op.view, &current)?;
173899×
        local_current.sort();
173999×
        let mut view = op.view.clone();
174099×
        let mut current_heads = local_current.clone();
174199×
        let mut changed = false;
174299×
        let mut others = Vec::new();
174399×
        let tracked = op
174499×
            .view
174599×
            .remotes
174699×
            .get(remote_name)
174799×
            .cloned()
174899×
            .unwrap_or_default();
1749103×
        for (name, remote_state) in tracked {
1750
            // Every local bookmark tracks the remote's of the same name;
1751
            // the current one may be new here.
1752103×
            let local_state = op.view.bookmarks.get(&name).copied();
1753103×
            if local_state.is_none() && name != current {
17540×
                continue;
1755103×
            }
1756103×
            if local_state == Some(remote_state) {
17579×
                continue;
175894×
            }
175994×
            let local = self.heads_of(&op.view, &name)?;
176094×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1761123×
            if remote_heads.iter().all(|h| local.contains(h)) {
17620×
                continue;
176394×
            }
176494×
            let mut all = local.clone();
176594×
            all.extend(remote_heads);
176694×
            let st = self.load_state_history(&all)?;
176794×
            let mut heads = st.maximal(&all);
176894×
            heads.sort();
176994×
            let mut sorted_local = local;
177094×
            sorted_local.sort();
177194×
            if heads == sorted_local {
17721×
                continue;
177393×
            }
177493×
            view.bookmarks.insert(
177593×
                name.clone(),
177693×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1777
            );
177893×
            if name == current {
177991×
                changed = true;
178091×
                current_heads = heads;
178191×
            } else {
17822×
                others.push(name);
17832×
            }
1784
        }
178599×
        if changed || !others.is_empty() {
178692×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
17877×
        }
1788
        // The working copy follows its bookmark whenever nothing would be
1789
        // lost, also when this pull brought nothing new but it had been
1790
        // left behind (oxygen#89).
179199×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1792
        Ok(PullReport {
179399×
            heads: if changed {
179491×
                current_heads
1795
            } else {
17968×
                local_current
1797
            },
179899×
            changed,
179999×
            checked_out,
180099×
            others,
1801
        })
1802102×
    }
1803
1804
    /// How many changes the working copy's bookmark has that its base
1805
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1806
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1807
    /// the bookmark or holds changes the bookmark lacks. History is read
1808
    /// only when the base and the bookmark's heads differ (oxygen#89).
18097×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
18107×
        let (_, wc) = self.working_copy()?;
18117×
        let mut base = wc.deps.clone();
18127×
        base.sort();
18137×
        let mut heads = self.bookmark_heads()?;
18147×
        heads.sort();
18157×
        if base == heads || heads.is_empty() {
18166×
            return Ok(None);
18171×
        }
18181×
        let state = self.load_state_history(&heads)?;
18191×
        if !base.iter().all(|h| state.contains(h)) {
18200×
            return Ok(None);
18211×
        }
18221×
        let had = if base.is_empty() {
18230×
            0
1824
        } else {
18251×
            self.load_state_history(&base)?.len()
1826
        };
18271×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
18287×
    }
1829
1830
    /// Bring the working copy to `heads`, the state of its bookmark
1831
    /// `bookmark`, when nothing would be lost: its base is part of that
1832
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1833
    /// with uncommitted work, the work comes along when the new changes
1834
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1835
    /// it followed only from exactly the bookmark's old heads, so a working
1836
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1837
    /// or a pull from another workspace) never caught up, and nothing said
1838
    /// so (oxygen#74, #89). Returns whether it moved.
183999×
    pub fn follow_bookmark(
184099×
        &self,
184199×
        heads: &[ChangeHash],
184299×
        bookmark: &str,
184399×
        command: &str,
184499×
    ) -> Result<bool> {
184599×
        let snap = self.snapshot(command)?;
184699×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
184799×
        let mut base = snap.base.maximal(&snap.wc.deps);
184899×
        base.sort();
184999×
        let mut target = heads.to_vec();
185099×
        target.sort();
185199×
        if base == target {
18527×
            return Ok(false);
185392×
        }
185492×
        let state = self.load_state_history(heads)?;
1855163×
        if !base.iter().all(|h| state.contains(h)) {
1856
            // The working copy holds changes the bookmark lacks: not ours to move.
18570×
            return Ok(false);
185892×
        }
185992×
        if clean {
186092×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
186192×
            Ok(true)
1862
        } else {
18630×
            Ok(self
18640×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
18650×
                .is_ok())
1866
        }
186799×
    }
1868
1869
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1870
    /// changes and attesting the reference when a key is available.
1871
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1872
    /// state, attested when we have an identity. The local bookmark, if
1873
    /// any, is kept; only the remote-tracking entry goes.
18745×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
18755×
        let remote = self.open_named_remote(remote_name)?;
18765×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
18775×
        let resp = remote.refs()?;
18787×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
18791×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1880
        };
18814×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
18820×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
18834×
        }
18844×
        let attestation = match self.secret_key()? {
18852×
            Some(_) => Some(self.sign_attest(&Attest {
18862×
                repo: self.id()?,
18872×
                hlc: Hlc::now(),
18882×
                body: AttestBody::Ref {
18892×
                    name: bookmark.to_string(),
18902×
                    old_state: r.state,
18912×
                    new_state: ObjectRef::ZERO,
18922×
                    serial: r.last_serial.unwrap_or(0) + 1,
18932×
                },
18940×
            })?),
18952×
            None => None,
1896
        };
18974×
        let results = remote.push(
18984×
            Bundle::default(),
18994×
            vec![RefUpdate {
19004×
                name: bookmark.to_string(),
19014×
                old_state: r.state,
19024×
                new_state: ObjectRef::ZERO,
19034×
                force: true,
19044×
                attestation,
19054×
            }],
19064×
            None,
19074×
            vec![],
19080×
        )?;
19094×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
19102×
            let (op_ref, op) = self.head_op()?;
19112×
            let mut view = op.view.clone();
19122×
            if let Some(m) = view.remotes.get_mut(remote_name) {
19132×
                m.remove(bookmark);
19142×
            }
19152×
            self.record_op(
19162×
                &[op_ref],
19172×
                &format!("oxy push {remote_name} --delete {bookmark}"),
19182×
                view,
19190×
            )?;
19202×
        }
19214×
        Ok(results)
19225×
    }
1923
1924
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1925
    /// repository's config (its URL, token, CA and store settings), its
1926
    /// tracking bookmarks in the view, and a store remote's mirror under
1927
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
19283×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
19293×
        if !self.config.remotes.contains_key(name) {
19301×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
19312×
        }
19322×
        let prefix = format!("remote.{name}.");
19332×
        let keys: Vec<String> = self
19342×
            .config
19352×
            .repo_layer()
19362×
            .keys()
19374×
            .filter(|k| k.starts_with(&prefix))
19382×
            .cloned()
19392×
            .collect();
19403×
        for k in keys {
19413×
            self.config.set(&k, "")?;
1942
        }
19432×
        self.config.remotes.remove(name);
19442×
        self.save_config()?;
19452×
        let (op_ref, op) = self.head_op()?;
19462×
        if op.view.remotes.contains_key(name) {
19471×
            let mut view = op.view.clone();
19481×
            view.remotes.remove(name);
19491×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
19501×
        }
19512×
        let mirror = self.oxy.join("remotes").join(name);
19522×
        if mirror.is_dir() {
19530×
            fs::remove_dir_all(&mirror)?;
19542×
        }
19552×
        Ok(())
19563×
    }
1957
1958
    /// `changes`, in dependency order, cut into batches of about
1959
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1960
    /// There is always one, perhaps empty.
1961283×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1962283×
        let blob_len = |r: &ObjectRef| -> u64 {
196329×
            self.store
196429×
                .get_typed(r, ObjectType::Blob)
196529×
                .ok()
196629×
                .and_then(|b| Blob::decode(&b).ok())
196729×
                .map_or(0, |b| b.length)
196829×
        };
1969283×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1970387×
        for h in changes {
1971387×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1972387×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1973387×
            let mut weight = raw.len() as u64;
1974520×
            for t in &texts {
1975520×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
197626×
                    weight += blob_len(r);
1977494×
                }
1978
            }
1979659×
            for e in &c.edits {
19803×
                if let Edit::Replace { new: Some(b), .. } = e {
19813×
                    weight += blob_len(b);
1982656×
                }
1983
            }
1984387×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
19855×
                out.push(std::mem::take(&mut batch));
19865×
                bytes = 0;
1987382×
            }
1988387×
            batch.push(*h);
1989387×
            bytes += weight;
1990
        }
1991283×
        out.push(batch);
1992283×
        Ok(out)
1993283×
    }
1994
1995346×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1996346×
        let bookmark = self.config.bookmark.clone();
1997346×
        self.push_bookmark(remote_name, &bookmark, force)
1998346×
    }
1999
2000
    /// `push` for a named bookmark (`oxy push -b NAME`).
2001354×
    pub fn push_bookmark(
2002354×
        &self,
2003354×
        remote_name: &str,
2004354×
        bookmark: &str,
2005354×
        force: bool,
2006354×
    ) -> Result<Vec<RefResult>> {
2007354×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2008354×
    }
2009
2010
    /// `push_bookmark`, saying how a long push is going: one line per
2011
    /// batch sent (oxygen#95).
2012362×
    pub fn push_bookmark_with(
2013362×
        &self,
2014362×
        remote_name: &str,
2015362×
        bookmark: &str,
2016362×
        force: bool,
2017362×
        progress: crate::store::Progress,
2018362×
    ) -> Result<Vec<RefResult>> {
2019362×
        let (op_ref, op) = self.head_op()?;
2020362×
        if !op.view.bookmarks.contains_key(bookmark) {
20210×
            return fail(format!("no bookmark {bookmark}"));
2022362×
        }
2023362×
        let bookmark = bookmark.to_string();
2024362×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2025
        // pre-push hook: may veto before the remote is contacted.
2026362×
        self.run_hook(
2027362×
            "pre-push",
2028362×
            &format!(
2029
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2030362×
                json_str(remote_name),
2031362×
                json_str(&bookmark),
2032718×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2033
            ),
20341×
        )?;
2035361×
        let remote = self.open_named_remote(remote_name)?;
2036361×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2037358×
        let resp = remote.refs()?;
2038358×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2039358×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2040358×
        let policy_to_send = match (&local_policy, &resp.policy) {
204129×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
204210×
            (Some(l), None) => Some(l.clone()),
204316×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
20441×
                return fail(format!(
2045
                    "{remote_name} has a newer policy (serial {}); fetch first",
2046
                    r.policy.serial
2047
                ));
2048
            }
2049334×
            _ => None,
2050
        };
2051357×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2052357×
        if remote_has_policy && self.secret_key()?.is_none() {
20531×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2054356×
        }
2055356×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2056356×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2057356×
            .tag_refs()?
2058356×
            .into_iter()
2059356×
            .filter(|t| !remote_tags.contains(&t.name))
2060356×
            .collect();
2061356×
        let refs = resp.refs;
2062356×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2063356×
        let (remote_state, remote_heads, last_serial) =
2064356×
            match refs.iter().find(|r| r.name == bookmark) {
2065339×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
206617×
                None => (empty, vec![], None),
2067
            };
2068356×
        let new_state = self
2069356×
            .store
2070356×
            .put_state(&StateObject::new(local_heads.clone()))?;
2071
        // A push that carries a policy re-attests the bookmark even when its
2072
        // state is unchanged, so the current attestation is always by a key
2073
        // the current policy authorizes (a revoked key's attestation would
2074
        // otherwise be refused by every later fetch).
2075356×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
20769×
            return Ok(vec![RefResult {
20779×
                name: bookmark,
20789×
                ok: true,
20799×
                reason: "already up to date".into(),
20809×
            }]);
2081347×
        }
2082365×
        for h in &remote_heads {
2083365×
            if !self.store.has(h) {
208463×
                return fail(format!(
2085
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
208663×
                    h.short(12)
2087
                ));
2088302×
            }
2089
        }
2090284×
        if !force {
2091284×
            let closure = self.closure_in_store(&local_heads)?;
2092284×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
20930×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2094284×
            }
20950×
        }
2096284×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2097284×
        let key = self.secret_key()?.map(|(k, _)| k);
2098284×
        if let Some(key) = key {
2099
            // Seal this author's changes that carry no valid authenticator,
2100
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2101
            // are stored, so each batch's bundle carries those it needs.
210287×
            let mut unsigned = Vec::new();
210387×
            for h in &to_send {
210479×
                let c = self.store.get_change_meta(h)?;
210579×
                if self.seals_for_author(&c.author, &key)
210676×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
210747×
                {
210847×
                    unsigned.push(*h);
210947×
                }
2110
            }
211187×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
211244×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2113
            }
2114197×
        }
2115
        // A long history goes in batches, in dependency order, so neither
2116
        // side holds it whole and no request passes the remote's limit:
2117
        // all but the last carry objects alone; the last moves the bookmark
2118
        // (oxygen#95).
2119283×
        let batches = self.push_batches(&to_send)?;
2120283×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2121283×
        for (i, batch) in earlier.iter().enumerate() {
21225×
            progress(&format!(
21235×
                "part {} of {}: {} changes",
21245×
                i + 1,
21255×
                batches.len(),
21265×
                batch.len()
21275×
            ));
21285×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
21295×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
21305×
                Some(r) if r.ok => {}
21310×
                Some(r) => {
21320×
                    return fail(format!(
2133
                        "{remote_name} refused part {} of the push: {}",
21340×
                        i + 1,
2135
                        r.reason
2136
                    ))
2137
                }
2138
                None => {
21390×
                    return fail(format!(
2140
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2141
                    ))
2142
                }
2143
            }
2144
        }
2145283×
        if batches.len() > 1 {
21461×
            progress(&format!(
21471×
                "part {} of {}: {} changes",
21481×
                batches.len(),
21491×
                batches.len(),
21501×
                last.len()
21511×
            ));
2152282×
        }
2153283×
        let mut bundle = self.bundle_for(last)?;
2154283×
        bundle.objects.push((
2155283×
            ObjectType::State,
2156283×
            StateObject::new(local_heads.clone()).encode(),
2157283×
        ));
2158283×
        let attestation = match key {
215986×
            Some(_) => Some(self.sign_attest(&Attest {
216086×
                repo: self.id()?,
216186×
                hlc: Hlc::now(),
216286×
                body: AttestBody::Ref {
216386×
                    name: bookmark.clone(),
216486×
                    old_state: remote_state,
216586×
                    new_state,
216686×
                    serial: next_serial(last_serial),
216786×
                },
21681×
            })?),
2169197×
            None => None,
2170
        };
2171
        // Whoever signed the move, and whom a delegate acts for, travel with
2172
        // it: a receiver that has never seen a change by this delegate could
2173
        // not otherwise check its signature (oxygenhub#129).
2174282×
        if attestation.is_some() {
2175170×
            for k in [self.signing_key(), self.config.author_key]
217685×
                .into_iter()
217785×
                .flatten()
2178
            {
2179170×
                if let Ok(id) = self.identity(&k) {
2180170×
                    let body = id.encode();
2181170×
                    if !bundle
2182170×
                        .objects
2183170×
                        .iter()
2184199×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
218517×
                    {
218617×
                        bundle.objects.push((ObjectType::Identity, body));
2187153×
                    }
21880×
                }
2189
            }
2190
            // A short-lived signing key's certificate goes with it (§14.7).
219185×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
219285×
            self.attach_certificates_for(&mut bundle, &signers)?;
2193197×
        }
2194282×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
219585×
            AttestBody::Ref { serial, .. } => Some(serial),
21960×
            _ => None,
219785×
        });
2198282×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2199
        // Tag states must be present on the remote: bundle their changes too.
2200282×
        for t in &tags_to_send {
22016×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
22026×
            let extra: Vec<ChangeHash> =
22036×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
22046×
            if !extra.is_empty() {
22050×
                let more = self.bundle_for(&extra)?;
22060×
                bundle.changes.extend(more.changes);
22070×
                bundle.hashes.extend(more.hashes);
22080×
                bundle.attests.extend(more.attests);
22090×
                bundle.objects.extend(more.objects);
22106×
            }
22116×
            bundle.objects.push((
22126×
                ObjectType::State,
22136×
                StateObject::new(t.heads.clone()).encode(),
22146×
            ));
2215
        }
2216282×
        if let Some(l) = &policy_to_send {
221723×
            let remote_serial = resp_policy_serial;
221823×
            bundle.policies = self
221923×
                .policy_history()?
222023×
                .into_iter()
222150×
                .filter(|sp| {
222250×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
222325×
                        && sp.policy.serial < l.policy.serial
222450×
                })
222523×
                .collect();
2226259×
        }
2227282×
        let results = remote.push(
2228282×
            bundle,
2229282×
            vec![RefUpdate {
2230282×
                name: bookmark.clone(),
2231282×
                old_state: remote_state,
2232282×
                new_state,
2233282×
                force,
2234282×
                attestation,
2235282×
            }],
2236282×
            policy_to_send,
2237282×
            tags_to_send,
22387×
        )?;
223923×
        if let (Some(serial), true) = (
2240275×
            sent_serial,
2241281×
            results.iter().any(|r| r.ok && r.name == "policy"),
2242
        ) {
224323×
            self.record_policy_serial(remote_name, serial)?;
2244252×
        }
2245298×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2246252×
            let mut view = op.view.clone();
2247252×
            view.remotes
2248252×
                .entry(remote_name.to_string())
2249252×
                .or_default()
2250252×
                .insert(bookmark.clone(), new_state);
2251252×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2252249×
            if let Some(s) = serial {
225364×
                self.record_serial(remote_name, &bookmark, s)?;
2254185×
            }
225523×
        }
2256270×
        Ok(results)
2257362×
    }
2258
2259
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2260
    /// bookmark set to the remote's, working copy checked out.
2261233×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2262233×
        Self::clone_with(url, dest, None, &[])
2263233×
    }
2264
2265
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2266
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2267
    /// unless a size is given, so out-of-scope binaries are never fetched).
2268241×
    pub fn clone_with(
2269241×
        url: &str,
2270241×
        dest: &Path,
2271241×
        max_blob: Option<u64>,
2272241×
        sparse: &[String],
2273241×
    ) -> Result<Repo> {
2274241×
        Self::clone_full(url, dest, max_blob, sparse, None)
2275241×
    }
2276
2277
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2278
    /// changes within `depth` steps of them; the rest is the boundary.
22791×
    pub fn clone_shallow(
22801×
        url: &str,
22811×
        dest: &Path,
22821×
        depth: u32,
22831×
        max_blob: Option<u64>,
22841×
        sparse: &[String],
22851×
    ) -> Result<Repo> {
22861×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
22871×
    }
2288
2289242×
    fn clone_full(
2290242×
        url: &str,
2291242×
        dest: &Path,
2292242×
        max_blob: Option<u64>,
2293242×
        sparse: &[String],
2294242×
        depth: Option<u32>,
2295242×
    ) -> Result<Repo> {
2296242×
        let options = crate::credentials::Credentials::user().options_for(url);
2297242×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2298242×
    }
2299
2300
    /// Clone a subrepo with the credentials the parent would use for its
2301
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2302
    /// subrepo: it finds the same ones again through its parent.
23039×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
23049×
        let options = self.credentials_for(url);
23059×
        Self::clone_using(url, dest, None, &[], None, &options)
23069×
    }
2307
2308
    /// The name of a remote of this repository on the same hub (scheme,
2309
    /// host and port) as `url`.
231021×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
231125×
        let origin = |u: &str| -> Option<String> {
231225×
            let (scheme, rest) = u.split_once("://")?;
23138×
            if !matches!(scheme, "http" | "https") {
23140×
                return None;
23158×
            }
23168×
            let host = rest.split('/').next()?;
23178×
            Some(format!(
23188×
                "{}://{}",
23198×
                scheme.to_ascii_lowercase(),
23208×
                host.to_ascii_lowercase()
23218×
            ))
232225×
        };
232321×
        let want = origin(url)?;
23244×
        self.config
23254×
            .remotes
23264×
            .iter()
23274×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
23284×
            .map(|(name, _)| name.clone())
232921×
    }
2330
2331
    /// The token and CA to reach `url` with: those of a remote of this
2332
    /// repository on the same hub (scheme, host and port), else the
2333
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2334
    /// and enclosing checkouts', as a clone would use them.
233521×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
233621×
        match self.remote_on_same_hub(url) {
23371×
            Some(name) => RemoteOptions {
23381×
                repo_id: None,
23391×
                cache_dir: None,
23401×
                ..self.remote_options(&name)
23411×
            },
2342
            None => {
234320×
                let mut options = RemoteOptions::default();
234420×
                self.fill_credentials(url, &mut options);
234520×
                options
2346
            }
2347
        }
234821×
    }
2349
2350251×
    fn clone_using(
2351251×
        url: &str,
2352251×
        dest: &Path,
2353251×
        max_blob: Option<u64>,
2354251×
        sparse: &[String],
2355251×
        depth: Option<u32>,
2356251×
        options: &RemoteOptions,
2357251×
    ) -> Result<Repo> {
2358251×
        let remote = open_remote(url, options)?;
2359251×
        let id = remote.repo_id()?;
2360247×
        if id == crate::protocol::UNBOUND_ID {
23612×
            return fail(format!(
2362
                "{url} is empty and unbound: push a repository to it first"
2363
            ));
2364245×
        }
2365245×
        let mut repo = Repo::init_with_id(dest, id)?;
2366245×
        repo.config
2367245×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2368245×
        if let Some(m) = max_blob {
23692×
            repo.config.set("filter.max-blob", &m.to_string())?;
2370243×
        } else if !sparse.is_empty() {
23711×
            repo.config.set("filter.max-blob", "0")?;
2372242×
        }
2373245×
        if !sparse.is_empty() {
23741×
            repo.config.set("filter.paths", &sparse.join(","))?;
2375244×
        }
2376245×
        repo.save_config()?;
2377245×
        if let Some(depth) = depth {
23781×
            repo.fetch_shallow("origin", depth)?;
2379
        } else {
2380244×
            repo.fetch("origin")?;
2381
        }
2382244×
        let (op_ref, op) = repo.head_op()?;
2383
        // The remote's default bookmark, else ours (main), else its only one.
2384244×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2385
        // Asked of the remote as now configured, so a store-backed one
2386
        // answers from the mirror the fetch just filled.
2387244×
        let advertised = repo
2388244×
            .open_named_remote("origin")
2389244×
            .ok()
2390244×
            .and_then(|r| r.refs().ok())
2391244×
            .and_then(|r| r.default_bookmark);
2392244×
        let bookmark = advertised
2393244×
            .filter(|b| theirs.contains_key(b))
2394244×
            .or_else(|| {
23957×
                theirs
23967×
                    .contains_key(&repo.config.bookmark)
23977×
                    .then(|| repo.config.bookmark.clone())
23987×
            })
2399244×
            .or_else(|| {
24000×
                (theirs.len() == 1)
24010×
                    .then(|| theirs.keys().next().cloned())
24020×
                    .flatten()
24030×
            })
2404244×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2405244×
        let initial = repo.config.bookmark.clone();
2406244×
        if bookmark != repo.config.bookmark {
24071×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
24081×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
24091×
            repo.config.bookmark = bookmark.clone();
2410243×
        }
2411244×
        if let Some(state) = theirs.get(&bookmark).copied() {
2412244×
            let heads = repo.store.get_state(&state)?.heads;
2413244×
            let mut view = op.view.clone();
2414
            // The empty bookmark `init` made goes when another is checked out.
2415244×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
24161×
                view.bookmarks.remove(&initial);
2417243×
            }
2418244×
            view.bookmarks.insert(bookmark, state);
2419244×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2420244×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
24210×
        }
2422244×
        Ok(repo)
2423251×
    }
2424
}
2425
2426
/// The serial of a reference's next attestation: one more than the last the
2427
/// remote reports, or, for a bookmark the remote does not have, the clock in
2428
/// milliseconds, so a bookmark created again after a deletion goes past the
2429
/// deletion's serial the remote keeps.
243086×
fn next_serial(last: Option<u64>) -> u64 {
243186×
    match last {
243256×
        Some(l) => l + 1,
243330×
        None => Hlc::now().wall_ms.max(1),
2434
    }
243586×
}