OXYGENHUB

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

1771 of 1979 lines run, 258 of 376 functions · run #350 on proposal/125 · 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
581354×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
591354×
        self.oxy.join("attest").join(name_file(bookmark))
601354×
    }
61
62
    /// The latest reference attestation stored for a bookmark.
631270×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
641270×
        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
            }
761035×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
770×
            Err(e) => Err(e.into()),
78
        }
791270×
    }
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
861038×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
871038×
        let view = self.view()?;
881038×
        let mut out = Vec::new();
891062×
        for (name, state) in &view.bookmarks {
901062×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
911062×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
92136×
                AttestBody::Ref { serial, .. } => Some(serial),
930×
                _ => None,
94136×
            });
951062×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
961062×
            let accepted = match &attestation {
97125×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
98937×
                None => None,
99
            };
1001062×
            out.push(RemoteRef {
1011062×
                name: name.clone(),
1021062×
                state: *state,
1031062×
                heads: self.store.get_state(state)?.heads,
1041062×
                attestation,
1051062×
                last_serial,
1061062×
                accepted,
1071062×
                logged: None,
1081062×
                integration: vec![],
109
            });
110
        }
1111038×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1121038×
        let history = self
1131038×
            .policy_history()?
1141038×
            .into_iter()
1151038×
            .filter(|sp| {
116126×
                policy
117126×
                    .as_ref()
118126×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
119126×
            })
1201038×
            .collect();
121
        Ok(RefsResponse {
1221038×
            refs: out,
1231038×
            policy,
1241038×
            tags: self.tag_refs()?,
1251038×
            history,
1261038×
            default_bookmark: Some(self.config.bookmark.clone()),
1271038×
            log: None,
1281038×
            witnesses: vec![],
129
        })
1301038×
    }
131
132
    /// Every change reachable from `heads` that is in the store.
1331372×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1341372×
        let mut seen = BTreeSet::new();
1351372×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1364760×
        while let Some(h) = stack.pop() {
1373388×
            if seen.contains(&h) || !self.store.has(&h) {
1381014×
                continue;
1392374×
            }
1402374×
            seen.insert(h);
1412374×
            stack.extend(self.store.get_change_meta(&h)?.deps);
142
        }
1431372×
        Ok(seen)
1441372×
    }
145
146
    /// The changes within `depth` dependency steps of `heads` (spec §17),
147
    /// nearest first; depth 1 is the heads themselves.
1483×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1493×
        let mut out = Vec::new();
1503×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1513×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1523×
        for _ in 0..depth.max(1) {
1538×
            let mut next = Vec::new();
15412×
            for h in layer {
15512×
                if !seen.insert(h) || !self.store.has(&h) {
1562×
                    continue;
15710×
                }
15810×
                let c = self.store.get_change(&h)?;
15910×
                next.extend(c.deps.iter().copied());
16010×
                out.push(h);
161
            }
1628×
            if next.is_empty() {
1631×
                break;
1647×
            }
1657×
            layer = next;
166
        }
1673×
        out.reverse();
1683×
        Ok(out)
1693×
    }
170
1711979×
    fn shallow_path(&self) -> PathBuf {
1721979×
        self.oxy.join("shallow")
1731979×
    }
174
175
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1761976×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1771976×
        fs::read_to_string(self.shallow_path())
1781976×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1791976×
            .unwrap_or_default()
1801976×
    }
181
182190×
    pub fn is_shallow(&self) -> bool {
183190×
        !self.boundary().is_empty()
184190×
    }
185
1863×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1873×
        if boundary.is_empty() {
1881×
            let _ = fs::remove_file(self.shallow_path());
1891×
            return Ok(());
1902×
        }
1912×
        let text: String = boundary
1922×
            .iter()
1932×
            .map(|h| format!("{}\n", h.to_hex()))
1942×
            .collect();
1952×
        write_atomic(&self.shallow_path(), text.as_bytes())
1963×
    }
197
198
    /// Recompute the boundary from what is stored: every dependency of a
199
    /// stored change that is not itself stored.
2003×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2013×
        let mut boundary = self.boundary();
2023×
        boundary.retain(|h| !self.store.has(h));
20310×
        for h in imported {
20413×
            for d in self.store.get_change_meta(h)?.deps {
20513×
                if !self.store.has(&d) {
2062×
                    boundary.insert(d);
20711×
                }
208
            }
209
        }
2103×
        self.write_boundary(&boundary)
2113×
    }
212
213
    /// Fetch `depth` more levels of history below the shallow boundary.
2142×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2152×
        let boundary = self.boundary();
2162×
        if boundary.is_empty() {
2170×
            return Ok(0);
2182×
        }
2192×
        let remote = self.open_named_remote(remote_name)?;
2202×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2212×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2222×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2232×
        if self.config.max_blob.is_some() {
2240×
            self.register_missing_blobs(&imported, remote_name)?;
2252×
        }
2262×
        self.refresh_boundary(&imported)?;
2272×
        Ok(imported.len())
2282×
    }
229
230
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
231785×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
232785×
        let have = self.closure_in_store(have)?;
233
        // In a shallow repository the walk stops at the boundary, whose
234
        // changes the remote is assumed to hold.
235785×
        let boundary = self.boundary();
236785×
        let mut out = Vec::new();
237785×
        let mut done: BTreeSet<ChangeHash> = have.clone();
238785×
        done.extend(boundary.iter().copied());
239
        // Iterative post-order DFS.
2401226×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2413269×
        while let Some((h, expanded)) = stack.pop() {
2422484×
            if done.contains(&h) {
243400×
                continue;
2442084×
            }
2452084×
            if !self.store.has(&h) {
2460×
                return fail(format!("change {} is not in this repository", h.short(12)));
2472084×
            }
2482084×
            if expanded {
2491042×
                done.insert(h);
2501042×
                out.push(h);
2511042×
                continue;
2521042×
            }
2531042×
            stack.push((h, true));
2541042×
            for d in self.store.get_change_meta(&h)?.deps {
255736×
                if !done.contains(&d) {
256216×
                    stack.push((d, false));
257520×
                }
258
            }
259
        }
260785×
        Ok(out)
261785×
    }
262
263
    /// Bundle changes (in the given dependency order) with their signatures,
264
    /// seals, identities, blobs, chunks.
265309×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
266309×
        self.bundle_for_filtered(changes, None)
267309×
    }
268
269
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2704×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2714×
        let mut out = Vec::new();
2724×
        for r in refs {
2734×
            let (ty, body) = match self.store.get(r) {
2744×
                Ok(x) => x,
2750×
                Err(StoreError::NotFound(_)) => continue,
2760×
                Err(e) => return Err(e.into()),
277
            };
2784×
            if ty == ObjectType::Blob {
2795×
                for c in Blob::decode(&body)?.chunks {
2805×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2815×
                        out.push((cty, cb));
2825×
                    }
283
                }
2840×
            }
2854×
            out.push((ty, body));
286
        }
2874×
        Ok(out)
2884×
    }
289
290
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
291
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
292355×
    pub fn bundle_for_filtered(
293355×
        &self,
294355×
        changes: &[ChangeHash],
295355×
        max_blob: Option<u64>,
296355×
    ) -> Result<Bundle> {
297355×
        self.bundle_of(changes, max_blob, false)
298355×
    }
299
300
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
301
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
302
    /// with their text blobs and chunks among the objects, so neither side
303
    /// decodes or encodes their text.
304335×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
305335×
        self.bundle_of(changes, max_blob, true)
306335×
    }
307
308690×
    fn bundle_of(
309690×
        &self,
310690×
        changes: &[ChangeHash],
311690×
        max_blob: Option<u64>,
312690×
        raw: bool,
313690×
    ) -> Result<Bundle> {
314690×
        let mut bundle = Bundle::default();
315690×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
316690×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3171074×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3181074×
            if !r.is_zero() && self.store.has(r) {
319219×
                objects.insert(*r);
320855×
            }
3211074×
        };
322967×
        for h in changes {
323
            // Raw: the stored bytes, and a skeleton for the rest.
324967×
            let (c, encoded) = if raw {
325521×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
326521×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3275023×
                for t in texts {
3285023×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3293×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3303×
                        objects.insert(r);
3313×
                        objects.extend(blob.chunks);
3325020×
                    }
333
                }
334521×
                (skel, Some(bytes))
335
            } else {
336446×
                (self.store.get_change(h)?, None)
337
            };
338967×
            let sigs = self.store.signatures(h)?;
339967×
            add_object(&c.author, &mut objects);
340967×
            for s in &sigs {
34122×
                add_object(&s.key, &mut objects);
34222×
            }
3436062×
            for e in &c.edits {
3446062×
                if let Edit::Replace { old, new, .. } = e {
34514×
                    for b in [old, new].into_iter().flatten() {
34614×
                        if self.store.has(b) {
34714×
                            if let Ok(blob) =
34814×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
349
                            {
35014×
                                if max_blob.is_some_and(|m| blob.length > m) {
3514×
                                    continue;
35210×
                                }
35310×
                                objects.insert(*b);
35410×
                                objects.extend(blob.chunks.iter().copied());
3550×
                            }
3560×
                        }
357
                    }
3586050×
                }
359
            }
360967×
            for s in self.store.seals_for(h)? {
36190×
                seals.insert(s);
36290×
            }
363967×
            match encoded {
364521×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
365446×
                None => {
366446×
                    bundle.changes.push((c, sigs));
367446×
                    bundle.hashes.push(*h);
368446×
                }
369
            }
370
        }
371690×
        for r in seals {
37285×
            let attest = self.store.get_attest(&r)?;
37385×
            let sigs = self.store.signatures(&r)?;
37485×
            for s in &sigs {
37585×
                add_object(&s.key, &mut objects);
37685×
            }
37785×
            bundle.attests.push(SignedAttest { attest, sigs });
378
        }
379690×
        for r in objects {
380134×
            let (ty, body) = self.store.get(&r)?;
381134×
            bundle.objects.push((ty, body));
382
        }
383690×
        self.attach_certificates(&mut bundle)?;
384690×
        Ok(bundle)
385690×
    }
386
387
    /// Add the certificates of short-lived keys that signed what `bundle`
388
    /// carries, and their issuers' identities, so a receiver can tell who
389
    /// they stand for (spec §14.7). `also` names more signers (a reference
390
    /// attestation sent beside the bundle).
391775×
    pub(crate) fn attach_certificates_for(
392775×
        &self,
393775×
        bundle: &mut Bundle,
394775×
        also: &[KeyId],
395775×
    ) -> Result<()> {
396775×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
397775×
        keys.extend(
398775×
            bundle
399775×
                .changes
400775×
                .iter()
401775×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
402
        );
403775×
        keys.extend(
404775×
            bundle
405775×
                .raw_changes
406775×
                .iter()
407775×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
408
        );
409775×
        keys.extend(
410775×
            bundle
411775×
                .attests
412775×
                .iter()
413775×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
414
        );
415775×
        for k in keys {
416193×
            let Some(r) = self.store.certificate_of(&k)? else {
417172×
                continue;
418
            };
41921×
            let cert = self.store.get_certificate(&r)?;
42021×
            if bundle
42121×
                .certificates
42221×
                .iter()
42321×
                .any(|c| c.cert.hash() == cert.cert.hash())
424
            {
4257×
                continue;
42614×
            }
42728×
            for id in [&k, &cert.cert.issuer] {
42828×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
42928×
                    if !bundle
43028×
                        .objects
43128×
                        .iter()
43245×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
43314×
                    {
43414×
                        bundle.objects.push((ObjectType::Identity, body));
43514×
                    }
4360×
                }
437
            }
43814×
            bundle.certificates.push(cert);
439
        }
440775×
        Ok(())
441775×
    }
442
443690×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
444690×
        self.attach_certificates_for(bundle, &[])
445690×
    }
446
447
    /// Keep the certificates a bundle brings once each verifies with the
448
    /// identity of the issuer it names; one that does not refuses the bundle.
449735×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
450735×
        for c in certs {
45114×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4520×
                RepoError::Msg(format!(
4530×
                    "a certificate names issuer {}, whose identity did not come with it",
4540×
                    c.cert.issuer.short(12)
4550×
                ))
4560×
            })?;
45714×
            c.verify(&issuer)
45814×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
45914×
            self.store.put_identity(&c.cert.key)?;
46014×
            self.store.put_certificate(c)?;
461
        }
462735×
        Ok(())
463735×
    }
464
465
    /// A signer authorized for `reference` by what an issuer certified it
466
    /// as (spec §14.7): a short-lived key with a kept certificate that
467
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
468
    /// signer did not choose) and names a subject the policy grants.
46927×
    pub(crate) fn certified_authorized(
47027×
        &self,
47127×
        p: &crate::policy::Policy,
47227×
        signer: &KeyId,
47327×
        reference: &str,
47427×
        scope: Scope,
47527×
        at_ms: u64,
47627×
    ) -> bool {
47727×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
4785×
            return false;
479
        };
48022×
        let Ok(c) = self.store.get_certificate(&r) else {
4810×
            return false;
482
        };
48322×
        let Some(issuer) = p
48422×
            .identity(&c.cert.issuer)
48522×
            .cloned()
48622×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
487
        else {
4880×
            return false;
489
        };
49022×
        c.verify(&issuer).is_ok()
49122×
            && c.cert.key_id() == *signer
49222×
            && c.cert.covers(scope, at_ms)
49318×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
49427×
    }
495
496
    /// Store a bundle's contents. With `strict`, every change must
497
    /// authenticate (signature or seal by its author or a delegate).
498732×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
499732×
        self.import_bundle_inner(bundle, strict, false)
500732×
    }
501
502
    /// Like `import_bundle`, accepting changes whose dependencies are absent
503
    /// (they join the shallow boundary).
5043×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5053×
        self.import_bundle_inner(bundle, strict, true)
5063×
    }
507
508735×
    fn import_bundle_inner(
509735×
        &self,
510735×
        bundle: &Bundle,
511735×
        strict: bool,
512735×
        shallow: bool,
513735×
    ) -> Result<Vec<ChangeHash>> {
514735×
        let batch = self.store.begin_batch()?;
515735×
        let result = self.import_bundle_batched(bundle, strict, shallow);
516735×
        batch.finish()?;
517733×
        result
518735×
    }
519
520735×
    fn import_bundle_batched(
521735×
        &self,
522735×
        bundle: &Bundle,
523735×
        strict: bool,
524735×
        shallow: bool,
525735×
    ) -> Result<Vec<ChangeHash>> {
526735×
        for (ty, _) in &bundle.objects {
5270×
            if !matches!(
528531×
                ty,
529
                ObjectType::Chunk
530
                    | ObjectType::Blob
531
                    | ObjectType::Identity
532
                    | ObjectType::State
533
                    | ObjectType::Checkpoint
534
            ) {
5350×
                return fail(format!("bundle may not carry {} objects", ty.name()));
536531×
            }
537
        }
538
        // All at once: in a large batch they are compressed on every core.
539735×
        let objects: Vec<(ObjectType, &[u8])> = bundle
540735×
            .objects
541735×
            .iter()
542735×
            .map(|(ty, body)| (*ty, body.as_slice()))
543735×
            .collect();
544735×
        self.store.put_many(&objects)?;
545735×
        self.adopt_certificates(&bundle.certificates)?;
546735×
        for sa in &bundle.attests {
54788×
            let r = self.store.put_attest(&sa.attest)?;
54888×
            for sig in &sa.sigs {
54988×
                self.store.put_signature(&r, sig)?;
550
            }
55188×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
55293×
                for h in hashes {
55393×
                    self.store.index_seal(h, &r)?;
554
                }
5550×
            }
556
        }
557
        // Each change's hash: from the bundle when its maker knew it, else
558
        // worked out once (for a change adding a whole tree, hashing is
559
        // chunking all its text).
560735×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
561726×
            bundle.hashes.clone()
562
        } else {
5639×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
564
        };
565735×
        let raw_hashes: Vec<ChangeHash> = bundle
566735×
            .raw_changes
567735×
            .iter()
568735×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
569735×
            .collect();
570735×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
571735×
        let boundary = self.boundary();
572735×
        let mut imported = Vec::new();
573
        // Changes as stored: checked, then stored as they are, their text
574
        // blobs having come with the objects.
575735×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
576522×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
577522×
            for d in &skel.deps {
578400×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
579
                {
5800×
                    return fail(format!(
581
                        "change {} depends on {}, which is neither stored nor in the bundle",
5820×
                        h.short(12),
5830×
                        d.short(12)
584
                    ));
585400×
                }
586
            }
5875024×
            for t in texts {
5885024×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
5894×
                    if !self.store.has(&r) {
5901×
                        return fail(format!(
591
                            "change {} came without its text blob {}",
5921×
                            h.short(12),
5931×
                            r.short(12)
594
                        ));
5953×
                    }
5965020×
                }
597
            }
598521×
            self.store.put(ObjectType::Change, bytes)?;
599521×
            for sig in sigs {
6004×
                self.store.put_signature(&h, sig)?;
601
            }
602521×
            imported.push(h);
603
        }
604734×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
605474×
            for d in &c.deps {
606290×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
607
                {
6083×
                    return fail(format!(
609
                        "change {} depends on {}, which is neither stored nor in the bundle",
6103×
                        h.short(12),
6113×
                        d.short(12)
612
                    ));
613287×
                }
614
            }
615471×
            let stored = self.store.put_change(c)?;
616471×
            if stored != h {
6170×
                return fail(format!(
618
                    "change {} is not the change the bundle names",
6190×
                    h.short(12)
620
                ));
621471×
            }
622471×
            for sig in sigs {
62327×
                self.store.put_signature(&h, sig)?;
624
            }
625471×
            imported.push(h);
626
        }
627731×
        if strict {
62843×
            for h in &imported {
62930×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6304×
                    return fail(format!(
631
                        "change {} is not authenticated by its author",
6324×
                        h.short(12)
633
                    ));
63426×
                }
635
            }
636688×
        }
637727×
        Ok(imported)
638735×
    }
639
640
    /// Verify a reference attestation against an update it claims to describe.
641
    /// `allow_equal` lets a client re-read the attestation it already has; a
642
    /// server receiving a push requires a strictly greater serial.
643
    /// A reference attestation signed by a delegate of an identity the
644
    /// rule lists is authorized as that identity (spec §14.5): the identity
645
    /// named the delegate with the `refs` scope, still in force at `at_ms`
646
    /// (the attestation's wall time), and the policy names the identity.
647
    /// Revoked keys authorize nothing either way.
64831×
    pub(crate) fn delegate_authorized(
64931×
        &self,
65031×
        p: &crate::policy::Policy,
65131×
        signer: &KeyId,
65231×
        reference: &str,
65331×
        at_ms: u64,
65431×
    ) -> bool {
65531×
        if p.is_revoked(signer) {
6561×
            return false;
65730×
        }
65830×
        let Some(rule) = p.rule_for(reference) else {
6590×
            return false;
660
        };
66131×
        rule.keys.iter().any(|k| {
66231×
            !p.is_revoked(k)
66331×
                && p.identity(k)
66431×
                    .cloned()
66531×
                    .or_else(|| self.store.get_identity(k).ok())
66631×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
66731×
        })
66831×
    }
669
670
    /// A lasting attestation (a tag) signed by a key the policy has since
671
    /// rotated away from (spec §14.2) is authorized as the key that
672
    /// succeeded it: a key the rule lists reaches the signer through
673
    /// `previous` links, and the attestation is dated (`at_ms`) before the
674
    /// signer's successor was made, so a superseded key makes nothing new.
675
    /// Revoked keys authorize nothing.
6766×
    pub(crate) fn predecessor_authorized(
6776×
        &self,
6786×
        p: &crate::policy::Policy,
6796×
        signer: &KeyId,
6806×
        reference: &str,
6816×
        at_ms: u64,
6826×
    ) -> bool {
6836×
        if p.is_revoked(signer) {
6840×
            return false;
6856×
        }
6866×
        let Some(rule) = p.rule_for(reference) else {
6870×
            return false;
688
        };
6897×
        let identity = |k: &KeyId| {
6907×
            p.identity(k)
6917×
                .cloned()
6927×
                .or_else(|| self.store.get_identity(k).ok())
6937×
        };
6946×
        rule.keys.iter().any(|k| {
6956×
            if p.is_revoked(k) {
6960×
                return false;
6976×
            }
6986×
            let mut cur = identity(k);
6996×
            for _ in 0..32 {
7007×
                let Some(id) = cur else {
7010×
                    return false;
702
                };
7031×
                match id.previous {
7046×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7051×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
7061×
                    _ => return false,
707
                }
708
            }
7090×
            false
7106×
        })
7116×
    }
712
713114×
    fn check_ref_attest(
714114×
        &self,
715114×
        sa: &SignedAttest,
716114×
        name: &str,
717114×
        old_state: &ObjectRef,
718114×
        new_state: &ObjectRef,
719114×
        last_serial: Option<u64>,
720114×
        allow_equal: bool,
721114×
    ) -> std::result::Result<u64, String> {
722
        let AttestBody::Ref {
723114×
            name: n,
724114×
            old_state: o,
725114×
            new_state: nw,
726114×
            serial,
727114×
        } = &sa.attest.body
728
        else {
7290×
            return Err("attestation is not a ref attestation".into());
730
        };
731114×
        if n != name || o != old_state || nw != new_state {
7321×
            return Err("attestation does not describe this update".into());
733113×
        }
734113×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7350×
            return Err("attestation is for a different repository".into());
736113×
        }
737113×
        if let Some(last) = last_serial {
73868×
            if *serial < last || (*serial == last && !allow_equal) {
7391×
                return Err(format!(
7401×
                    "attestation serial {serial} is not greater than the last seen {last}"
7411×
                ));
74267×
            }
74345×
        }
744112×
        let r = sa.attest.hash();
745112×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
746112×
        let id = self
747112×
            .store
748112×
            .get_identity(&sig.key)
749112×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
750112×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
751112×
        Ok(*serial)
752114×
    }
753
754
    /// Accept a push (spec §16.4). Without a trust policy every repository
755
    /// is unverified, so unsigned changes and unattested updates are accepted;
756
    /// attestations that are present must still be valid. With a policy,
757
    /// every change and update is checked against it. A newer policy in the
758
    /// push is applied first when it is signed by the current roots.
759287×
    pub fn receive_push(
760287×
        &self,
761287×
        bundle: Bundle,
762287×
        updates: Vec<RefUpdate>,
763287×
        policy: Option<SignedPolicy>,
764287×
        tags: Vec<crate::protocol::TagRef>,
765287×
    ) -> Result<Vec<RefResult>> {
766287×
        Ok(self
767287×
            .receive_push_report(bundle, updates, policy, tags)?
768
            .results)
769287×
    }
770
771
    /// `receive_push` with what a host wants to log: each accepted
772
    /// reference's old and new state and heads, and the changes this push
773
    /// stored (hub spec §6.12).
774327×
    pub fn receive_push_report(
775327×
        &self,
776327×
        bundle: Bundle,
777327×
        updates: Vec<RefUpdate>,
778327×
        policy: Option<SignedPolicy>,
779327×
        tags: Vec<crate::protocol::TagRef>,
780327×
    ) -> Result<PushReport> {
781
        // Updates are checked against the head as it is now, not as this
782
        // handle first read it (oxygenhub#249): another push may have
783
        // landed since.
784327×
        self.refresh()?;
785327×
        let mut report = PushReport::default();
786327×
        let results = &mut report.results;
787327×
        if let Some(sp) = policy {
78825×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
78923×
                Ok(()) => {
79023×
                    results.push(RefResult {
79123×
                        name: "policy".into(),
79223×
                        ok: true,
79323×
                        reason: format!("serial {}", sp.policy.serial),
79423×
                    });
79523×
                }
7962×
                Err(e) => {
7972×
                    results.push(RefResult {
7982×
                        name: "policy".into(),
7992×
                        ok: false,
8002×
                        reason: e,
8012×
                    });
8022×
                    for u in updates {
8030×
                        results.push(RefResult {
8040×
                            name: u.name,
8050×
                            ok: false,
8060×
                            reason: "policy update was rejected".into(),
8070×
                        });
8080×
                    }
8092×
                    return Ok(report);
810
                }
811
            }
812302×
        }
813325×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
814
        // A push of objects alone (one batch of a long history, oxygen#95)
815
        // names no reference: its outcome is reported as `objects`.
816325×
        let objects_only = updates.is_empty() && tags.is_empty();
817325×
        match self.import_bundle(&bundle, policy.is_some()) {
818319×
            Ok(imported) => {
819319×
                if objects_only {
8207×
                    results.push(RefResult {
8217×
                        name: OBJECTS_RESULT.into(),
8227×
                        ok: true,
8237×
                        reason: format!("{} changes stored", imported.len()),
8247×
                    });
825312×
                }
826319×
                report.imported = imported;
827
            }
8286×
            Err(e) => {
8296×
                if objects_only {
8300×
                    results.push(RefResult {
8310×
                        name: OBJECTS_RESULT.into(),
8320×
                        ok: false,
8330×
                        reason: e.to_string(),
8340×
                    });
8356×
                }
8366×
                for u in updates {
8376×
                    results.push(RefResult {
8386×
                        name: u.name,
8396×
                        ok: false,
8406×
                        reason: e.to_string(),
8416×
                    });
8426×
                }
8436×
                return Ok(report);
844
            }
845
        }
846319×
        let (op_ref, op) = self.head_op()?;
847319×
        let mut view = op.view.clone();
848319×
        let mut names = Vec::new();
849319×
        for u in updates {
850310×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
851310×
            let (ok, reason) = match outcome {
852284×
                Ok(()) => (true, String::new()),
85326×
                Err(e) => (false, e),
854
            };
855310×
            if ok {
856284×
                names.push(u.name.clone());
857284×
                let heads = self
858284×
                    .store
859284×
                    .get_state(&u.new_state)
860284×
                    .map(|s| s.heads)
861284×
                    .unwrap_or_default();
862284×
                report.updated.push(RefUpdated {
863284×
                    name: u.name.clone(),
864284×
                    old_state: u.old_state,
865284×
                    new_state: u.new_state,
866284×
                    heads,
867284×
                });
86826×
            }
869310×
            results.push(RefResult {
870310×
                name: u.name,
871310×
                ok,
872310×
                reason,
873310×
            });
874
        }
875319×
        for t in &tags {
8768×
            let name = format!("tags/{}", t.name);
8778×
            let new = !view.tags.contains_key(&t.name);
8788×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
879
                Ok(()) => {
880
                    // A tag new here is an update too, so a hub can start
881
                    // its pipeline's tag jobs (oxygenflow#24); one it
882
                    // already had, sent again, is not.
8836×
                    if new {
8846×
                        report.updated.push(RefUpdated {
8856×
                            name: name.clone(),
8866×
                            old_state: ObjectRef::ZERO,
8876×
                            new_state: t.state,
8886×
                            heads: t.heads.clone(),
8896×
                        });
8906×
                    }
8916×
                    names.push(name.clone());
8926×
                    results.push(RefResult {
8936×
                        name,
8946×
                        ok: true,
8956×
                        reason: String::new(),
8966×
                    });
897
                }
8982×
                Err(e) => results.push(RefResult {
8992×
                    name,
9002×
                    ok: false,
9012×
                    reason: e,
9022×
                }),
903
            }
904
        }
905319×
        if !names.is_empty() {
906284×
            self.record_op(
907284×
                &[op_ref],
908284×
                &format!("push received: {}", names.join(" ")),
909284×
                view,
9103×
            )?;
91135×
        }
912316×
        Ok(report)
913327×
    }
914
915
    /// Check an update's attestation against the latest one for its
916
    /// reference and store it as the new latest. Failures say what was
917
    /// being done, for which reference, so a refused push can be diagnosed
918
    /// from its reason alone.
91984×
    fn record_update_attest(
92084×
        &self,
92184×
        u: &RefUpdate,
92284×
        sa: &SignedAttest,
92384×
    ) -> std::result::Result<(), String> {
92484×
        let name = &u.name;
92584×
        let last = self
92684×
            .latest_ref_attest(name)
92784×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
92884×
            .and_then(|(_, a)| match a.attest.body {
92955×
                AttestBody::Ref { serial, .. } => Some(serial),
9300×
                _ => None,
93155×
            });
93284×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
93382×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
93482×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
93581×
        for sig in &sa.sigs {
93681×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
937
        }
93881×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
939
        // Signed by a short-lived key: a host records when it accepted it.
94078×
        let certified = sa
94178×
            .sigs
94278×
            .first()
94378×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
94478×
        if certified {
9452×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
94676×
        }
94778×
        Ok(())
94884×
    }
949
950
    /// Record that this host accepted attestation `r` now, signed with its
951
    /// acceptor key (spec §14.7); nothing without one.
9523×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
9533×
        let Some(acceptor) = &self.acceptor else {
9542×
            return Ok(());
955
        };
9561×
        let (id, sk) = (&acceptor.0, &acceptor.1);
9571×
        let attest = Attest {
9581×
            repo: self.id()?,
9591×
            hlc: Hlc::now(),
9601×
            body: AttestBody::Accepted { attest: *r },
961
        };
9621×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
9631×
        self.store.put_identity(id)?;
9641×
        let a = self.store.put_attest(&attest)?;
9651×
        self.store.put_signature(&a, &sig)?;
9661×
        self.store.index_add_pub("accepted", r, &a)?;
9671×
        Ok(())
9683×
    }
969
970
    /// The host's acceptance of attestation `r`, if one was recorded.
971127×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
972127×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
973117×
            return Ok(None);
974
        };
975
        Ok(Some(SignedAttest {
97610×
            attest: self.store.get_attest(&a)?,
97710×
            sigs: self.store.signatures(&a)?,
978
        }))
979127×
    }
980
981
    /// When a certified signer's attestation `sa` is checked on a fetch: the
982
    /// host's acceptance time, if `accepted` is signed by the issuer of the
983
    /// signer's certificate and accepts `sa`; else the attestation's own
984
    /// time, which the signer chose.
98519×
    pub(crate) fn certified_time(
98619×
        &self,
98719×
        signer: &KeyId,
98819×
        sa: &SignedAttest,
98919×
        accepted: Option<&SignedAttest>,
99019×
    ) -> u64 {
99119×
        let own = sa.attest.hlc.wall_ms;
99219×
        let Some(acc) = accepted else {
99313×
            return own;
994
        };
9956×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
9960×
            return own;
997
        };
9986×
        let Ok(cert) = self.store.get_certificate(&c) else {
9990×
            return own;
1000
        };
10016×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
10020×
            return own;
1003
        };
10046×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
10051×
            return own;
1006
        };
10075×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
10080×
            return own;
1009
        };
10105×
        if *attest == sa.attest.hash()
10114×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1012
        {
10134×
            acc.attest.hlc.wall_ms
1014
        } else {
10151×
            own
1016
        }
101719×
    }
1018
1019
    /// A fetched bookmark's attestation by a signer the policy does not
1020
    /// list itself: a delegate or a short-lived key, whose authority
1021
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1022
    /// attestation's integrated time when the host's log gives one; else
1023
    /// as before, at the host's acceptance for a certified signer, when it
1024
    /// countersigned one, or at the attestation's own time, and said so
1025
    /// when the host keeps a log. Failing at the integrated time but not
1026
    /// as before is a note while logs are new; a large gap between the
1027
    /// claimed and the integrated time is a note.
1028
    #[allow(clippy::too_many_arguments)]
102915×
    pub(crate) fn authorize_in_time(
103015×
        &self,
103115×
        p: &crate::policy::Policy,
103215×
        remote_name: &str,
103315×
        r: &crate::protocol::RemoteRef,
103415×
        sa: &SignedAttest,
103515×
        signer: &KeyId,
103615×
        log: &super::transparency::LogCheck,
103715×
        notes: &mut Vec<String>,
103815×
    ) -> Result<()> {
1039
        use super::transparency::{gap_note, judge, Timed};
104015×
        let own = sa.attest.hlc.wall_ms;
104115×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
104215×
        let time = log.time_of(&r.name);
104317×
        let check = |t_delegate: u64, t_cert: u64| {
104417×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
104517×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
104617×
        };
104715×
        let before = if at != own {
10483×
            "the host's acceptance"
1049
        } else {
105012×
            "the time it claims"
1051
        };
105215×
        let what = format!("{remote_name}/{}", r.name);
105315×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1054
            Timed::Refused => {
10551×
                return fail(format!(
1056
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
10571×
                    signer.short(12)
1058
                ))
1059
            }
10603×
            Timed::Integrated => {}
10611×
            Timed::Disagrees => notes.push(format!(
1062
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
10631×
                signer.short(12),
10641×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1065
            )),
10661×
            Timed::Fallback if log.kept => notes.push(format!(
1067
                "{what}: {} checked at {before}, not at a witnessed time: {}",
10681×
                signer.short(12),
10691×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1070
            )),
10719×
            Timed::Fallback => {}
1072
        }
107314×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
10742×
            notes.push(format!("{what}'s attestation {n}"));
107512×
        }
107614×
        Ok(())
107715×
    }
1078
1079
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1080
    /// at `old_state`, is never the bookmark a non-bare repository has
1081
    /// checked out (a bare one's default is its host's to protect, see
1082
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1083
    /// an attestation by a key that may update it.
1084
    /// The deletion's attestation stays the bookmark's latest, so an older
1085
    /// one cannot be replayed to bring it back.
10863×
    fn apply_deletion(
10873×
        &self,
10883×
        view: &mut View,
10893×
        u: &RefUpdate,
10903×
        policy: Option<&crate::policy::Policy>,
10913×
    ) -> std::result::Result<(), String> {
10923×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
10930×
            return Err(format!("no bookmark {:?} to delete", u.name));
1094
        };
10953×
        if current != u.old_state {
10960×
            return Err("stale: the remote bookmark has moved; pull first".into());
10973×
        }
10983×
        if !self.is_bare() && u.name == self.config.bookmark {
10991×
            return Err(format!(
11001×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
11011×
                u.name
11021×
            ));
11032×
        }
11042×
        if let Some(p) = policy {
11050×
            let Some(sa) = &u.attestation else {
11060×
                return Err(format!(
11070×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
11080×
                    u.name
11090×
                ));
1110
            };
11110×
            let signer = sa
11120×
                .sigs
11130×
                .first()
11140×
                .map(|s| s.key)
11150×
                .ok_or("attestation carries no signature")?;
1116
            // Received now: the receiver's own clock is the trusted time.
11170×
            let now = Hlc::now().wall_ms;
11180×
            if !p.authorizes(&signer, &u.name)
11190×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11200×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1121
            {
11220×
                return Err(format!(
11230×
                    "key {} may not delete {:?} under this repository's policy",
11240×
                    signer.short(12),
11250×
                    u.name
11260×
                ));
11270×
            }
11282×
        }
11292×
        if let Some(sa) = &u.attestation {
11301×
            self.record_update_attest(u, sa)?;
11311×
        }
11322×
        view.bookmarks.remove(&u.name);
11332×
        Ok(())
11343×
    }
1135
1136310×
    fn apply_update(
1137310×
        &self,
1138310×
        view: &mut View,
1139310×
        u: &RefUpdate,
1140310×
        policy: Option<&crate::policy::Policy>,
1141310×
    ) -> std::result::Result<(), String> {
1142310×
        if u.name == "policy" {
11430×
            return Err(
11440×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
11450×
            );
1146310×
        }
1147310×
        let empty = self
1148310×
            .store
1149310×
            .put_state(&StateObject::new(vec![]))
1150310×
            .map_err(|e| e.to_string())?;
1151310×
        if u.new_state.is_zero() {
11523×
            return self.apply_deletion(view, u, policy);
1153307×
        }
1154307×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1155307×
        if current != u.old_state {
11569×
            return Err("stale: the remote bookmark has moved; pull first".into());
1157298×
        }
1158298×
        let new_state = self
1159298×
            .store
1160298×
            .get_state(&u.new_state)
1161298×
            .map_err(|_| "new state object is missing".to_string())?;
1162557×
        for h in &new_state.heads {
1163557×
            if !self.store.has(h) {
11641×
                return Err(format!("head {} is missing", h.short(12)));
1165556×
            }
1166
        }
1167297×
        if !u.force {
1168296×
            let old_heads = self
1169296×
                .store
1170296×
                .get_state(&current)
1171296×
                .map_err(|e| e.to_string())?
1172
                .heads;
1173296×
            let closure = self
1174296×
                .closure_in_store(&new_state.heads)
1175296×
                .map_err(|e| e.to_string())?;
1176296×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
11771×
                return Err(format!(
11781×
                    "not a fast-forward: current head {} would be dropped (use --force)",
11791×
                    h.short(12)
11801×
                ));
1181295×
            }
11821×
        }
1183296×
        if let Some(p) = policy {
118438×
            let Some(sa) = &u.attestation else {
11851×
                return Err(format!(
11861×
                    "{:?} requires a signed reference attestation under this repository's policy",
11871×
                    u.name
11881×
                ));
1189
            };
119037×
            let signer = sa
119137×
                .sigs
119237×
                .first()
119337×
                .map(|s| s.key)
119437×
                .ok_or("attestation carries no signature")?;
1195
            // Received now: the receiver's own clock is the trusted time.
119637×
            let now = Hlc::now().wall_ms;
119737×
            if !p.authorizes(&signer, &u.name)
119811×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11999×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1200
            {
12017×
                return Err(format!(
12027×
                    "key {} may not update {:?} under this repository's policy",
12037×
                    signer.short(12),
12047×
                    u.name
12057×
                ));
120630×
            }
120730×
            let old_heads = self
120830×
                .store
120930×
                .get_state(&current)
121030×
                .map_err(|e| e.to_string())?
1211
                .heads;
121230×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1213258×
        }
1214288×
        if let Some(sa) = &u.attestation {
121583×
            self.record_update_attest(u, sa)?;
1216205×
        }
1217282×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1218282×
        Ok(())
1219310×
    }
1220
1221
    // ------------------------------------------------------------ client side
1222
12231384×
    fn remote_url(&self, name: &str) -> Result<String> {
12241384×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
12253×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
12263×
            RepoError::Msg(match names.as_slice() {
12273×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
12281×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1229
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
12301×
                    names.join(", "),
12311×
                    names[0],
12321×
                    names[0]
1233
                ),
12340×
                _ => format!(
1235
                    "no remote named {name:?}; this repository has {}",
12360×
                    names.join(", ")
1237
                ),
1238
            })
12393×
        })
12401384×
    }
1241
1242
    /// Refuse a remote that is another repository. An **unbound** remote
1243
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1244
    /// for pushes, which bind it to this repository's id (spec §16.1).
1245753×
    fn check_remote_id(
1246753×
        &self,
1247753×
        remote: &dyn crate::protocol::Remote,
1248753×
        remote_name: &str,
1249753×
        allow_unbound: bool,
1250753×
    ) -> Result<()> {
1251753×
        let theirs = remote.repo_id()?;
1252752×
        if theirs == self.id()? {
1253729×
            return Ok(());
125423×
        }
125523×
        if theirs == crate::protocol::UNBOUND_ID {
125620×
            if allow_unbound {
125719×
                return Ok(());
12581×
            }
12591×
            return fail(format!(
1260
                "remote {remote_name:?} is empty and unbound: push to it first"
1261
            ));
12623×
        }
12633×
        fail(format!(
1264
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1265
        ))
1266753×
    }
1267
1268
    /// Credentials and trust for a remote: `remote.<name>.token` and
1269
    /// `remote.<name>.ca`, else the defaults for its URL
1270
    /// ([`Repo::fill_credentials`]).
12711032×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
12721032×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
12731032×
        let mut options = RemoteOptions {
12741032×
            repo_id: self.id().ok(),
12751032×
            token: self.config.remote_tokens.get(name).cloned(),
12761032×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
12771032×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
12781032×
            ..RemoteOptions::default()
12791032×
        };
12801032×
        self.fill_credentials(&url, &mut options);
12811032×
        options
12821032×
    }
1283
1284
    /// The user's credential store (`credentials.toml` beside the user
1285
    /// configuration file).
12861053×
    pub fn credentials(&self) -> crate::credentials::Credentials {
12871053×
        crate::credentials::Credentials::at(
12881053×
            self.user_config
12891053×
                .parent()
12901053×
                .map(Path::to_path_buf)
12911053×
                .unwrap_or_else(default_home),
1292
        )
12931053×
    }
1294
1295
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1296
    /// then the user's credential store for its hub, then a remote on the
1297
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1298
    /// When the token is not this remote's own or the environment's, the
1299
    /// other tokens enclosing checkouts hold for the hub are kept to try
1300
    /// if it is refused: a stale stored login must not hide a parent's
1301
    /// good token (oxygen#112).
13021054×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
13031054×
        if options.token.is_some() && options.ca.is_some() {
13041×
            return;
13051053×
        }
13061053×
        let explicit =
13071053×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
13081053×
        let stored = self.credentials().options_for(url);
13091053×
        options.token = options.token.take().or(stored.token);
13101053×
        options.ca = options.ca.take().or(stored.ca);
13111053×
        let enclosing = self.enclosing_credentials(url);
13121053×
        if options.token.is_none() {
13131043×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
131410×
        }
13151053×
        if options.ca.is_none() {
1316988×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
131765×
        }
13181053×
        if !explicit {
13191046×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
13205×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
13212×
                    options.fallback_tokens.push(t);
13223×
                }
1323
            }
13247×
        }
13251054×
    }
1326
1327
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1328
    /// checkouts, nearest first.
13291053×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
13301053×
        let mut out = Vec::new();
13311053×
        let Some(hub) = crate::credentials::hub_of(url) else {
1332919×
            return out;
1333
        };
1334134×
        let mut at = self.root.parent();
1335544×
        while let Some(dir) = at {
1336410×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
13370×
                break;
1338
            };
1339410×
            for (key, remote_url) in &cfg {
134015×
                let Some(name) = key
134115×
                    .strip_prefix("remote.")
134215×
                    .and_then(|k| k.strip_suffix(".url"))
1343
                else {
13447×
                    continue;
1345
                };
13468×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
13471×
                    continue;
13487×
                }
13497×
                out.push((
13507×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
13517×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
13527×
                ));
1353
            }
1354410×
            at = dir.parent();
1355
        }
1356134×
        out
13571053×
    }
1358
1359
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1360
    /// no changes and no reference updates, which the receiver stores.
13610×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
13620×
        let remote = self.open_named_remote(remote_name)?;
13630×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13640×
        let mut bundle = Bundle::default();
13650×
        for r in seals {
13660×
            let attest = self.store.get_attest(r)?;
13670×
            let sigs = self.store.signatures(r)?;
13680×
            bundle
13690×
                .attests
13700×
                .push(crate::protocol::SignedAttest { attest, sigs });
1371
        }
13720×
        let results = remote.push(bundle, vec![], None, vec![])?;
13730×
        if let Some(r) = results.iter().find(|r| !r.ok) {
13740×
            return fail(format!("{}: {}", r.name, r.reason));
13750×
        }
13760×
        Ok(())
13770×
    }
1378
1379
    /// The remote whose URL starts with `base` (a hub), if configured.
13804×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
13814×
        let base = base.trim_end_matches('/');
13824×
        self.config
13834×
            .remotes
13844×
            .iter()
13854×
            .find(|(_, url)| url.trim_end_matches('/') == base)
13864×
            .map(|(name, _)| name.clone())
13874×
    }
1388
1389
    /// Open a remote by name or, failing that, by URL with the default
1390
    /// credentials (see [`Repo::credentials_for`]).
13910×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
13920×
        if let Some(name) = self.remote_for_url(url) {
13930×
            return Ok((name.clone(), self.open_named_remote(&name)?));
13940×
        }
13950×
        let options = RemoteOptions {
13960×
            repo_id: self.id().ok(),
13970×
            ..self.credentials_for(url)
13980×
        };
13990×
        Ok((url.to_string(), open_remote(url, &options)?))
14000×
    }
1401
1402
    /// Credentials for a URL: those of the configured remote with that
1403
    /// URL, else the environment's.
14044×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
14054×
        match self.remote_for_url(url) {
14064×
            Some(name) => self.remote_options(&name),
14070×
            None => RemoteOptions {
14080×
                repo_id: self.id().ok(),
14090×
                ..self.credentials_for(url)
14100×
            },
1411
        }
14124×
    }
1413
14141015×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
14151015×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
14161015×
    }
1417
1418124×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1419124×
        self.oxy
1420124×
            .join("remotes")
1421124×
            .join(remote)
1422124×
            .join(format!("{bookmark}.serial"))
1423124×
    }
1424
142530×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
142630×
        fs::read_to_string(self.serial_path(remote, bookmark))
142730×
            .ok()
142830×
            .and_then(|s| s.trim().parse().ok())
142930×
    }
1430
143194×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
143294×
        let p = self.serial_path(remote, bookmark);
143394×
        fs::create_dir_all(p.parent().unwrap())?;
143494×
        write_atomic(&p, serial.to_string().as_bytes())
143594×
    }
1436
1437411×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1438411×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1439411×
    }
1440
1441
    /// The highest policy serial `remote` has ever presented.
1442369×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1443369×
        fs::read_to_string(self.policy_serial_path(remote))
1444369×
            .ok()
1445369×
            .and_then(|s| s.trim().parse().ok())
1446369×
    }
1447
144842×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
144942×
        let p = self.policy_serial_path(remote);
145042×
        fs::create_dir_all(p.parent().unwrap())?;
145142×
        write_atomic(&p, serial.to_string().as_bytes())
145242×
    }
1453
145427×
    fn lazy_dir(&self) -> PathBuf {
145527×
        self.oxy.join("lazy")
145627×
    }
1457
1458
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
14594×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
14604×
        fs::create_dir_all(self.lazy_dir())?;
14614×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
14624×
    }
1463
1464
    /// Which remote promised an absent blob, if any.
146515×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
146615×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
146715×
            .ok()
146815×
            .map(|s| s.trim().to_string())
146915×
    }
1470
1471
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
14724×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
14734×
        let Some(remote_name) = self.lazy_remote(blob) else {
14740×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1475
        };
14764×
        let remote = self.open_named_remote(&remote_name)?;
14774×
        let objects = remote.objects(&[*blob])?;
14789×
        for (ty, body) in objects {
14799×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
14809×
                self.store.put(ty, &body)?;
14810×
            }
1482
        }
14834×
        if !self.store.has(blob) {
14840×
            return fail(format!(
1485
                "{remote_name} did not send blob {}",
14860×
                blob.short(12)
1487
            ));
14884×
        }
14894×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
14904×
        Ok(())
14914×
    }
1492
1493
    /// After importing from `remote`, record every blob the changes reference
1494
    /// that the store lacks as lazily available from that remote.
14954×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
14964×
        let mut n = 0;
14974×
        for h in changes {
14984×
            let c = self.store.get_change(h)?;
149913×
            for e in &c.edits {
150013×
                if let Edit::Replace { old, new, .. } = e {
15016×
                    for b in [old, new].into_iter().flatten() {
15026×
                        if !self.store.has(b) {
15034×
                            self.register_lazy(b, remote)?;
15044×
                            n += 1;
15052×
                        }
1506
                    }
15077×
                }
1508
            }
1509
        }
15104×
        Ok(n)
15114×
    }
1512
1513
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1514369×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1515369×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1516495×
        for st in view
1517369×
            .bookmarks
1518369×
            .values()
1519369×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1520
        {
1521495×
            if let Ok(s) = self.store.get_state(st) {
1522495×
                have.extend(s.heads);
1523495×
            }
1524
        }
1525369×
        have.extend(view.workspaces.values().copied());
1526369×
        Ok(have.into_iter().collect())
1527369×
    }
1528
1529
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1530375×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1531375×
        let remote = self.open_named_remote(remote_name)?;
1532372×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1533370×
        let resp = remote.refs()?;
1534
        // The host's transparency log (spec §14.8): a fork fails here.
1535369×
        let log = self.check_log(
1536369×
            &self.remote_url(remote_name)?,
1537369×
            self.config.remote_cas.get(remote_name).map(Path::new),
1538369×
            &resp,
15390×
        )?;
1540369×
        let mut log_notes = log.notes.clone();
1541
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1542
        // and signed by roots we trust, or on first contact. A remote that
1543
        // once presented a policy may never present none or an older one:
1544
        // that is a downgrade. A remote that never presented one is
1545
        // unverified, and this fetch is checked only as far as possible.
1546369×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1547369×
        let seen = self.remote_policy_serial(remote_name);
1548369×
        let mut unverified = false;
1549369×
        match &resp.policy {
155019×
            Some(sp) => {
155119×
                if seen.is_some_and(|s| sp.policy.serial < s) {
15520×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
155319×
                }
15548×
                match &local_policy {
15558×
                    Some(l) if sp.policy.serial < l.serial => {}
15568×
                    Some(l) if sp.policy.serial == l.serial => {
15574×
                        if sp.policy.hash() != l.hash() {
15580×
                            return fail(format!(
1559
                                "{remote_name} presents a different policy with the same serial {}",
1560
                                l.serial
1561
                            ));
15624×
                        }
1563
                    }
1564
                    _ => {
156515×
                        self.adopt_policy_chain(
156615×
                            &resp.history,
156715×
                            sp,
156815×
                            &format!("oxy fetch {remote_name}"),
1569
                        )
157015×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1571
                    }
1572
                }
157319×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1574
            }
1575
            None => {
1576350×
                if seen.is_some() {
15770×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1578350×
                }
1579350×
                unverified = true;
1580
            }
1581
        }
1582369×
        let policy = if unverified {
1583350×
            None
1584
        } else {
158519×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1586
        };
1587369×
        let (op_ref, op) = self.head_op()?;
1588369×
        let mut view = op.view.clone();
1589369×
        let have = self.known_heads(&view)?;
1590369×
        let mut report = Vec::new();
1591369×
        let max_blob = self.config.max_blob;
1592377×
        for r in resp.refs {
1593377×
            let needed = {
1594377×
                let _t = crate::timing::phase("fetch: negotiate");
1595377×
                remote.negotiate(&have, &r.heads)?
1596
            };
1597377×
            let bundle = {
1598377×
                let _t = crate::timing::phase("fetch: bundle");
1599377×
                remote.fetch(&needed, max_blob)?
1600
            };
1601
            // Changes are not individually re-verified here: the bookmark's
1602
            // attestation (checked below) binds its whole state, and the
1603
            // receiver of the push verified the added changes at that time.
1604377×
            let imported = {
1605377×
                let _t = crate::timing::phase("fetch: import");
1606377×
                self.import_bundle(&bundle, false)?
1607
            };
1608377×
            if max_blob.is_some() {
16094×
                self.register_missing_blobs(&imported, remote_name)?;
1610373×
            }
1611509×
            for h in &r.heads {
1612509×
                if !self.store.has(h) {
16130×
                    return fail(format!("remote did not send head {}", h.short(12)));
1614509×
                }
1615
            }
1616377×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1617377×
            if state != r.state {
16180×
                return fail(format!(
1619
                    "remote state {} does not match its heads",
16200×
                    r.state.short(12)
1621
                ));
1622377×
            }
1623377×
            if let Some(p) = &policy {
162419×
                let Some(sa) = &r.attestation else {
16250×
                    return fail(format!(
1626
                        "{remote_name}/{} has no attestation, which its policy requires",
1627
                        r.name
1628
                    ));
1629
                };
163019×
                let signer = sa
163119×
                    .sigs
163219×
                    .first()
163319×
                    .map(|s| s.key)
163419×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
163519×
                if !p.authorizes(&signer, &r.name) {
16368×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
163711×
                }
1638358×
            }
1639377×
            if let Some(sa) = &r.attestation {
1640
                let AttestBody::Ref {
164130×
                    old_state,
164230×
                    new_state,
1643
                    ..
164430×
                } = &sa.attest.body
1645
                else {
16460×
                    return fail("remote sent a non-ref attestation for a bookmark");
1647
                };
164830×
                let (old_state, new_state) = (*old_state, *new_state);
164930×
                let serial = self
165030×
                    .check_ref_attest(
165130×
                        sa,
165230×
                        &r.name,
165330×
                        &old_state,
165430×
                        &new_state,
165530×
                        self.last_seen_serial(remote_name, &r.name),
1656
                        true,
1657
                    )
165830×
                    .map_err(|e| {
16590×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
16600×
                    })?;
166130×
                if new_state != r.state {
16620×
                    return fail(format!(
1663
                        "attestation for {}/{} does not cover its current state",
1664
                        remote_name, r.name
1665
                    ));
166630×
                }
166730×
                let ar = self.store.put_attest(&sa.attest)?;
166830×
                for sig in &sa.sigs {
166930×
                    self.store.put_signature(&ar, sig)?;
1670
                }
167130×
                self.record_serial(remote_name, &r.name, serial)?;
1672347×
            }
1673377×
            view.remotes
1674377×
                .entry(remote_name.to_string())
1675377×
                .or_default()
1676377×
                .insert(r.name.clone(), state);
1677377×
            report.push((r.name, r.heads, imported.len()));
1678
        }
1679369×
        let mut new_tags = 0;
1680369×
        for t in &resp.tags {
168113×
            if view.tags.contains_key(&t.name) {
16824×
                continue;
16839×
            }
1684
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
16859×
            let missing: Vec<ChangeHash> = t
16869×
                .heads
16879×
                .iter()
16889×
                .filter(|h| !self.store.has(h))
16899×
                .copied()
16909×
                .collect();
16919×
            if !missing.is_empty() {
16920×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
16930×
                let bundle = remote.fetch(&needed, max_blob)?;
16940×
                self.import_bundle(&bundle, false)?;
16959×
            }
16969×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
16979×
            self.adopt_tag(&mut view, t, policy.as_ref())
16989×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
16999×
            new_tags += 1;
1700
        }
1701369×
        if view != op.view {
1702358×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
170311×
        }
1704369×
        let _ = self.run_hook(
1705369×
            "post-fetch",
1706369×
            &format!(
1707
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1708369×
                json_str(remote_name),
1709377×
                json_array(report.iter().map(|(n, heads, _)| format!(
1710
                    "{{\"name\":{},\"heads\":{}}}",
1711377×
                    json_str(n),
1712509×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1713
                )))
1714
            ),
1715
        );
1716369×
        Ok(FetchReport {
1717369×
            refs: report,
1718369×
            unverified,
1719369×
            new_tags,
1720369×
            log_notes,
1721369×
        })
1722375×
    }
1723
1724
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1725
    /// the changes within `depth` steps of its heads, and the boundary below.
17261×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
17271×
        let remote = self.open_named_remote(remote_name)?;
17281×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
17291×
        let resp = remote.refs()?;
17301×
        let bookmark = self.config.bookmark.clone();
17311×
        if let Some(sp) = &resp.policy {
17320×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
17330×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
17340×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
17351×
        }
17361×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
17370×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1738
        };
17391×
        if r.heads.is_empty() {
17400×
            return Ok(0);
17411×
        }
1742
        // Base: the remote's checkpoint of exactly these heads.
17431×
        let cp_bundle = remote.checkpoint(&r.heads)?;
17441×
        let mut cp_ref = None;
17453×
        for (ty, body) in &cp_bundle.objects {
17463×
            let put = self.store.put(*ty, body)?;
17473×
            if *ty == ObjectType::Checkpoint {
17481×
                cp_ref = Some(put);
17492×
            }
1750
        }
17511×
        let Some(cp_ref) = cp_ref else {
17520×
            return fail(format!("{remote_name} sent no checkpoint"));
1753
        };
17541×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1755
        // History window.
17561×
        let wanted = remote.shallow(&r.heads, depth)?;
17571×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
17581×
        let imported = self.import_bundle_shallow(&bundle, false)?;
17591×
        if self.config.max_blob.is_some() {
17600×
            self.register_missing_blobs(&imported, remote_name)?;
17611×
        }
17621×
        self.refresh_boundary(&imported)?;
17631×
        if let Some(sa) = &r.attestation {
17640×
            let ar = self.store.put_attest(&sa.attest)?;
17650×
            for sig in &sa.sigs {
17660×
                self.store.put_signature(&ar, sig)?;
1767
            }
17680×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
17690×
                self.record_serial(remote_name, &r.name, serial)?;
17700×
            }
17711×
        }
17721×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
17731×
        let (op_ref, op) = self.head_op()?;
17741×
        let mut view = op.view.clone();
17751×
        view.remotes
17761×
            .entry(remote_name.to_string())
17771×
            .or_default()
17781×
            .insert(r.name.clone(), state);
17791×
        self.record_op(
17801×
            &[op_ref],
17811×
            &format!("oxy fetch {remote_name} --depth {depth}"),
17821×
            view,
17830×
        )?;
17841×
        Ok(imported.len())
17851×
    }
1786
1787
    /// Fetch, then take the union of the local bookmark's state with the
1788
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1789109×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1790109×
        let _wc = self.lock_working_copy()?;
1791109×
        self.fetch(remote_name)?;
1792106×
        let (op_ref, op) = self.head_op()?;
1793106×
        let current = self.config.bookmark.clone();
1794106×
        let mut local_current = self.heads_of(&op.view, &current)?;
1795106×
        local_current.sort();
1796106×
        let mut view = op.view.clone();
1797106×
        let mut current_heads = local_current.clone();
1798106×
        let mut changed = false;
1799106×
        let mut others = Vec::new();
1800106×
        let tracked = op
1801106×
            .view
1802106×
            .remotes
1803106×
            .get(remote_name)
1804106×
            .cloned()
1805106×
            .unwrap_or_default();
1806110×
        for (name, remote_state) in tracked {
1807
            // Every local bookmark tracks the remote's of the same name;
1808
            // the current one may be new here.
1809110×
            let local_state = op.view.bookmarks.get(&name).copied();
1810110×
            if local_state.is_none() && name != current {
18110×
                continue;
1812110×
            }
1813110×
            if local_state == Some(remote_state) {
18149×
                continue;
1815101×
            }
1816101×
            let local = self.heads_of(&op.view, &name)?;
1817101×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1818137×
            if remote_heads.iter().all(|h| local.contains(h)) {
18190×
                continue;
1820101×
            }
1821101×
            let mut all = local.clone();
1822101×
            all.extend(remote_heads);
1823101×
            let st = self.load_state_history(&all)?;
1824101×
            let mut heads = st.maximal(&all);
1825101×
            heads.sort();
1826101×
            let mut sorted_local = local;
1827101×
            sorted_local.sort();
1828101×
            if heads == sorted_local {
18291×
                continue;
1830100×
            }
1831100×
            view.bookmarks.insert(
1832100×
                name.clone(),
1833100×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1834
            );
1835100×
            if name == current {
183698×
                changed = true;
183798×
                current_heads = heads;
183898×
            } else {
18392×
                others.push(name);
18402×
            }
1841
        }
1842106×
        if changed || !others.is_empty() {
184399×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
18447×
        }
1845
        // The working copy follows its bookmark whenever nothing would be
1846
        // lost, also when this pull brought nothing new but it had been
1847
        // left behind (oxygen#89).
1848106×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1849
        Ok(PullReport {
1850106×
            heads: if changed {
185198×
                current_heads
1852
            } else {
18538×
                local_current
1854
            },
1855106×
            changed,
1856106×
            checked_out,
1857106×
            others,
1858
        })
1859109×
    }
1860
1861
    /// How many changes the working copy's bookmark has that its base
1862
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1863
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1864
    /// the bookmark or holds changes the bookmark lacks. History is read
1865
    /// only when the base and the bookmark's heads differ (oxygen#89).
18667×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
18677×
        let (_, wc) = self.working_copy()?;
18687×
        let mut base = wc.deps.clone();
18697×
        base.sort();
18707×
        let mut heads = self.bookmark_heads()?;
18717×
        heads.sort();
18727×
        if base == heads || heads.is_empty() {
18736×
            return Ok(None);
18741×
        }
18751×
        let state = self.load_state_history(&heads)?;
18761×
        if !base.iter().all(|h| state.contains(h)) {
18770×
            return Ok(None);
18781×
        }
18791×
        let had = if base.is_empty() {
18800×
            0
1881
        } else {
18821×
            self.load_state_history(&base)?.len()
1883
        };
18841×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
18857×
    }
1886
1887
    /// Bring the working copy to `heads`, the state of its bookmark
1888
    /// `bookmark`, when nothing would be lost: its base is part of that
1889
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1890
    /// with uncommitted work, the work comes along when the new changes
1891
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1892
    /// it followed only from exactly the bookmark's old heads, so a working
1893
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1894
    /// or a pull from another workspace) never caught up, and nothing said
1895
    /// so (oxygen#74, #89). Returns whether it moved.
1896106×
    pub fn follow_bookmark(
1897106×
        &self,
1898106×
        heads: &[ChangeHash],
1899106×
        bookmark: &str,
1900106×
        command: &str,
1901106×
    ) -> Result<bool> {
1902106×
        let snap = self.snapshot(command)?;
1903106×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1904106×
        let mut base = snap.base.maximal(&snap.wc.deps);
1905106×
        base.sort();
1906106×
        let mut target = heads.to_vec();
1907106×
        target.sort();
1908106×
        if base == target {
19097×
            return Ok(false);
191099×
        }
191199×
        let state = self.load_state_history(heads)?;
1912177×
        if !base.iter().all(|h| state.contains(h)) {
1913
            // The working copy holds changes the bookmark lacks: not ours to move.
19140×
            return Ok(false);
191599×
        }
191699×
        if clean {
191799×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
191899×
            Ok(true)
1919
        } else {
19200×
            Ok(self
19210×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
19220×
                .is_ok())
1923
        }
1924106×
    }
1925
1926
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1927
    /// changes and attesting the reference when a key is available.
1928
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1929
    /// state, attested when we have an identity. The local bookmark, if
1930
    /// any, is kept; only the remote-tracking entry goes.
19315×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
19325×
        let remote = self.open_named_remote(remote_name)?;
19335×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
19345×
        let resp = remote.refs()?;
19357×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
19361×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1937
        };
19384×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
19390×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
19404×
        }
19414×
        let attestation = match self.secret_key()? {
19422×
            Some(_) => Some(self.sign_attest(&Attest {
19432×
                repo: self.id()?,
19442×
                hlc: Hlc::now(),
19452×
                body: AttestBody::Ref {
19462×
                    name: bookmark.to_string(),
19472×
                    old_state: r.state,
19482×
                    new_state: ObjectRef::ZERO,
19492×
                    serial: r.last_serial.unwrap_or(0) + 1,
19502×
                },
19510×
            })?),
19522×
            None => None,
1953
        };
19544×
        let results = remote.push(
19554×
            Bundle::default(),
19564×
            vec![RefUpdate {
19574×
                name: bookmark.to_string(),
19584×
                old_state: r.state,
19594×
                new_state: ObjectRef::ZERO,
19604×
                force: true,
19614×
                attestation,
19624×
            }],
19634×
            None,
19644×
            vec![],
19650×
        )?;
19664×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
19672×
            let (op_ref, op) = self.head_op()?;
19682×
            let mut view = op.view.clone();
19692×
            if let Some(m) = view.remotes.get_mut(remote_name) {
19702×
                m.remove(bookmark);
19712×
            }
19722×
            self.record_op(
19732×
                &[op_ref],
19742×
                &format!("oxy push {remote_name} --delete {bookmark}"),
19752×
                view,
19760×
            )?;
19772×
        }
19784×
        Ok(results)
19795×
    }
1980
1981
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1982
    /// repository's config (its URL, token, CA and store settings), its
1983
    /// tracking bookmarks in the view, and a store remote's mirror under
1984
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
19853×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
19863×
        if !self.config.remotes.contains_key(name) {
19871×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
19882×
        }
19892×
        let prefix = format!("remote.{name}.");
19902×
        let keys: Vec<String> = self
19912×
            .config
19922×
            .repo_layer()
19932×
            .keys()
19944×
            .filter(|k| k.starts_with(&prefix))
19952×
            .cloned()
19962×
            .collect();
19973×
        for k in keys {
19983×
            self.config.set(&k, "")?;
1999
        }
20002×
        self.config.remotes.remove(name);
20012×
        self.save_config()?;
20022×
        let (op_ref, op) = self.head_op()?;
20032×
        if op.view.remotes.contains_key(name) {
20041×
            let mut view = op.view.clone();
20051×
            view.remotes.remove(name);
20061×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
20071×
        }
20082×
        let mirror = self.oxy.join("remotes").join(name);
20092×
        if mirror.is_dir() {
20100×
            fs::remove_dir_all(&mirror)?;
20112×
        }
20122×
        Ok(())
20133×
    }
2014
2015
    /// `changes`, in dependency order, cut into batches of about
2016
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2017
    /// There is always one, perhaps empty.
2018290×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2019290×
        let blob_len = |r: &ObjectRef| -> u64 {
202029×
            self.store
202129×
                .get_typed(r, ObjectType::Blob)
202229×
                .ok()
202329×
                .and_then(|b| Blob::decode(&b).ok())
202429×
                .map_or(0, |b| b.length)
202529×
        };
2026290×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2027394×
        for h in changes {
2028394×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2029394×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2030394×
            let mut weight = raw.len() as u64;
2031522×
            for t in &texts {
2032522×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
203326×
                    weight += blob_len(r);
2034496×
                }
2035
            }
2036682×
            for e in &c.edits {
20373×
                if let Edit::Replace { new: Some(b), .. } = e {
20383×
                    weight += blob_len(b);
2039679×
                }
2040
            }
2041394×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
20425×
                out.push(std::mem::take(&mut batch));
20435×
                bytes = 0;
2044389×
            }
2045394×
            batch.push(*h);
2046394×
            bytes += weight;
2047
        }
2048290×
        out.push(batch);
2049290×
        Ok(out)
2050290×
    }
2051
2052360×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2053360×
        let bookmark = self.config.bookmark.clone();
2054360×
        self.push_bookmark(remote_name, &bookmark, force)
2055360×
    }
2056
2057
    /// `push` for a named bookmark (`oxy push -b NAME`).
2058368×
    pub fn push_bookmark(
2059368×
        &self,
2060368×
        remote_name: &str,
2061368×
        bookmark: &str,
2062368×
        force: bool,
2063368×
    ) -> Result<Vec<RefResult>> {
2064368×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2065368×
    }
2066
2067
    /// `push_bookmark`, saying how a long push is going: one line per
2068
    /// batch sent (oxygen#95).
2069376×
    pub fn push_bookmark_with(
2070376×
        &self,
2071376×
        remote_name: &str,
2072376×
        bookmark: &str,
2073376×
        force: bool,
2074376×
        progress: crate::store::Progress,
2075376×
    ) -> Result<Vec<RefResult>> {
2076376×
        let (op_ref, op) = self.head_op()?;
2077376×
        if !op.view.bookmarks.contains_key(bookmark) {
20780×
            return fail(format!("no bookmark {bookmark}"));
2079376×
        }
2080376×
        let bookmark = bookmark.to_string();
2081376×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2082
        // pre-push hook: may veto before the remote is contacted.
2083376×
        self.run_hook(
2084376×
            "pre-push",
2085376×
            &format!(
2086
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2087376×
                json_str(remote_name),
2088376×
                json_str(&bookmark),
2089751×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2090
            ),
20911×
        )?;
2092375×
        let remote = self.open_named_remote(remote_name)?;
2093375×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2094372×
        let resp = remote.refs()?;
2095372×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2096372×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2097372×
        let policy_to_send = match (&local_policy, &resp.policy) {
209829×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
209910×
            (Some(l), None) => Some(l.clone()),
210016×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
21011×
                return fail(format!(
2102
                    "{remote_name} has a newer policy (serial {}); fetch first",
2103
                    r.policy.serial
2104
                ));
2105
            }
2106348×
            _ => None,
2107
        };
2108371×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2109371×
        if remote_has_policy && self.secret_key()?.is_none() {
21101×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2111370×
        }
2112370×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2113370×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2114370×
            .tag_refs()?
2115370×
            .into_iter()
2116370×
            .filter(|t| !remote_tags.contains(&t.name))
2117370×
            .collect();
2118370×
        let refs = resp.refs;
2119370×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2120370×
        let (remote_state, remote_heads, last_serial) =
2121370×
            match refs.iter().find(|r| r.name == bookmark) {
2122353×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
212317×
                None => (empty, vec![], None),
2124
            };
2125370×
        let new_state = self
2126370×
            .store
2127370×
            .put_state(&StateObject::new(local_heads.clone()))?;
2128
        // A push that carries a policy re-attests the bookmark even when its
2129
        // state is unchanged, so the current attestation is always by a key
2130
        // the current policy authorizes (a revoked key's attestation would
2131
        // otherwise be refused by every later fetch).
2132370×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
21339×
            return Ok(vec![RefResult {
21349×
                name: bookmark,
21359×
                ok: true,
21369×
                reason: "already up to date".into(),
21379×
            }]);
2138361×
        }
2139393×
        for h in &remote_heads {
2140393×
            if !self.store.has(h) {
214170×
                return fail(format!(
2142
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
214370×
                    h.short(12)
2144
                ));
2145323×
            }
2146
        }
2147291×
        if !force {
2148291×
            let closure = self.closure_in_store(&local_heads)?;
2149304×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
21500×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2151291×
            }
21520×
        }
2153291×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2154291×
        let key = self.secret_key()?.map(|(k, _)| k);
2155291×
        if let Some(key) = key {
2156
            // Seal this author's changes that carry no valid authenticator,
2157
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2158
            // are stored, so each batch's bundle carries those it needs.
215987×
            let mut unsigned = Vec::new();
216087×
            for h in &to_send {
216179×
                let c = self.store.get_change_meta(h)?;
216279×
                if self.seals_for_author(&c.author, &key)
216376×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
216447×
                {
216547×
                    unsigned.push(*h);
216647×
                }
2167
            }
216887×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
216944×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2170
            }
2171204×
        }
2172
        // A long history goes in batches, in dependency order, so neither
2173
        // side holds it whole and no request passes the remote's limit:
2174
        // all but the last carry objects alone; the last moves the bookmark
2175
        // (oxygen#95).
2176290×
        let batches = self.push_batches(&to_send)?;
2177290×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2178290×
        for (i, batch) in earlier.iter().enumerate() {
21795×
            progress(&format!(
21805×
                "part {} of {}: {} changes",
21815×
                i + 1,
21825×
                batches.len(),
21835×
                batch.len()
21845×
            ));
21855×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
21865×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
21875×
                Some(r) if r.ok => {}
21880×
                Some(r) => {
21890×
                    return fail(format!(
2190
                        "{remote_name} refused part {} of the push: {}",
21910×
                        i + 1,
2192
                        r.reason
2193
                    ))
2194
                }
2195
                None => {
21960×
                    return fail(format!(
2197
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2198
                    ))
2199
                }
2200
            }
2201
        }
2202290×
        if batches.len() > 1 {
22031×
            progress(&format!(
22041×
                "part {} of {}: {} changes",
22051×
                batches.len(),
22061×
                batches.len(),
22071×
                last.len()
22081×
            ));
2209289×
        }
2210290×
        let mut bundle = self.bundle_for(last)?;
2211290×
        bundle.objects.push((
2212290×
            ObjectType::State,
2213290×
            StateObject::new(local_heads.clone()).encode(),
2214290×
        ));
2215290×
        let attestation = match key {
221686×
            Some(_) => Some(self.sign_attest(&Attest {
221786×
                repo: self.id()?,
221886×
                hlc: Hlc::now(),
221986×
                body: AttestBody::Ref {
222086×
                    name: bookmark.clone(),
222186×
                    old_state: remote_state,
222286×
                    new_state,
222386×
                    serial: next_serial(last_serial),
222486×
                },
22251×
            })?),
2226204×
            None => None,
2227
        };
2228
        // Whoever signed the move, and whom a delegate acts for, travel with
2229
        // it: a receiver that has never seen a change by this delegate could
2230
        // not otherwise check its signature (oxygenhub#129).
2231289×
        if attestation.is_some() {
2232170×
            for k in [self.signing_key(), self.config.author_key]
223385×
                .into_iter()
223485×
                .flatten()
2235
            {
2236170×
                if let Ok(id) = self.identity(&k) {
2237170×
                    let body = id.encode();
2238170×
                    if !bundle
2239170×
                        .objects
2240170×
                        .iter()
2241197×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
224217×
                    {
224317×
                        bundle.objects.push((ObjectType::Identity, body));
2244153×
                    }
22450×
                }
2246
            }
2247
            // A short-lived signing key's certificate goes with it (§14.7).
224885×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
224985×
            self.attach_certificates_for(&mut bundle, &signers)?;
2250204×
        }
2251289×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
225285×
            AttestBody::Ref { serial, .. } => Some(serial),
22530×
            _ => None,
225485×
        });
2255289×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2256
        // Tag states must be present on the remote: bundle their changes too.
2257289×
        for t in &tags_to_send {
22586×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
22596×
            let extra: Vec<ChangeHash> =
22606×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
22616×
            if !extra.is_empty() {
22620×
                let more = self.bundle_for(&extra)?;
22630×
                bundle.changes.extend(more.changes);
22640×
                bundle.hashes.extend(more.hashes);
22650×
                bundle.attests.extend(more.attests);
22660×
                bundle.objects.extend(more.objects);
22676×
            }
22686×
            bundle.objects.push((
22696×
                ObjectType::State,
22706×
                StateObject::new(t.heads.clone()).encode(),
22716×
            ));
2272
        }
2273289×
        if let Some(l) = &policy_to_send {
227423×
            let remote_serial = resp_policy_serial;
227523×
            bundle.policies = self
227623×
                .policy_history()?
227723×
                .into_iter()
227850×
                .filter(|sp| {
227950×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
228025×
                        && sp.policy.serial < l.policy.serial
228150×
                })
228223×
                .collect();
2283266×
        }
2284289×
        let results = remote.push(
2285289×
            bundle,
2286289×
            vec![RefUpdate {
2287289×
                name: bookmark.clone(),
2288289×
                old_state: remote_state,
2289289×
                new_state,
2290289×
                force,
2291289×
                attestation,
2292289×
            }],
2293289×
            policy_to_send,
2294289×
            tags_to_send,
22957×
        )?;
229623×
        if let (Some(serial), true) = (
2297282×
            sent_serial,
2298288×
            results.iter().any(|r| r.ok && r.name == "policy"),
2299
        ) {
230023×
            self.record_policy_serial(remote_name, serial)?;
2301259×
        }
2302305×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2303259×
            let mut view = op.view.clone();
2304259×
            view.remotes
2305259×
                .entry(remote_name.to_string())
2306259×
                .or_default()
2307259×
                .insert(bookmark.clone(), new_state);
2308259×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2309256×
            if let Some(s) = serial {
231064×
                self.record_serial(remote_name, &bookmark, s)?;
2311192×
            }
231223×
        }
2313277×
        Ok(results)
2314376×
    }
2315
2316
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2317
    /// bookmark set to the remote's, working copy checked out.
2318241×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2319241×
        Self::clone_with(url, dest, None, &[])
2320241×
    }
2321
2322
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2323
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2324
    /// unless a size is given, so out-of-scope binaries are never fetched).
2325249×
    pub fn clone_with(
2326249×
        url: &str,
2327249×
        dest: &Path,
2328249×
        max_blob: Option<u64>,
2329249×
        sparse: &[String],
2330249×
    ) -> Result<Repo> {
2331249×
        Self::clone_full(url, dest, max_blob, sparse, None)
2332249×
    }
2333
2334
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2335
    /// changes within `depth` steps of them; the rest is the boundary.
23361×
    pub fn clone_shallow(
23371×
        url: &str,
23381×
        dest: &Path,
23391×
        depth: u32,
23401×
        max_blob: Option<u64>,
23411×
        sparse: &[String],
23421×
    ) -> Result<Repo> {
23431×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
23441×
    }
2345
2346250×
    fn clone_full(
2347250×
        url: &str,
2348250×
        dest: &Path,
2349250×
        max_blob: Option<u64>,
2350250×
        sparse: &[String],
2351250×
        depth: Option<u32>,
2352250×
    ) -> Result<Repo> {
2353250×
        let options = crate::credentials::Credentials::user().options_for(url);
2354250×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2355250×
    }
2356
2357
    /// Clone a subrepo with the credentials the parent would use for its
2358
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2359
    /// subrepo: it finds the same ones again through its parent.
236010×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
236110×
        let options = self.credentials_for(url);
236210×
        Self::clone_using(url, dest, None, &[], None, &options)
236310×
    }
2364
2365
    /// The name of a remote of this repository on the same hub (scheme,
2366
    /// host and port) as `url`.
236723×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
236827×
        let origin = |u: &str| -> Option<String> {
236927×
            let (scheme, rest) = u.split_once("://")?;
23708×
            if !matches!(scheme, "http" | "https") {
23710×
                return None;
23728×
            }
23738×
            let host = rest.split('/').next()?;
23748×
            Some(format!(
23758×
                "{}://{}",
23768×
                scheme.to_ascii_lowercase(),
23778×
                host.to_ascii_lowercase()
23788×
            ))
237927×
        };
238023×
        let want = origin(url)?;
23814×
        self.config
23824×
            .remotes
23834×
            .iter()
23844×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
23854×
            .map(|(name, _)| name.clone())
238623×
    }
2387
2388
    /// The token and CA to reach `url` with: those of a remote of this
2389
    /// repository on the same hub (scheme, host and port), else the
2390
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2391
    /// and enclosing checkouts', as a clone would use them.
239223×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
239323×
        match self.remote_on_same_hub(url) {
23941×
            Some(name) => RemoteOptions {
23951×
                repo_id: None,
23961×
                cache_dir: None,
23971×
                ..self.remote_options(&name)
23981×
            },
2399
            None => {
240022×
                let mut options = RemoteOptions::default();
240122×
                self.fill_credentials(url, &mut options);
240222×
                options
2403
            }
2404
        }
240523×
    }
2406
2407260×
    fn clone_using(
2408260×
        url: &str,
2409260×
        dest: &Path,
2410260×
        max_blob: Option<u64>,
2411260×
        sparse: &[String],
2412260×
        depth: Option<u32>,
2413260×
        options: &RemoteOptions,
2414260×
    ) -> Result<Repo> {
2415260×
        let remote = open_remote(url, options)?;
2416260×
        let id = remote.repo_id()?;
2417256×
        if id == crate::protocol::UNBOUND_ID {
24182×
            return fail(format!(
2419
                "{url} is empty and unbound: push a repository to it first"
2420
            ));
2421254×
        }
2422254×
        let mut repo = Repo::init_with_id(dest, id)?;
2423254×
        repo.config
2424254×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2425254×
        if let Some(m) = max_blob {
24262×
            repo.config.set("filter.max-blob", &m.to_string())?;
2427252×
        } else if !sparse.is_empty() {
24281×
            repo.config.set("filter.max-blob", "0")?;
2429251×
        }
2430254×
        if !sparse.is_empty() {
24311×
            repo.config.set("filter.paths", &sparse.join(","))?;
2432253×
        }
2433254×
        repo.save_config()?;
2434254×
        if let Some(depth) = depth {
24351×
            repo.fetch_shallow("origin", depth)?;
2436
        } else {
2437253×
            repo.fetch("origin")?;
2438
        }
2439253×
        let (op_ref, op) = repo.head_op()?;
2440
        // The remote's default bookmark, else ours (main), else its only one.
2441253×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2442
        // Asked of the remote as now configured, so a store-backed one
2443
        // answers from the mirror the fetch just filled.
2444253×
        let advertised = repo
2445253×
            .open_named_remote("origin")
2446253×
            .ok()
2447253×
            .and_then(|r| r.refs().ok())
2448253×
            .and_then(|r| r.default_bookmark);
2449253×
        let bookmark = advertised
2450253×
            .filter(|b| theirs.contains_key(b))
2451253×
            .or_else(|| {
24527×
                theirs
24537×
                    .contains_key(&repo.config.bookmark)
24547×
                    .then(|| repo.config.bookmark.clone())
24557×
            })
2456253×
            .or_else(|| {
24570×
                (theirs.len() == 1)
24580×
                    .then(|| theirs.keys().next().cloned())
24590×
                    .flatten()
24600×
            })
2461253×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2462253×
        let initial = repo.config.bookmark.clone();
2463253×
        if bookmark != repo.config.bookmark {
24641×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
24651×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
24661×
            repo.config.bookmark = bookmark.clone();
2467252×
        }
2468253×
        if let Some(state) = theirs.get(&bookmark).copied() {
2469253×
            let heads = repo.store.get_state(&state)?.heads;
2470253×
            let mut view = op.view.clone();
2471
            // The empty bookmark `init` made goes when another is checked out.
2472253×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
24731×
                view.bookmarks.remove(&initial);
2474252×
            }
2475253×
            view.bookmarks.insert(bookmark, state);
2476253×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2477253×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
24780×
        }
2479253×
        Ok(repo)
2480260×
    }
2481
}
2482
2483
/// The serial of a reference's next attestation: one more than the last the
2484
/// remote reports, or, for a bookmark the remote does not have, the clock in
2485
/// milliseconds, so a bookmark created again after a deletion goes past the
2486
/// deletion's serial the remote keeps.
248786×
fn next_serial(last: Option<u64>) -> u64 {
248886×
    match last {
248956×
        Some(l) => l + 1,
249030×
        None => Hlc::now().wall_ms.max(1),
2491
    }
249286×
}