OXYGENHUB

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

1839 of 2046 lines run, 270 of 388 functions · run #356 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
    /// What checking the host's transparency log found short of a fork
34
    /// (spec §14.8): attestations not logged yet, a log that could not be
35
    /// read. A fork fails the fetch instead.
36
    pub log_notes: Vec<String>,
37
    /// Bookmarks left as they were because their attestation could not be
38
    /// verified (its signer unknown here, or its signature bad), each with
39
    /// why (oxygenhub#266). The current bookmark is never skipped: its
40
    /// fetch fails instead.
41
    pub skipped: Vec<(String, String)>,
42
}
43
44
#[derive(Debug, Clone, PartialEq, Eq)]
45
pub struct PullReport {
46
    /// The current bookmark's heads after the pull.
47
    pub heads: Vec<ChangeHash>,
48
    /// Whether the current bookmark changed.
49
    pub changed: bool,
50
    pub checked_out: bool,
51
    /// Other bookmarks the pull moved: each local bookmark tracks the
52
    /// remote's of the same name.
53
    pub others: Vec<String>,
54
    /// What the fetch left as it was ([`FetchReport::skipped`]).
55
    pub skipped: Vec<(String, String)>,
56
}
57
58
/// The result a push of objects alone reports (a batch of a long history):
59
/// not a reference.
60
pub const OBJECTS_RESULT: &str = "objects";
61
62
impl Repo {
63
    // ------------------------------------------------------------ serving (spec §16)
64
651920×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
661920×
        self.oxy.join("attest").join(name_file(bookmark))
671920×
    }
68
69
    /// The latest reference attestation stored for a bookmark.
701327×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
711327×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
72292×
            Ok(h) => {
73292×
                let r = ObjectRef::from_hex(h.trim())
74292×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
75
                Ok(Some((
76292×
                    r,
77
                    SignedAttest {
78292×
                        attest: self.store.get_attest(&r)?,
79292×
                        sigs: self.store.signatures(&r)?,
80
                    },
81
                )))
82
            }
831035×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
840×
            Err(e) => Err(e.into()),
85
        }
861327×
    }
87
8897×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
8997×
        fs::create_dir_all(self.oxy.join("attest"))?;
9097×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
9197×
    }
92
931051×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
941051×
        let view = self.view()?;
951051×
        let mut out = Vec::new();
961104×
        for (name, state) in &view.bookmarks {
971104×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
981104×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
99186×
                AttestBody::Ref { serial, .. } => Some(serial),
1000×
                _ => None,
101186×
            });
1021104×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1031104×
            let accepted = match &attestation {
104175×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
105929×
                None => None,
106
            };
1071104×
            out.push(RemoteRef {
1081104×
                name: name.clone(),
1091104×
                state: *state,
1101104×
                heads: self.store.get_state(state)?.heads,
1111104×
                attestation,
1121104×
                last_serial,
1131104×
                accepted,
1141104×
                logged: None,
1151104×
                integration: vec![],
116
            });
117
        }
1181051×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1191051×
        let history = self
1201051×
            .policy_history()?
1211051×
            .into_iter()
1221051×
            .filter(|sp| {
123146×
                policy
124146×
                    .as_ref()
125146×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
126146×
            })
1271051×
            .collect();
128
        Ok(RefsResponse {
1291051×
            refs: out,
1301051×
            policy,
1311051×
            tags: self.tag_refs()?,
1321051×
            history,
1331051×
            default_bookmark: Some(self.config.bookmark.clone()),
1341051×
            log: None,
1351051×
            witnesses: vec![],
136
        })
1371051×
    }
138
139
    /// Every change reachable from `heads` that is in the store.
1401428×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1411428×
        let mut seen = BTreeSet::new();
1421428×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1434833×
        while let Some(h) = stack.pop() {
1443405×
            if seen.contains(&h) || !self.store.has(&h) {
1451010×
                continue;
1462395×
            }
1472395×
            seen.insert(h);
1482395×
            stack.extend(self.store.get_change_meta(&h)?.deps);
149
        }
1501428×
        Ok(seen)
1511428×
    }
152
153
    /// The changes within `depth` dependency steps of `heads` (spec §17),
154
    /// nearest first; depth 1 is the heads themselves.
1553×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1563×
        let mut out = Vec::new();
1573×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1583×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1593×
        for _ in 0..depth.max(1) {
1608×
            let mut next = Vec::new();
16112×
            for h in layer {
16212×
                if !seen.insert(h) || !self.store.has(&h) {
1632×
                    continue;
16410×
                }
16510×
                let c = self.store.get_change(&h)?;
16610×
                next.extend(c.deps.iter().copied());
16710×
                out.push(h);
168
            }
1698×
            if next.is_empty() {
1701×
                break;
1717×
            }
1727×
            layer = next;
173
        }
1743×
        out.reverse();
1753×
        Ok(out)
1763×
    }
177
1782051×
    fn shallow_path(&self) -> PathBuf {
1792051×
        self.oxy.join("shallow")
1802051×
    }
181
182
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1832048×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1842048×
        fs::read_to_string(self.shallow_path())
1852048×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1862048×
            .unwrap_or_default()
1872048×
    }
188
189190×
    pub fn is_shallow(&self) -> bool {
190190×
        !self.boundary().is_empty()
191190×
    }
192
1933×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1943×
        if boundary.is_empty() {
1951×
            let _ = fs::remove_file(self.shallow_path());
1961×
            return Ok(());
1972×
        }
1982×
        let text: String = boundary
1992×
            .iter()
2002×
            .map(|h| format!("{}\n", h.to_hex()))
2012×
            .collect();
2022×
        write_atomic(&self.shallow_path(), text.as_bytes())
2033×
    }
204
205
    /// Recompute the boundary from what is stored: every dependency of a
206
    /// stored change that is not itself stored.
2073×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2083×
        let mut boundary = self.boundary();
2093×
        boundary.retain(|h| !self.store.has(h));
21010×
        for h in imported {
21113×
            for d in self.store.get_change_meta(h)?.deps {
21213×
                if !self.store.has(&d) {
2132×
                    boundary.insert(d);
21411×
                }
215
            }
216
        }
2173×
        self.write_boundary(&boundary)
2183×
    }
219
220
    /// Fetch `depth` more levels of history below the shallow boundary.
2212×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2222×
        let boundary = self.boundary();
2232×
        if boundary.is_empty() {
2240×
            return Ok(0);
2252×
        }
2262×
        let remote = self.open_named_remote(remote_name)?;
2272×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2282×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2292×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2302×
        if self.config.max_blob.is_some() {
2310×
            self.register_missing_blobs(&imported, remote_name)?;
2322×
        }
2332×
        self.refresh_boundary(&imported)?;
2342×
        Ok(imported.len())
2352×
    }
236
237
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
238824×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
239824×
        let have = self.closure_in_store(have)?;
240
        // In a shallow repository the walk stops at the boundary, whose
241
        // changes the remote is assumed to hold.
242824×
        let boundary = self.boundary();
243824×
        let mut out = Vec::new();
244824×
        let mut done: BTreeSet<ChangeHash> = have.clone();
245824×
        done.extend(boundary.iter().copied());
246
        // Iterative post-order DFS.
2471277×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2483376×
        while let Some((h, expanded)) = stack.pop() {
2492552×
            if done.contains(&h) {
250434×
                continue;
2512118×
            }
2522118×
            if !self.store.has(&h) {
2530×
                return fail(format!("change {} is not in this repository", h.short(12)));
2542118×
            }
2552118×
            if expanded {
2561059×
                done.insert(h);
2571059×
                out.push(h);
2581059×
                continue;
2591059×
            }
2601059×
            stack.push((h, true));
2611059×
            for d in self.store.get_change_meta(&h)?.deps {
262718×
                if !done.contains(&d) {
263216×
                    stack.push((d, false));
264502×
                }
265
            }
266
        }
267824×
        Ok(out)
268824×
    }
269
270
    /// Bundle changes (in the given dependency order) with their signatures,
271
    /// seals, identities, blobs, chunks.
272318×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
273318×
        self.bundle_of(changes, None, false, false)
274318×
    }
275
276
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2774×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2784×
        let mut out = Vec::new();
2794×
        for r in refs {
2804×
            let (ty, body) = match self.store.get(r) {
2814×
                Ok(x) => x,
2820×
                Err(StoreError::NotFound(_)) => continue,
2830×
                Err(e) => return Err(e.into()),
284
            };
2854×
            if ty == ObjectType::Blob {
2865×
                for c in Blob::decode(&body)?.chunks {
2875×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2885×
                        out.push((cty, cb));
2895×
                    }
290
                }
2910×
            }
2924×
            out.push((ty, body));
293
        }
2944×
        Ok(out)
2954×
    }
296
297
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
298
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
299
    ///
300
    /// This is what a server answers a fetch with, so it also carries what
301
    /// verifies the attestations it serves beside it (see
302
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
30348×
    pub fn bundle_for_filtered(
30448×
        &self,
30548×
        changes: &[ChangeHash],
30648×
        max_blob: Option<u64>,
30748×
    ) -> Result<Bundle> {
30848×
        self.bundle_of(changes, max_blob, false, true)
30948×
    }
310
311
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
312
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
313
    /// with their text blobs and chunks among the objects, so neither side
314
    /// decodes or encodes their text.
315360×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
316360×
        self.bundle_of(changes, max_blob, true, true)
317360×
    }
318
319
    /// The keys that signed the attestations this repository serves with
320
    /// its references: each bookmark's latest and each tag's. A fetch
321
    /// bundle carries their identities and certificates (spec §16.2), so a
322
    /// client can check an attestation whose signer signed none of the
323
    /// changes it receives, a delegate or a short-lived key that only
324
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
325
    /// list per reference; nothing per change.
326408×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
327408×
        let view = self.view()?;
328408×
        let pointers = view
329408×
            .bookmarks
330408×
            .keys()
331496×
            .map(|b| self.ref_attest_path(b))
332408×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
333408×
        let mut keys = BTreeSet::new();
334509×
        for p in pointers {
335509×
            let Ok(text) = fs::read_to_string(&p) else {
336362×
                continue;
337
            };
338147×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3390×
                continue;
340
            };
341147×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
342
        }
343408×
        Ok(keys)
344408×
    }
345
346
    /// `serving`: a fetch's answer, which carries the identities and
347
    /// certificates of [`Repo::served_attest_signers`] too.
348726×
    fn bundle_of(
349726×
        &self,
350726×
        changes: &[ChangeHash],
351726×
        max_blob: Option<u64>,
352726×
        raw: bool,
353726×
        serving: bool,
354726×
    ) -> Result<Bundle> {
355726×
        let mut bundle = Bundle::default();
356726×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
357726×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3581203×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3591203×
            if !r.is_zero() && self.store.has(r) {
360334×
                objects.insert(*r);
361869×
            }
3621203×
        };
363980×
        for h in changes {
364
            // Raw: the stored bytes, and a skeleton for the rest.
365980×
            let (c, encoded) = if raw {
366524×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
367524×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3684975×
                for t in texts {
3694975×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3703×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3713×
                        objects.insert(r);
3723×
                        objects.extend(blob.chunks);
3734972×
                    }
374
                }
375524×
                (skel, Some(bytes))
376
            } else {
377456×
                (self.store.get_change(h)?, None)
378
            };
379980×
            let sigs = self.store.signatures(h)?;
380980×
            add_object(&c.author, &mut objects);
381980×
            for s in &sigs {
38237×
                add_object(&s.key, &mut objects);
38337×
            }
3845953×
            for e in &c.edits {
3855953×
                if let Edit::Replace { old, new, .. } = e {
38614×
                    for b in [old, new].into_iter().flatten() {
38714×
                        if self.store.has(b) {
38814×
                            if let Ok(blob) =
38914×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
390
                            {
39114×
                                if max_blob.is_some_and(|m| blob.length > m) {
3924×
                                    continue;
39310×
                                }
39410×
                                objects.insert(*b);
39510×
                                objects.extend(blob.chunks.iter().copied());
3960×
                            }
3970×
                        }
398
                    }
3995941×
                }
400
            }
401980×
            for s in self.store.seals_for(h)? {
40295×
                seals.insert(s);
40395×
            }
404980×
            match encoded {
405524×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
406456×
                None => {
407456×
                    bundle.changes.push((c, sigs));
408456×
                    bundle.hashes.push(*h);
409456×
                }
410
            }
411
        }
412726×
        for r in seals {
41390×
            let attest = self.store.get_attest(&r)?;
41490×
            let sigs = self.store.signatures(&r)?;
41590×
            for s in &sigs {
41690×
                add_object(&s.key, &mut objects);
41790×
            }
41890×
            bundle.attests.push(SignedAttest { attest, sigs });
419
        }
420726×
        let signers: Vec<KeyId> = if serving {
421408×
            let signers = self.served_attest_signers()?;
422408×
            for k in &signers {
42396×
                add_object(k, &mut objects);
42496×
            }
425408×
            signers.into_iter().collect()
426
        } else {
427318×
            Vec::new()
428
        };
429726×
        for r in objects {
430197×
            let (ty, body) = self.store.get(&r)?;
431197×
            bundle.objects.push((ty, body));
432
        }
433726×
        self.attach_certificates_for(&mut bundle, &signers)?;
434726×
        Ok(bundle)
435726×
    }
436
437
    /// Add the certificates of short-lived keys that signed what `bundle`
438
    /// carries, and their issuers' identities, so a receiver can tell who
439
    /// they stand for (spec §14.7). `also` names more signers (a reference
440
    /// attestation sent beside the bundle).
441821×
    pub(crate) fn attach_certificates_for(
442821×
        &self,
443821×
        bundle: &mut Bundle,
444821×
        also: &[KeyId],
445821×
    ) -> Result<()> {
446821×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
447821×
        keys.extend(
448821×
            bundle
449821×
                .changes
450821×
                .iter()
451821×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
452
        );
453821×
        keys.extend(
454821×
            bundle
455821×
                .raw_changes
456821×
                .iter()
457821×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
458
        );
459821×
        keys.extend(
460821×
            bundle
461821×
                .attests
462821×
                .iter()
463821×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
464
        );
465821×
        for k in keys {
466289×
            let Some(r) = self.store.certificate_of(&k)? else {
467263×
                continue;
468
            };
46926×
            let cert = self.store.get_certificate(&r)?;
47026×
            if bundle
47126×
                .certificates
47226×
                .iter()
47326×
                .any(|c| c.cert.hash() == cert.cert.hash())
474
            {
4757×
                continue;
47619×
            }
47738×
            for id in [&k, &cert.cert.issuer] {
47838×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
47938×
                    if !bundle
48038×
                        .objects
48138×
                        .iter()
48265×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
48319×
                    {
48419×
                        bundle.objects.push((ObjectType::Identity, body));
48519×
                    }
4860×
                }
487
            }
48819×
            bundle.certificates.push(cert);
489
        }
490821×
        Ok(())
491821×
    }
492
493
    /// Keep the certificates a bundle brings once each verifies with the
494
    /// identity of the issuer it names; one that does not refuses the bundle.
495768×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
496768×
        for c in certs {
49718×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4980×
                RepoError::Msg(format!(
4990×
                    "a certificate names issuer {}, whose identity did not come with it",
5000×
                    c.cert.issuer.short(12)
5010×
                ))
5020×
            })?;
50318×
            c.verify(&issuer)
50418×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
50518×
            self.store.put_identity(&c.cert.key)?;
50618×
            self.store.put_certificate(c)?;
507
        }
508768×
        Ok(())
509768×
    }
510
511
    /// A signer authorized for `reference` by what an issuer certified it
512
    /// as (spec §14.7): a short-lived key with a kept certificate that
513
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
514
    /// signer did not choose) and names a subject the policy grants.
51529×
    pub(crate) fn certified_authorized(
51629×
        &self,
51729×
        p: &crate::policy::Policy,
51829×
        signer: &KeyId,
51929×
        reference: &str,
52029×
        scope: Scope,
52129×
        at_ms: u64,
52229×
    ) -> bool {
52329×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5245×
            return false;
525
        };
52624×
        let Ok(c) = self.store.get_certificate(&r) else {
5270×
            return false;
528
        };
52924×
        let Some(issuer) = p
53024×
            .identity(&c.cert.issuer)
53124×
            .cloned()
53224×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
533
        else {
5340×
            return false;
535
        };
53624×
        c.verify(&issuer).is_ok()
53724×
            && c.cert.key_id() == *signer
53824×
            && c.cert.covers(scope, at_ms)
53920×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
54029×
    }
541
542
    /// Store a bundle's contents. With `strict`, every change must
543
    /// authenticate (signature or seal by its author or a delegate).
544765×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
545765×
        self.import_bundle_inner(bundle, strict, false)
546765×
    }
547
548
    /// Like `import_bundle`, accepting changes whose dependencies are absent
549
    /// (they join the shallow boundary).
5503×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5513×
        self.import_bundle_inner(bundle, strict, true)
5523×
    }
553
554768×
    fn import_bundle_inner(
555768×
        &self,
556768×
        bundle: &Bundle,
557768×
        strict: bool,
558768×
        shallow: bool,
559768×
    ) -> Result<Vec<ChangeHash>> {
560768×
        let batch = self.store.begin_batch()?;
561768×
        let result = self.import_bundle_batched(bundle, strict, shallow);
562768×
        batch.finish()?;
563766×
        result
564768×
    }
565
566768×
    fn import_bundle_batched(
567768×
        &self,
568768×
        bundle: &Bundle,
569768×
        strict: bool,
570768×
        shallow: bool,
571768×
    ) -> Result<Vec<ChangeHash>> {
572768×
        for (ty, _) in &bundle.objects {
5730×
            if !matches!(
574606×
                ty,
575
                ObjectType::Chunk
576
                    | ObjectType::Blob
577
                    | ObjectType::Identity
578
                    | ObjectType::State
579
                    | ObjectType::Checkpoint
580
            ) {
5810×
                return fail(format!("bundle may not carry {} objects", ty.name()));
582606×
            }
583
        }
584
        // All at once: in a large batch they are compressed on every core.
585768×
        let objects: Vec<(ObjectType, &[u8])> = bundle
586768×
            .objects
587768×
            .iter()
588768×
            .map(|(ty, body)| (*ty, body.as_slice()))
589768×
            .collect();
590768×
        self.store.put_many(&objects)?;
591768×
        self.adopt_certificates(&bundle.certificates)?;
592768×
        for sa in &bundle.attests {
59393×
            let r = self.store.put_attest(&sa.attest)?;
59493×
            for sig in &sa.sigs {
59593×
                self.store.put_signature(&r, sig)?;
596
            }
59793×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
59898×
                for h in hashes {
59998×
                    self.store.index_seal(h, &r)?;
600
                }
6010×
            }
602
        }
603
        // Each change's hash: from the bundle when its maker knew it, else
604
        // worked out once (for a change adding a whole tree, hashing is
605
        // chunking all its text).
606768×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
607759×
            bundle.hashes.clone()
608
        } else {
6099×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
610
        };
611768×
        let raw_hashes: Vec<ChangeHash> = bundle
612768×
            .raw_changes
613768×
            .iter()
614768×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
615768×
            .collect();
616768×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
617768×
        let boundary = self.boundary();
618768×
        let mut imported = Vec::new();
619
        // Changes as stored: checked, then stored as they are, their text
620
        // blobs having come with the objects.
621768×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
622525×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
623525×
            for d in &skel.deps {
624382×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
625
                {
6260×
                    return fail(format!(
627
                        "change {} depends on {}, which is neither stored nor in the bundle",
6280×
                        h.short(12),
6290×
                        d.short(12)
630
                    ));
631382×
                }
632
            }
6334976×
            for t in texts {
6344976×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6354×
                    if !self.store.has(&r) {
6361×
                        return fail(format!(
637
                            "change {} came without its text blob {}",
6381×
                            h.short(12),
6391×
                            r.short(12)
640
                        ));
6413×
                    }
6424972×
                }
643
            }
644524×
            self.store.put(ObjectType::Change, bytes)?;
645524×
            for sig in sigs {
64613×
                self.store.put_signature(&h, sig)?;
647
            }
648524×
            imported.push(h);
649
        }
650767×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
651484×
            for d in &c.deps {
652290×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
653
                {
6543×
                    return fail(format!(
655
                        "change {} depends on {}, which is neither stored nor in the bundle",
6563×
                        h.short(12),
6573×
                        d.short(12)
658
                    ));
659287×
                }
660
            }
661481×
            let stored = self.store.put_change(c)?;
662481×
            if stored != h {
6630×
                return fail(format!(
664
                    "change {} is not the change the bundle names",
6650×
                    h.short(12)
666
                ));
667481×
            }
668481×
            for sig in sigs {
66933×
                self.store.put_signature(&h, sig)?;
670
            }
671481×
            imported.push(h);
672
        }
673764×
        if strict {
67449×
            for h in &imported {
67534×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6764×
                    return fail(format!(
677
                        "change {} is not authenticated by its author",
6784×
                        h.short(12)
679
                    ));
68030×
                }
681
            }
682715×
        }
683760×
        Ok(imported)
684768×
    }
685
686
    /// Verify a reference attestation against an update it claims to describe.
687
    /// `allow_equal` lets a client re-read the attestation it already has; a
688
    /// server receiving a push requires a strictly greater serial.
689
    /// A reference attestation signed by a delegate of an identity the
690
    /// rule lists is authorized as that identity (spec §14.5): the identity
691
    /// named the delegate with the `refs` scope, still in force at `at_ms`
692
    /// (the attestation's wall time), and the policy names the identity.
693
    /// Revoked keys authorize nothing either way.
69436×
    pub(crate) fn delegate_authorized(
69536×
        &self,
69636×
        p: &crate::policy::Policy,
69736×
        signer: &KeyId,
69836×
        reference: &str,
69936×
        at_ms: u64,
70036×
    ) -> bool {
70136×
        if p.is_revoked(signer) {
7021×
            return false;
70335×
        }
70435×
        let Some(rule) = p.rule_for(reference) else {
7050×
            return false;
706
        };
70736×
        rule.keys.iter().any(|k| {
70836×
            !p.is_revoked(k)
70936×
                && p.identity(k)
71036×
                    .cloned()
71136×
                    .or_else(|| self.store.get_identity(k).ok())
71236×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
71336×
        })
71436×
    }
715
716
    /// A lasting attestation (a tag) signed by a key the policy has since
717
    /// rotated away from (spec §14.2) is authorized as the key that
718
    /// succeeded it: a key the rule lists reaches the signer through
719
    /// `previous` links, and the attestation is dated (`at_ms`) before the
720
    /// signer's successor was made, so a superseded key makes nothing new.
721
    /// Revoked keys authorize nothing.
7226×
    pub(crate) fn predecessor_authorized(
7236×
        &self,
7246×
        p: &crate::policy::Policy,
7256×
        signer: &KeyId,
7266×
        reference: &str,
7276×
        at_ms: u64,
7286×
    ) -> bool {
7296×
        if p.is_revoked(signer) {
7300×
            return false;
7316×
        }
7326×
        let Some(rule) = p.rule_for(reference) else {
7330×
            return false;
734
        };
7357×
        let identity = |k: &KeyId| {
7367×
            p.identity(k)
7377×
                .cloned()
7387×
                .or_else(|| self.store.get_identity(k).ok())
7397×
        };
7406×
        rule.keys.iter().any(|k| {
7416×
            if p.is_revoked(k) {
7420×
                return false;
7436×
            }
7446×
            let mut cur = identity(k);
7456×
            for _ in 0..32 {
7467×
                let Some(id) = cur else {
7470×
                    return false;
748
                };
7491×
                match id.previous {
7506×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7511×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
7521×
                    _ => return false,
753
                }
754
            }
7550×
            false
7566×
        })
7576×
    }
758
75994×
    fn check_ref_attest(
76094×
        &self,
76194×
        sa: &SignedAttest,
76294×
        name: &str,
76394×
        old_state: &ObjectRef,
76494×
        new_state: &ObjectRef,
76594×
        last_serial: Option<u64>,
76694×
        allow_equal: bool,
76794×
    ) -> std::result::Result<u64, String> {
76892×
        let serial =
76994×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
77092×
        self.verify_attest_signature(sa)?;
77192×
        Ok(serial)
77294×
    }
773
774
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
775
    /// attestation describes this update of this repository with a serial
776
    /// past the last seen.
777152×
    fn check_ref_attest_body(
778152×
        &self,
779152×
        sa: &SignedAttest,
780152×
        name: &str,
781152×
        old_state: &ObjectRef,
782152×
        new_state: &ObjectRef,
783152×
        last_serial: Option<u64>,
784152×
        allow_equal: bool,
785152×
    ) -> std::result::Result<u64, String> {
786
        let AttestBody::Ref {
787152×
            name: n,
788152×
            old_state: o,
789152×
            new_state: nw,
790152×
            serial,
791152×
        } = &sa.attest.body
792
        else {
7930×
            return Err("attestation is not a ref attestation".into());
794
        };
795152×
        if n != name || o != old_state || nw != new_state {
7961×
            return Err("attestation does not describe this update".into());
797151×
        }
798151×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7990×
            return Err("attestation is for a different repository".into());
800151×
        }
801151×
        if let Some(last) = last_serial {
80280×
            if *serial < last || (*serial == last && !allow_equal) {
8031×
                return Err(format!(
8041×
                    "attestation serial {serial} is not greater than the last seen {last}"
8051×
                ));
80679×
            }
80771×
        }
808150×
        Ok(*serial)
809152×
    }
810
811
    /// An attestation's first signature verifies with its signer's
812
    /// identity, which must be stored here.
813150×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
814150×
        let r = sa.attest.hash();
815150×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
816150×
        let id = self
817150×
            .store
818150×
            .get_identity(&sig.key)
819150×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
820144×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
821150×
    }
822
823
    /// Accept a push (spec §16.4). Without a trust policy every repository
824
    /// is unverified, so unsigned changes and unattested updates are accepted;
825
    /// attestations that are present must still be valid. With a policy,
826
    /// every change and update is checked against it. A newer policy in the
827
    /// push is applied first when it is signed by the current roots.
828295×
    pub fn receive_push(
829295×
        &self,
830295×
        bundle: Bundle,
831295×
        updates: Vec<RefUpdate>,
832295×
        policy: Option<SignedPolicy>,
833295×
        tags: Vec<crate::protocol::TagRef>,
834295×
    ) -> Result<Vec<RefResult>> {
835295×
        Ok(self
836295×
            .receive_push_report(bundle, updates, policy, tags)?
837
            .results)
838295×
    }
839
840
    /// `receive_push` with what a host wants to log: each accepted
841
    /// reference's old and new state and heads, and the changes this push
842
    /// stored (hub spec §6.12).
843336×
    pub fn receive_push_report(
844336×
        &self,
845336×
        bundle: Bundle,
846336×
        updates: Vec<RefUpdate>,
847336×
        policy: Option<SignedPolicy>,
848336×
        tags: Vec<crate::protocol::TagRef>,
849336×
    ) -> Result<PushReport> {
850
        // Updates are checked against the head as it is now, not as this
851
        // handle first read it (oxygenhub#249): another push may have
852
        // landed since.
853336×
        self.refresh()?;
854336×
        let mut report = PushReport::default();
855336×
        let results = &mut report.results;
856336×
        if let Some(sp) = policy {
85729×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
85827×
                Ok(()) => {
85927×
                    results.push(RefResult {
86027×
                        name: "policy".into(),
86127×
                        ok: true,
86227×
                        reason: format!("serial {}", sp.policy.serial),
86327×
                    });
86427×
                }
8652×
                Err(e) => {
8662×
                    results.push(RefResult {
8672×
                        name: "policy".into(),
8682×
                        ok: false,
8692×
                        reason: e,
8702×
                    });
8712×
                    for u in updates {
8720×
                        results.push(RefResult {
8730×
                            name: u.name,
8740×
                            ok: false,
8750×
                            reason: "policy update was rejected".into(),
8760×
                        });
8770×
                    }
8782×
                    return Ok(report);
879
                }
880
            }
881307×
        }
882334×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
883
        // A push of objects alone (one batch of a long history, oxygen#95)
884
        // names no reference: its outcome is reported as `objects`.
885334×
        let objects_only = updates.is_empty() && tags.is_empty();
886334×
        match self.import_bundle(&bundle, policy.is_some()) {
887328×
            Ok(imported) => {
888328×
                if objects_only {
8897×
                    results.push(RefResult {
8907×
                        name: OBJECTS_RESULT.into(),
8917×
                        ok: true,
8927×
                        reason: format!("{} changes stored", imported.len()),
8937×
                    });
894321×
                }
895328×
                report.imported = imported;
896
            }
8976×
            Err(e) => {
8986×
                if objects_only {
8990×
                    results.push(RefResult {
9000×
                        name: OBJECTS_RESULT.into(),
9010×
                        ok: false,
9020×
                        reason: e.to_string(),
9030×
                    });
9046×
                }
9056×
                for u in updates {
9066×
                    results.push(RefResult {
9076×
                        name: u.name,
9086×
                        ok: false,
9096×
                        reason: e.to_string(),
9106×
                    });
9116×
                }
9126×
                return Ok(report);
913
            }
914
        }
915328×
        let (op_ref, op) = self.head_op()?;
916328×
        let mut view = op.view.clone();
917328×
        let mut names = Vec::new();
918328×
        for u in updates {
919319×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
920319×
            let (ok, reason) = match outcome {
921292×
                Ok(()) => (true, String::new()),
92227×
                Err(e) => (false, e),
923
            };
924319×
            if ok {
925292×
                names.push(u.name.clone());
926292×
                let heads = self
927292×
                    .store
928292×
                    .get_state(&u.new_state)
929292×
                    .map(|s| s.heads)
930292×
                    .unwrap_or_default();
931292×
                report.updated.push(RefUpdated {
932292×
                    name: u.name.clone(),
933292×
                    old_state: u.old_state,
934292×
                    new_state: u.new_state,
935292×
                    heads,
936292×
                });
93727×
            }
938319×
            results.push(RefResult {
939319×
                name: u.name,
940319×
                ok,
941319×
                reason,
942319×
            });
943
        }
944328×
        for t in &tags {
9458×
            let name = format!("tags/{}", t.name);
9468×
            let new = !view.tags.contains_key(&t.name);
9478×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
948
                Ok(()) => {
949
                    // A tag new here is an update too, so a hub can start
950
                    // its pipeline's tag jobs (oxygenflow#24); one it
951
                    // already had, sent again, is not.
9526×
                    if new {
9536×
                        report.updated.push(RefUpdated {
9546×
                            name: name.clone(),
9556×
                            old_state: ObjectRef::ZERO,
9566×
                            new_state: t.state,
9576×
                            heads: t.heads.clone(),
9586×
                        });
9596×
                    }
9606×
                    names.push(name.clone());
9616×
                    results.push(RefResult {
9626×
                        name,
9636×
                        ok: true,
9646×
                        reason: String::new(),
9656×
                    });
966
                }
9672×
                Err(e) => results.push(RefResult {
9682×
                    name,
9692×
                    ok: false,
9702×
                    reason: e,
9712×
                }),
972
            }
973
        }
974328×
        if !names.is_empty() {
975292×
            self.record_op(
976292×
                &[op_ref],
977292×
                &format!("push received: {}", names.join(" ")),
978292×
                view,
9793×
            )?;
98036×
        }
981325×
        Ok(report)
982336×
    }
983
984
    /// Check an update's attestation against the latest one for its
985
    /// reference and store it as the new latest. Failures say what was
986
    /// being done, for which reference, so a refused push can be diagnosed
987
    /// from its reason alone.
98894×
    fn record_update_attest(
98994×
        &self,
99094×
        u: &RefUpdate,
99194×
        sa: &SignedAttest,
99294×
    ) -> std::result::Result<(), String> {
99394×
        let name = &u.name;
99494×
        let last = self
99594×
            .latest_ref_attest(name)
99694×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
99794×
            .and_then(|(_, a)| match a.attest.body {
99857×
                AttestBody::Ref { serial, .. } => Some(serial),
9990×
                _ => None,
100057×
            });
100194×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
100292×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
100392×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
100491×
        for sig in &sa.sigs {
100591×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1006
        }
100791×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1008
        // Signed by a short-lived key: a host records when it accepted it.
100988×
        let certified = sa
101088×
            .sigs
101188×
            .first()
101288×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
101388×
        if certified {
10143×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
101585×
        }
101688×
        Ok(())
101794×
    }
1018
1019
    /// Record that this host accepted attestation `r` now, signed with its
1020
    /// acceptor key (spec §14.7); nothing without one.
10214×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
10224×
        let Some(acceptor) = &self.acceptor else {
10233×
            return Ok(());
1024
        };
10251×
        let (id, sk) = (&acceptor.0, &acceptor.1);
10261×
        let attest = Attest {
10271×
            repo: self.id()?,
10281×
            hlc: Hlc::now(),
10291×
            body: AttestBody::Accepted { attest: *r },
1030
        };
10311×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
10321×
        self.store.put_identity(id)?;
10331×
        let a = self.store.put_attest(&attest)?;
10341×
        self.store.put_signature(&a, &sig)?;
10351×
        self.store.index_add_pub("accepted", r, &a)?;
10361×
        Ok(())
10374×
    }
1038
1039
    /// The host's acceptance of attestation `r`, if one was recorded.
1040177×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1041177×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1042167×
            return Ok(None);
1043
        };
1044
        Ok(Some(SignedAttest {
104510×
            attest: self.store.get_attest(&a)?,
104610×
            sigs: self.store.signatures(&a)?,
1047
        }))
1048177×
    }
1049
1050
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1051
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1052
    /// signer's certificate and accepts `sa`; else the attestation's own
1053
    /// time, which the signer chose.
105422×
    pub(crate) fn certified_time(
105522×
        &self,
105622×
        signer: &KeyId,
105722×
        sa: &SignedAttest,
105822×
        accepted: Option<&SignedAttest>,
105922×
    ) -> u64 {
106022×
        let own = sa.attest.hlc.wall_ms;
106122×
        let Some(acc) = accepted else {
106216×
            return own;
1063
        };
10646×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
10650×
            return own;
1066
        };
10676×
        let Ok(cert) = self.store.get_certificate(&c) else {
10680×
            return own;
1069
        };
10706×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
10710×
            return own;
1072
        };
10736×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
10741×
            return own;
1075
        };
10765×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
10770×
            return own;
1078
        };
10795×
        if *attest == sa.attest.hash()
10804×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1081
        {
10824×
            acc.attest.hlc.wall_ms
1083
        } else {
10841×
            own
1085
        }
108622×
    }
1087
1088
    /// A fetched bookmark's attestation by a signer the policy does not
1089
    /// list itself: a delegate or a short-lived key, whose authority
1090
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1091
    /// attestation's integrated time when the host's log gives one; else
1092
    /// as before, at the host's acceptance for a certified signer, when it
1093
    /// countersigned one, or at the attestation's own time, and said so
1094
    /// when the host keeps a log. Failing at the integrated time but not
1095
    /// as before is a note while logs are new; a large gap between the
1096
    /// claimed and the integrated time is a note.
1097
    #[allow(clippy::too_many_arguments)]
109818×
    pub(crate) fn authorize_in_time(
109918×
        &self,
110018×
        p: &crate::policy::Policy,
110118×
        remote_name: &str,
110218×
        r: &crate::protocol::RemoteRef,
110318×
        sa: &SignedAttest,
110418×
        signer: &KeyId,
110518×
        log: &super::transparency::LogCheck,
110618×
        notes: &mut Vec<String>,
110718×
    ) -> Result<()> {
1108
        use super::transparency::{gap_note, judge, Timed};
110918×
        let own = sa.attest.hlc.wall_ms;
111018×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
111118×
        let time = log.time_of(&r.name);
111220×
        let check = |t_delegate: u64, t_cert: u64| {
111320×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
111418×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
111520×
        };
111618×
        let before = if at != own {
11173×
            "the host's acceptance"
1118
        } else {
111915×
            "the time it claims"
1120
        };
112118×
        let what = format!("{remote_name}/{}", r.name);
112218×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1123
            Timed::Refused => {
11241×
                return fail(format!(
1125
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
11261×
                    signer.short(12)
1127
                ))
1128
            }
11293×
            Timed::Integrated => {}
11301×
            Timed::Disagrees => notes.push(format!(
1131
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
11321×
                signer.short(12),
11331×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1134
            )),
11351×
            Timed::Fallback if log.kept => notes.push(format!(
1136
                "{what}: {} checked at {before}, not at a witnessed time: {}",
11371×
                signer.short(12),
11381×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1139
            )),
114012×
            Timed::Fallback => {}
1141
        }
114217×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
11432×
            notes.push(format!("{what}'s attestation {n}"));
114415×
        }
114517×
        Ok(())
114618×
    }
1147
1148
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1149
    /// at `old_state`, is never the bookmark a non-bare repository has
1150
    /// checked out (a bare one's default is its host's to protect, see
1151
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1152
    /// an attestation by a key that may update it.
1153
    /// The deletion's attestation stays the bookmark's latest, so an older
1154
    /// one cannot be replayed to bring it back.
11553×
    fn apply_deletion(
11563×
        &self,
11573×
        view: &mut View,
11583×
        u: &RefUpdate,
11593×
        policy: Option<&crate::policy::Policy>,
11603×
    ) -> std::result::Result<(), String> {
11613×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
11620×
            return Err(format!("no bookmark {:?} to delete", u.name));
1163
        };
11643×
        if current != u.old_state {
11650×
            return Err("stale: the remote bookmark has moved; pull first".into());
11663×
        }
11673×
        if !self.is_bare() && u.name == self.config.bookmark {
11681×
            return Err(format!(
11691×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
11701×
                u.name
11711×
            ));
11722×
        }
11732×
        if let Some(p) = policy {
11740×
            let Some(sa) = &u.attestation else {
11750×
                return Err(format!(
11760×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
11770×
                    u.name
11780×
                ));
1179
            };
11800×
            let signer = sa
11810×
                .sigs
11820×
                .first()
11830×
                .map(|s| s.key)
11840×
                .ok_or("attestation carries no signature")?;
1185
            // Received now: the receiver's own clock is the trusted time.
11860×
            let now = Hlc::now().wall_ms;
11870×
            if !p.authorizes(&signer, &u.name)
11880×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11890×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1190
            {
11910×
                return Err(format!(
11920×
                    "key {} may not delete {:?} under this repository's policy",
11930×
                    signer.short(12),
11940×
                    u.name
11950×
                ));
11960×
            }
11972×
        }
11982×
        if let Some(sa) = &u.attestation {
11991×
            self.record_update_attest(u, sa)?;
12001×
        }
12012×
        view.bookmarks.remove(&u.name);
12022×
        Ok(())
12033×
    }
1204
1205319×
    fn apply_update(
1206319×
        &self,
1207319×
        view: &mut View,
1208319×
        u: &RefUpdate,
1209319×
        policy: Option<&crate::policy::Policy>,
1210319×
    ) -> std::result::Result<(), String> {
1211319×
        if u.name == "policy" {
12120×
            return Err(
12130×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
12140×
            );
1215319×
        }
1216319×
        let empty = self
1217319×
            .store
1218319×
            .put_state(&StateObject::new(vec![]))
1219319×
            .map_err(|e| e.to_string())?;
1220319×
        if u.new_state.is_zero() {
12213×
            return self.apply_deletion(view, u, policy);
1222316×
        }
1223316×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1224316×
        if current != u.old_state {
122510×
            return Err("stale: the remote bookmark has moved; pull first".into());
1226306×
        }
1227306×
        let new_state = self
1228306×
            .store
1229306×
            .get_state(&u.new_state)
1230306×
            .map_err(|_| "new state object is missing".to_string())?;
1231569×
        for h in &new_state.heads {
1232569×
            if !self.store.has(h) {
12331×
                return Err(format!("head {} is missing", h.short(12)));
1234568×
            }
1235
        }
1236305×
        if !u.force {
1237304×
            let old_heads = self
1238304×
                .store
1239304×
                .get_state(&current)
1240304×
                .map_err(|e| e.to_string())?
1241
                .heads;
1242304×
            let closure = self
1243304×
                .closure_in_store(&new_state.heads)
1244304×
                .map_err(|e| e.to_string())?;
1245304×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
12461×
                return Err(format!(
12471×
                    "not a fast-forward: current head {} would be dropped (use --force)",
12481×
                    h.short(12)
12491×
                ));
1250303×
            }
12511×
        }
1252304×
        if let Some(p) = policy {
125344×
            let Some(sa) = &u.attestation else {
12541×
                return Err(format!(
12551×
                    "{:?} requires a signed reference attestation under this repository's policy",
12561×
                    u.name
12571×
                ));
1258
            };
125943×
            let signer = sa
126043×
                .sigs
126143×
                .first()
126243×
                .map(|s| s.key)
126343×
                .ok_or("attestation carries no signature")?;
1264
            // Received now: the receiver's own clock is the trusted time.
126543×
            let now = Hlc::now().wall_ms;
126643×
            if !p.authorizes(&signer, &u.name)
126713×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
126810×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1269
            {
12707×
                return Err(format!(
12717×
                    "key {} may not update {:?} under this repository's policy",
12727×
                    signer.short(12),
12737×
                    u.name
12747×
                ));
127536×
            }
127636×
            let old_heads = self
127736×
                .store
127836×
                .get_state(&current)
127936×
                .map_err(|e| e.to_string())?
1280
                .heads;
128136×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1282260×
        }
1283296×
        if let Some(sa) = &u.attestation {
128493×
            self.record_update_attest(u, sa)?;
1285203×
        }
1286290×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1287290×
        Ok(())
1288319×
    }
1289
1290
    // ------------------------------------------------------------ client side
1291
12921403×
    fn remote_url(&self, name: &str) -> Result<String> {
12931403×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
12943×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
12953×
            RepoError::Msg(match names.as_slice() {
12963×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
12971×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1298
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
12991×
                    names.join(", "),
13001×
                    names[0],
13011×
                    names[0]
1302
                ),
13030×
                _ => format!(
1304
                    "no remote named {name:?}; this repository has {}",
13050×
                    names.join(", ")
1306
                ),
1307
            })
13083×
        })
13091403×
    }
1310
1311
    /// Refuse a remote that is another repository. An **unbound** remote
1312
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1313
    /// for pushes, which bind it to this repository's id (spec §16.1).
1314764×
    fn check_remote_id(
1315764×
        &self,
1316764×
        remote: &dyn crate::protocol::Remote,
1317764×
        remote_name: &str,
1318764×
        allow_unbound: bool,
1319764×
    ) -> Result<()> {
1320764×
        let theirs = remote.repo_id()?;
1321763×
        if theirs == self.id()? {
1322738×
            return Ok(());
132325×
        }
132425×
        if theirs == crate::protocol::UNBOUND_ID {
132522×
            if allow_unbound {
132621×
                return Ok(());
13271×
            }
13281×
            return fail(format!(
1329
                "remote {remote_name:?} is empty and unbound: push to it first"
1330
            ));
13313×
        }
13323×
        fail(format!(
1333
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1334
        ))
1335764×
    }
1336
1337
    /// Credentials and trust for a remote: `remote.<name>.token` and
1338
    /// `remote.<name>.ca`, else the defaults for its URL
1339
    /// ([`Repo::fill_credentials`]).
13401045×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
13411045×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
13421045×
        let mut options = RemoteOptions {
13431045×
            repo_id: self.id().ok(),
13441045×
            token: self.config.remote_tokens.get(name).cloned(),
13451045×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
13461045×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
13471045×
            ..RemoteOptions::default()
13481045×
        };
13491045×
        self.fill_credentials(&url, &mut options);
13501045×
        options
13511045×
    }
1352
1353
    /// The user's credential store (`credentials.toml` beside the user
1354
    /// configuration file).
13551066×
    pub fn credentials(&self) -> crate::credentials::Credentials {
13561066×
        crate::credentials::Credentials::at(
13571066×
            self.user_config
13581066×
                .parent()
13591066×
                .map(Path::to_path_buf)
13601066×
                .unwrap_or_else(default_home),
1361
        )
13621066×
    }
1363
1364
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1365
    /// then the user's credential store for its hub, then a remote on the
1366
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1367
    /// When the token is not this remote's own or the environment's, the
1368
    /// other tokens enclosing checkouts hold for the hub are kept to try
1369
    /// if it is refused: a stale stored login must not hide a parent's
1370
    /// good token (oxygen#112).
13711067×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
13721067×
        if options.token.is_some() && options.ca.is_some() {
13731×
            return;
13741066×
        }
13751066×
        let explicit =
13761066×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
13771066×
        let stored = self.credentials().options_for(url);
13781066×
        options.token = options.token.take().or(stored.token);
13791066×
        options.ca = options.ca.take().or(stored.ca);
13801066×
        let enclosing = self.enclosing_credentials(url);
13811066×
        if options.token.is_none() {
13821056×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
138310×
        }
13841066×
        if options.ca.is_none() {
13851002×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
138664×
        }
13871066×
        if !explicit {
13881059×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
13895×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
13902×
                    options.fallback_tokens.push(t);
13913×
                }
1392
            }
13937×
        }
13941067×
    }
1395
1396
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1397
    /// checkouts, nearest first.
13981066×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
13991066×
        let mut out = Vec::new();
14001066×
        let Some(hub) = crate::credentials::hub_of(url) else {
1401930×
            return out;
1402
        };
1403136×
        let mut at = self.root.parent();
1404552×
        while let Some(dir) = at {
1405416×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14060×
                break;
1407
            };
1408416×
            for (key, remote_url) in &cfg {
140915×
                let Some(name) = key
141015×
                    .strip_prefix("remote.")
141115×
                    .and_then(|k| k.strip_suffix(".url"))
1412
                else {
14137×
                    continue;
1414
                };
14158×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
14161×
                    continue;
14177×
                }
14187×
                out.push((
14197×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
14207×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
14217×
                ));
1422
            }
1423416×
            at = dir.parent();
1424
        }
1425136×
        out
14261066×
    }
1427
1428
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1429
    /// no changes and no reference updates, which the receiver stores.
14300×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
14310×
        let remote = self.open_named_remote(remote_name)?;
14320×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
14330×
        let mut bundle = Bundle::default();
14340×
        for r in seals {
14350×
            let attest = self.store.get_attest(r)?;
14360×
            let sigs = self.store.signatures(r)?;
14370×
            bundle
14380×
                .attests
14390×
                .push(crate::protocol::SignedAttest { attest, sigs });
1440
        }
14410×
        let results = remote.push(bundle, vec![], None, vec![])?;
14420×
        if let Some(r) = results.iter().find(|r| !r.ok) {
14430×
            return fail(format!("{}: {}", r.name, r.reason));
14440×
        }
14450×
        Ok(())
14460×
    }
1447
1448
    /// The remote whose URL starts with `base` (a hub), if configured.
14494×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
14504×
        let base = base.trim_end_matches('/');
14514×
        self.config
14524×
            .remotes
14534×
            .iter()
14544×
            .find(|(_, url)| url.trim_end_matches('/') == base)
14554×
            .map(|(name, _)| name.clone())
14564×
    }
1457
1458
    /// Open a remote by name or, failing that, by URL with the default
1459
    /// credentials (see [`Repo::credentials_for`]).
14600×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
14610×
        if let Some(name) = self.remote_for_url(url) {
14620×
            return Ok((name.clone(), self.open_named_remote(&name)?));
14630×
        }
14640×
        let options = RemoteOptions {
14650×
            repo_id: self.id().ok(),
14660×
            ..self.credentials_for(url)
14670×
        };
14680×
        Ok((url.to_string(), open_remote(url, &options)?))
14690×
    }
1470
1471
    /// Credentials for a URL: those of the configured remote with that
1472
    /// URL, else the environment's.
14734×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
14744×
        match self.remote_for_url(url) {
14754×
            Some(name) => self.remote_options(&name),
14760×
            None => RemoteOptions {
14770×
                repo_id: self.id().ok(),
14780×
                ..self.credentials_for(url)
14790×
            },
1480
        }
14814×
    }
1482
14831028×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
14841028×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
14851028×
    }
1486
1487178×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1488178×
        self.oxy
1489178×
            .join("remotes")
1490178×
            .join(remote)
1491178×
            .join(format!("{bookmark}.serial"))
1492178×
    }
1493
149458×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
149558×
        fs::read_to_string(self.serial_path(remote, bookmark))
149658×
            .ok()
149758×
            .and_then(|s| s.trim().parse().ok())
149858×
    }
1499
1500120×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1501120×
        let p = self.serial_path(remote, bookmark);
1502120×
        fs::create_dir_all(p.parent().unwrap())?;
1503120×
        write_atomic(&p, serial.to_string().as_bytes())
1504120×
    }
1505
1506425×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1507425×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1508425×
    }
1509
1510
    /// The highest policy serial `remote` has ever presented.
1511375×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1512375×
        fs::read_to_string(self.policy_serial_path(remote))
1513375×
            .ok()
1514375×
            .and_then(|s| s.trim().parse().ok())
1515375×
    }
1516
151750×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
151850×
        let p = self.policy_serial_path(remote);
151950×
        fs::create_dir_all(p.parent().unwrap())?;
152050×
        write_atomic(&p, serial.to_string().as_bytes())
152150×
    }
1522
152327×
    fn lazy_dir(&self) -> PathBuf {
152427×
        self.oxy.join("lazy")
152527×
    }
1526
1527
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
15284×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
15294×
        fs::create_dir_all(self.lazy_dir())?;
15304×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
15314×
    }
1532
1533
    /// Which remote promised an absent blob, if any.
153415×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
153515×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
153615×
            .ok()
153715×
            .map(|s| s.trim().to_string())
153815×
    }
1539
1540
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
15414×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
15424×
        let Some(remote_name) = self.lazy_remote(blob) else {
15430×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1544
        };
15454×
        let remote = self.open_named_remote(&remote_name)?;
15464×
        let objects = remote.objects(&[*blob])?;
15479×
        for (ty, body) in objects {
15489×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
15499×
                self.store.put(ty, &body)?;
15500×
            }
1551
        }
15524×
        if !self.store.has(blob) {
15530×
            return fail(format!(
1554
                "{remote_name} did not send blob {}",
15550×
                blob.short(12)
1556
            ));
15574×
        }
15584×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
15594×
        Ok(())
15604×
    }
1561
1562
    /// After importing from `remote`, record every blob the changes reference
1563
    /// that the store lacks as lazily available from that remote.
15644×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
15654×
        let mut n = 0;
15664×
        for h in changes {
15674×
            let c = self.store.get_change(h)?;
156813×
            for e in &c.edits {
156913×
                if let Edit::Replace { old, new, .. } = e {
15706×
                    for b in [old, new].into_iter().flatten() {
15716×
                        if !self.store.has(b) {
15724×
                            self.register_lazy(b, remote)?;
15734×
                            n += 1;
15742×
                        }
1575
                    }
15767×
                }
1577
            }
1578
        }
15794×
        Ok(n)
15804×
    }
1581
1582
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1583375×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1584375×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1585509×
        for st in view
1586375×
            .bookmarks
1587375×
            .values()
1588375×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1589
        {
1590509×
            if let Ok(s) = self.store.get_state(st) {
1591509×
                have.extend(s.heads);
1592509×
            }
1593
        }
1594375×
        have.extend(view.workspaces.values().copied());
1595375×
        Ok(have.into_iter().collect())
1596375×
    }
1597
1598
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1599381×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1600381×
        let remote = self.open_named_remote(remote_name)?;
1601378×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1602376×
        let resp = remote.refs()?;
1603
        // The host's transparency log (spec §14.8): a fork fails here.
1604375×
        let log = self.check_log(
1605375×
            &self.remote_url(remote_name)?,
1606375×
            self.config.remote_cas.get(remote_name).map(Path::new),
1607375×
            &resp,
16080×
        )?;
1609375×
        let mut log_notes = log.notes.clone();
1610
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1611
        // and signed by roots we trust, or on first contact. A remote that
1612
        // once presented a policy may never present none or an older one:
1613
        // that is a downgrade. A remote that never presented one is
1614
        // unverified, and this fetch is checked only as far as possible.
1615375×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1616375×
        let seen = self.remote_policy_serial(remote_name);
1617375×
        let mut unverified = false;
1618375×
        match &resp.policy {
161923×
            Some(sp) => {
162023×
                if seen.is_some_and(|s| sp.policy.serial < s) {
16210×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
162223×
                }
16239×
                match &local_policy {
16249×
                    Some(l) if sp.policy.serial < l.serial => {}
16259×
                    Some(l) if sp.policy.serial == l.serial => {
16265×
                        if sp.policy.hash() != l.hash() {
16270×
                            return fail(format!(
1628
                                "{remote_name} presents a different policy with the same serial {}",
1629
                                l.serial
1630
                            ));
16315×
                        }
1632
                    }
1633
                    _ => {
163418×
                        self.adopt_policy_chain(
163518×
                            &resp.history,
163618×
                            sp,
163718×
                            &format!("oxy fetch {remote_name}"),
1638
                        )
163918×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1640
                    }
1641
                }
164223×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1643
            }
1644
            None => {
1645352×
                if seen.is_some() {
16460×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1647352×
                }
1648352×
                unverified = true;
1649
            }
1650
        }
1651375×
        let policy = if unverified {
1652352×
            None
1653
        } else {
165423×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1655
        };
1656375×
        let (op_ref, op) = self.head_op()?;
1657375×
        let mut view = op.view.clone();
1658375×
        let have = self.known_heads(&view)?;
1659375×
        let mut report = Vec::new();
1660375×
        let mut skipped = Vec::new();
1661375×
        let max_blob = self.config.max_blob;
1662401×
        for r in resp.refs {
1663401×
            let needed = {
1664401×
                let _t = crate::timing::phase("fetch: negotiate");
1665401×
                remote.negotiate(&have, &r.heads)?
1666
            };
1667401×
            let bundle = {
1668401×
                let _t = crate::timing::phase("fetch: bundle");
1669401×
                remote.fetch(&needed, max_blob)?
1670
            };
1671
            // Changes are not individually re-verified here: the bookmark's
1672
            // attestation (checked below) binds its whole state, and the
1673
            // receiver of the push verified the added changes at that time.
1674401×
            let imported = {
1675401×
                let _t = crate::timing::phase("fetch: import");
1676401×
                self.import_bundle(&bundle, false)?
1677
            };
1678401×
            if max_blob.is_some() {
16794×
                self.register_missing_blobs(&imported, remote_name)?;
1680397×
            }
1681542×
            for h in &r.heads {
1682542×
                if !self.store.has(h) {
16830×
                    return fail(format!("remote did not send head {}", h.short(12)));
1684542×
                }
1685
            }
1686401×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1687401×
            if state != r.state {
16880×
                return fail(format!(
1689
                    "remote state {} does not match its heads",
16900×
                    r.state.short(12)
1691
                ));
1692401×
            }
1693401×
            if let Some(p) = &policy {
169426×
                let Some(sa) = &r.attestation else {
16950×
                    return fail(format!(
1696
                        "{remote_name}/{} has no attestation, which its policy requires",
1697
                        r.name
1698
                    ));
1699
                };
170026×
                let signer = sa
170126×
                    .sigs
170226×
                    .first()
170326×
                    .map(|s| s.key)
170426×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
170526×
                if !p.authorizes(&signer, &r.name) {
170611×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
170715×
                }
1708375×
            }
1709401×
            if let Some(sa) = &r.attestation {
1710
                let AttestBody::Ref {
171158×
                    old_state,
171258×
                    new_state,
1713
                    ..
171458×
                } = &sa.attest.body
1715
                else {
17160×
                    return fail("remote sent a non-ref attestation for a bookmark");
1717
                };
171858×
                let (old_state, new_state) = (*old_state, *new_state);
171958×
                let serial = self
172058×
                    .check_ref_attest_body(
172158×
                        sa,
172258×
                        &r.name,
172358×
                        &old_state,
172458×
                        &new_state,
172558×
                        self.last_seen_serial(remote_name, &r.name),
1726
                        true,
1727
                    )
172858×
                    .map_err(|e| {
17290×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
17300×
                    })?;
173158×
                if new_state != r.state {
17320×
                    return fail(format!(
1733
                        "attestation for {}/{} does not cover its current state",
1734
                        remote_name, r.name
1735
                    ));
173658×
                }
1737
                // A signature this client cannot verify (its signer unknown
1738
                // here, as from a host that did not send the identity, or
1739
                // bad) fails that bookmark alone: it stays as it was and
1740
                // the rest are fetched (oxygenhub#266). The current
1741
                // bookmark, which a pull would take, still fails the fetch.
1742
                // A policy's requirements were checked above and still fail.
174358×
                if let Err(e) = self.verify_attest_signature(sa) {
174412×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
174512×
                    if r.name == self.config.bookmark {
17463×
                        return fail(why);
17479×
                    }
17489×
                    skipped.push((r.name, why));
17499×
                    continue;
175046×
                }
175146×
                let ar = self.store.put_attest(&sa.attest)?;
175246×
                for sig in &sa.sigs {
175346×
                    self.store.put_signature(&ar, sig)?;
1754
                }
175546×
                self.record_serial(remote_name, &r.name, serial)?;
1756343×
            }
1757389×
            view.remotes
1758389×
                .entry(remote_name.to_string())
1759389×
                .or_default()
1760389×
                .insert(r.name.clone(), state);
1761389×
            report.push((r.name, r.heads, imported.len()));
1762
        }
1763372×
        let mut new_tags = 0;
1764372×
        for t in &resp.tags {
176513×
            if view.tags.contains_key(&t.name) {
17664×
                continue;
17679×
            }
1768
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
17699×
            let missing: Vec<ChangeHash> = t
17709×
                .heads
17719×
                .iter()
17729×
                .filter(|h| !self.store.has(h))
17739×
                .copied()
17749×
                .collect();
17759×
            if !missing.is_empty() {
17760×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
17770×
                let bundle = remote.fetch(&needed, max_blob)?;
17780×
                self.import_bundle(&bundle, false)?;
17799×
            }
17809×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
17819×
            self.adopt_tag(&mut view, t, policy.as_ref())
17829×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
17839×
            new_tags += 1;
1784
        }
1785372×
        if view != op.view {
1786358×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
178714×
        }
1788372×
        let _ = self.run_hook(
1789372×
            "post-fetch",
1790372×
            &format!(
1791
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1792372×
                json_str(remote_name),
1793386×
                json_array(report.iter().map(|(n, heads, _)| format!(
1794
                    "{{\"name\":{},\"heads\":{}}}",
1795386×
                    json_str(n),
1796527×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1797
                )))
1798
            ),
1799
        );
1800372×
        Ok(FetchReport {
1801372×
            refs: report,
1802372×
            unverified,
1803372×
            new_tags,
1804372×
            log_notes,
1805372×
            skipped,
1806372×
        })
1807381×
    }
1808
1809
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1810
    /// the changes within `depth` steps of its heads, and the boundary below.
18111×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
18121×
        let remote = self.open_named_remote(remote_name)?;
18131×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
18141×
        let resp = remote.refs()?;
18151×
        let bookmark = self.config.bookmark.clone();
18161×
        if let Some(sp) = &resp.policy {
18170×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
18180×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
18190×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
18201×
        }
18211×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
18220×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1823
        };
18241×
        if r.heads.is_empty() {
18250×
            return Ok(0);
18261×
        }
1827
        // Base: the remote's checkpoint of exactly these heads.
18281×
        let cp_bundle = remote.checkpoint(&r.heads)?;
18291×
        let mut cp_ref = None;
18303×
        for (ty, body) in &cp_bundle.objects {
18313×
            let put = self.store.put(*ty, body)?;
18323×
            if *ty == ObjectType::Checkpoint {
18331×
                cp_ref = Some(put);
18342×
            }
1835
        }
18361×
        let Some(cp_ref) = cp_ref else {
18370×
            return fail(format!("{remote_name} sent no checkpoint"));
1838
        };
18391×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1840
        // History window.
18411×
        let wanted = remote.shallow(&r.heads, depth)?;
18421×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
18431×
        let imported = self.import_bundle_shallow(&bundle, false)?;
18441×
        if self.config.max_blob.is_some() {
18450×
            self.register_missing_blobs(&imported, remote_name)?;
18461×
        }
18471×
        self.refresh_boundary(&imported)?;
18481×
        if let Some(sa) = &r.attestation {
18490×
            let ar = self.store.put_attest(&sa.attest)?;
18500×
            for sig in &sa.sigs {
18510×
                self.store.put_signature(&ar, sig)?;
1852
            }
18530×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
18540×
                self.record_serial(remote_name, &r.name, serial)?;
18550×
            }
18561×
        }
18571×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
18581×
        let (op_ref, op) = self.head_op()?;
18591×
        let mut view = op.view.clone();
18601×
        view.remotes
18611×
            .entry(remote_name.to_string())
18621×
            .or_default()
18631×
            .insert(r.name.clone(), state);
18641×
        self.record_op(
18651×
            &[op_ref],
18661×
            &format!("oxy fetch {remote_name} --depth {depth}"),
18671×
            view,
18680×
        )?;
18691×
        Ok(imported.len())
18701×
    }
1871
1872
    /// Fetch, then take the union of the local bookmark's state with the
1873
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1874109×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1875109×
        let _wc = self.lock_working_copy()?;
1876109×
        let skipped = self.fetch(remote_name)?.skipped;
1877105×
        let (op_ref, op) = self.head_op()?;
1878105×
        let current = self.config.bookmark.clone();
1879105×
        let mut local_current = self.heads_of(&op.view, &current)?;
1880105×
        local_current.sort();
1881105×
        let mut view = op.view.clone();
1882105×
        let mut current_heads = local_current.clone();
1883105×
        let mut changed = false;
1884105×
        let mut others = Vec::new();
1885105×
        let tracked = op
1886105×
            .view
1887105×
            .remotes
1888105×
            .get(remote_name)
1889105×
            .cloned()
1890105×
            .unwrap_or_default();
1891110×
        for (name, remote_state) in tracked {
1892
            // Every local bookmark tracks the remote's of the same name;
1893
            // the current one may be new here.
1894110×
            let local_state = op.view.bookmarks.get(&name).copied();
1895110×
            if local_state.is_none() && name != current {
18961×
                continue;
1897109×
            }
1898109×
            if local_state == Some(remote_state) {
189910×
                continue;
190099×
            }
190199×
            let local = self.heads_of(&op.view, &name)?;
190299×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1903150×
            if remote_heads.iter().all(|h| local.contains(h)) {
19040×
                continue;
190599×
            }
190699×
            let mut all = local.clone();
190799×
            all.extend(remote_heads);
190899×
            let st = self.load_state_history(&all)?;
190999×
            let mut heads = st.maximal(&all);
191099×
            heads.sort();
191199×
            let mut sorted_local = local;
191299×
            sorted_local.sort();
191399×
            if heads == sorted_local {
19141×
                continue;
191598×
            }
191698×
            view.bookmarks.insert(
191798×
                name.clone(),
191898×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1919
            );
192098×
            if name == current {
192196×
                changed = true;
192296×
                current_heads = heads;
192396×
            } else {
19242×
                others.push(name);
19252×
            }
1926
        }
1927105×
        if changed || !others.is_empty() {
192897×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
19298×
        }
1930
        // The working copy follows its bookmark whenever nothing would be
1931
        // lost, also when this pull brought nothing new but it had been
1932
        // left behind (oxygen#89).
1933105×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1934
        Ok(PullReport {
1935105×
            heads: if changed {
193696×
                current_heads
1937
            } else {
19389×
                local_current
1939
            },
1940105×
            changed,
1941105×
            checked_out,
1942105×
            others,
1943105×
            skipped,
1944
        })
1945109×
    }
1946
1947
    /// How many changes the working copy's bookmark has that its base
1948
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1949
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1950
    /// the bookmark or holds changes the bookmark lacks. History is read
1951
    /// only when the base and the bookmark's heads differ (oxygen#89).
19527×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
19537×
        let (_, wc) = self.working_copy()?;
19547×
        let mut base = wc.deps.clone();
19557×
        base.sort();
19567×
        let mut heads = self.bookmark_heads()?;
19577×
        heads.sort();
19587×
        if base == heads || heads.is_empty() {
19596×
            return Ok(None);
19601×
        }
19611×
        let state = self.load_state_history(&heads)?;
19621×
        if !base.iter().all(|h| state.contains(h)) {
19630×
            return Ok(None);
19641×
        }
19651×
        let had = if base.is_empty() {
19660×
            0
1967
        } else {
19681×
            self.load_state_history(&base)?.len()
1969
        };
19701×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
19717×
    }
1972
1973
    /// Bring the working copy to `heads`, the state of its bookmark
1974
    /// `bookmark`, when nothing would be lost: its base is part of that
1975
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1976
    /// with uncommitted work, the work comes along when the new changes
1977
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1978
    /// it followed only from exactly the bookmark's old heads, so a working
1979
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1980
    /// or a pull from another workspace) never caught up, and nothing said
1981
    /// so (oxygen#74, #89). Returns whether it moved.
1982105×
    pub fn follow_bookmark(
1983105×
        &self,
1984105×
        heads: &[ChangeHash],
1985105×
        bookmark: &str,
1986105×
        command: &str,
1987105×
    ) -> Result<bool> {
1988105×
        let snap = self.snapshot(command)?;
1989105×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1990105×
        let mut base = snap.base.maximal(&snap.wc.deps);
1991105×
        base.sort();
1992105×
        let mut target = heads.to_vec();
1993105×
        target.sort();
1994105×
        if base == target {
19958×
            return Ok(false);
199697×
        }
199797×
        let state = self.load_state_history(heads)?;
1998180×
        if !base.iter().all(|h| state.contains(h)) {
1999
            // The working copy holds changes the bookmark lacks: not ours to move.
20000×
            return Ok(false);
200197×
        }
200297×
        if clean {
200397×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
200497×
            Ok(true)
2005
        } else {
20060×
            Ok(self
20070×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
20080×
                .is_ok())
2009
        }
2010105×
    }
2011
2012
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2013
    /// changes and attesting the reference when a key is available.
2014
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2015
    /// state, attested when we have an identity. The local bookmark, if
2016
    /// any, is kept; only the remote-tracking entry goes.
20175×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
20185×
        let remote = self.open_named_remote(remote_name)?;
20195×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
20205×
        let resp = remote.refs()?;
20217×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
20221×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2023
        };
20244×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
20250×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
20264×
        }
20274×
        let attestation = match self.secret_key()? {
20282×
            Some(_) => Some(self.sign_attest(&Attest {
20292×
                repo: self.id()?,
20302×
                hlc: Hlc::now(),
20312×
                body: AttestBody::Ref {
20322×
                    name: bookmark.to_string(),
20332×
                    old_state: r.state,
20342×
                    new_state: ObjectRef::ZERO,
20352×
                    serial: r.last_serial.unwrap_or(0) + 1,
20362×
                },
20370×
            })?),
20382×
            None => None,
2039
        };
20404×
        let results = remote.push(
20414×
            Bundle::default(),
20424×
            vec![RefUpdate {
20434×
                name: bookmark.to_string(),
20444×
                old_state: r.state,
20454×
                new_state: ObjectRef::ZERO,
20464×
                force: true,
20474×
                attestation,
20484×
            }],
20494×
            None,
20504×
            vec![],
20510×
        )?;
20524×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
20532×
            let (op_ref, op) = self.head_op()?;
20542×
            let mut view = op.view.clone();
20552×
            if let Some(m) = view.remotes.get_mut(remote_name) {
20562×
                m.remove(bookmark);
20572×
            }
20582×
            self.record_op(
20592×
                &[op_ref],
20602×
                &format!("oxy push {remote_name} --delete {bookmark}"),
20612×
                view,
20620×
            )?;
20632×
        }
20644×
        Ok(results)
20655×
    }
2066
2067
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2068
    /// repository's config (its URL, token, CA and store settings), its
2069
    /// tracking bookmarks in the view, and a store remote's mirror under
2070
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
20713×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
20723×
        if !self.config.remotes.contains_key(name) {
20731×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
20742×
        }
20752×
        let prefix = format!("remote.{name}.");
20762×
        let keys: Vec<String> = self
20772×
            .config
20782×
            .repo_layer()
20792×
            .keys()
20804×
            .filter(|k| k.starts_with(&prefix))
20812×
            .cloned()
20822×
            .collect();
20833×
        for k in keys {
20843×
            self.config.set(&k, "")?;
2085
        }
20862×
        self.config.remotes.remove(name);
20872×
        self.save_config()?;
20882×
        let (op_ref, op) = self.head_op()?;
20892×
        if op.view.remotes.contains_key(name) {
20901×
            let mut view = op.view.clone();
20911×
            view.remotes.remove(name);
20921×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
20931×
        }
20942×
        let mirror = self.oxy.join("remotes").join(name);
20952×
        if mirror.is_dir() {
20960×
            fs::remove_dir_all(&mirror)?;
20972×
        }
20982×
        Ok(())
20993×
    }
2100
2101
    /// `changes`, in dependency order, cut into batches of about
2102
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2103
    /// There is always one, perhaps empty.
2104299×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2105299×
        let blob_len = |r: &ObjectRef| -> u64 {
210629×
            self.store
210729×
                .get_typed(r, ObjectType::Blob)
210829×
                .ok()
210929×
                .and_then(|b| Blob::decode(&b).ok())
211029×
                .map_or(0, |b| b.length)
211129×
        };
2112299×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2113404×
        for h in changes {
2114404×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2115404×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2116404×
            let mut weight = raw.len() as u64;
2117509×
            for t in &texts {
2118509×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
211926×
                    weight += blob_len(r);
2120483×
                }
2121
            }
2122659×
            for e in &c.edits {
21233×
                if let Edit::Replace { new: Some(b), .. } = e {
21243×
                    weight += blob_len(b);
2125656×
                }
2126
            }
2127404×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
21285×
                out.push(std::mem::take(&mut batch));
21295×
                bytes = 0;
2130399×
            }
2131404×
            batch.push(*h);
2132404×
            bytes += weight;
2133
        }
2134299×
        out.push(batch);
2135299×
        Ok(out)
2136299×
    }
2137
2138360×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2139360×
        let bookmark = self.config.bookmark.clone();
2140360×
        self.push_bookmark(remote_name, &bookmark, force)
2141360×
    }
2142
2143
    /// `push` for a named bookmark (`oxy push -b NAME`).
2144373×
    pub fn push_bookmark(
2145373×
        &self,
2146373×
        remote_name: &str,
2147373×
        bookmark: &str,
2148373×
        force: bool,
2149373×
    ) -> Result<Vec<RefResult>> {
2150373×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2151373×
    }
2152
2153
    /// `push_bookmark`, saying how a long push is going: one line per
2154
    /// batch sent (oxygen#95).
2155381×
    pub fn push_bookmark_with(
2156381×
        &self,
2157381×
        remote_name: &str,
2158381×
        bookmark: &str,
2159381×
        force: bool,
2160381×
        progress: crate::store::Progress,
2161381×
    ) -> Result<Vec<RefResult>> {
2162381×
        let (op_ref, op) = self.head_op()?;
2163381×
        if !op.view.bookmarks.contains_key(bookmark) {
21640×
            return fail(format!("no bookmark {bookmark}"));
2165381×
        }
2166381×
        let bookmark = bookmark.to_string();
2167381×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2168
        // pre-push hook: may veto before the remote is contacted.
2169381×
        self.run_hook(
2170381×
            "pre-push",
2171381×
            &format!(
2172
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2173381×
                json_str(remote_name),
2174381×
                json_str(&bookmark),
2175765×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2176
            ),
21771×
        )?;
2178380×
        let remote = self.open_named_remote(remote_name)?;
2179380×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2180377×
        let resp = remote.refs()?;
2181377×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2182377×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2183377×
        let policy_to_send = match (&local_policy, &resp.policy) {
218433×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
218512×
            (Some(l), None) => Some(l.clone()),
218618×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
21871×
                return fail(format!(
2188
                    "{remote_name} has a newer policy (serial {}); fetch first",
2189
                    r.policy.serial
2190
                ));
2191
            }
2192349×
            _ => None,
2193
        };
2194376×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2195376×
        if remote_has_policy && self.secret_key()?.is_none() {
21961×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2197375×
        }
2198375×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2199375×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2200375×
            .tag_refs()?
2201375×
            .into_iter()
2202375×
            .filter(|t| !remote_tags.contains(&t.name))
2203375×
            .collect();
2204375×
        let refs = resp.refs;
2205375×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2206375×
        let (remote_state, remote_heads, last_serial) =
2207376×
            match refs.iter().find(|r| r.name == bookmark) {
2208353×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
220922×
                None => (empty, vec![], None),
2210
            };
2211375×
        let new_state = self
2212375×
            .store
2213375×
            .put_state(&StateObject::new(local_heads.clone()))?;
2214
        // A push that carries a policy re-attests the bookmark even when its
2215
        // state is unchanged, so the current attestation is always by a key
2216
        // the current policy authorizes (a revoked key's attestation would
2217
        // otherwise be refused by every later fetch).
2218375×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
22198×
            return Ok(vec![RefResult {
22208×
                name: bookmark,
22218×
                ok: true,
22228×
                reason: "already up to date".into(),
22238×
            }]);
2224367×
        }
2225405×
        for h in &remote_heads {
2226405×
            if !self.store.has(h) {
222767×
                return fail(format!(
2228
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
222967×
                    h.short(12)
2230
                ));
2231338×
            }
2232
        }
2233300×
        if !force {
2234300×
            let closure = self.closure_in_store(&local_heads)?;
2235307×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
22360×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2237300×
            }
22380×
        }
2239300×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2240300×
        let key = self.secret_key()?.map(|(k, _)| k);
2241300×
        if let Some(key) = key {
2242
            // Seal this author's changes that carry no valid authenticator,
2243
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2244
            // are stored, so each batch's bundle carries those it needs.
224597×
            let mut unsigned = Vec::new();
224697×
            for h in &to_send {
224787×
                let c = self.store.get_change_meta(h)?;
224887×
                if self.seals_for_author(&c.author, &key)
224982×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
225048×
                {
225148×
                    unsigned.push(*h);
225248×
                }
2253
            }
225497×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
225545×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2256
            }
2257203×
        }
2258
        // A long history goes in batches, in dependency order, so neither
2259
        // side holds it whole and no request passes the remote's limit:
2260
        // all but the last carry objects alone; the last moves the bookmark
2261
        // (oxygen#95).
2262299×
        let batches = self.push_batches(&to_send)?;
2263299×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2264299×
        for (i, batch) in earlier.iter().enumerate() {
22655×
            progress(&format!(
22665×
                "part {} of {}: {} changes",
22675×
                i + 1,
22685×
                batches.len(),
22695×
                batch.len()
22705×
            ));
22715×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
22725×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
22735×
                Some(r) if r.ok => {}
22740×
                Some(r) => {
22750×
                    return fail(format!(
2276
                        "{remote_name} refused part {} of the push: {}",
22770×
                        i + 1,
2278
                        r.reason
2279
                    ))
2280
                }
2281
                None => {
22820×
                    return fail(format!(
2283
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2284
                    ))
2285
                }
2286
            }
2287
        }
2288299×
        if batches.len() > 1 {
22891×
            progress(&format!(
22901×
                "part {} of {}: {} changes",
22911×
                batches.len(),
22921×
                batches.len(),
22931×
                last.len()
22941×
            ));
2295298×
        }
2296299×
        let mut bundle = self.bundle_for(last)?;
2297299×
        bundle.objects.push((
2298299×
            ObjectType::State,
2299299×
            StateObject::new(local_heads.clone()).encode(),
2300299×
        ));
2301299×
        let attestation = match key {
230296×
            Some(_) => Some(self.sign_attest(&Attest {
230396×
                repo: self.id()?,
230496×
                hlc: Hlc::now(),
230596×
                body: AttestBody::Ref {
230696×
                    name: bookmark.clone(),
230796×
                    old_state: remote_state,
230896×
                    new_state,
230996×
                    serial: next_serial(last_serial),
231096×
                },
23111×
            })?),
2312203×
            None => None,
2313
        };
2314
        // Whoever signed the move, and whom a delegate acts for, travel with
2315
        // it: a receiver that has never seen a change by this delegate could
2316
        // not otherwise check its signature (oxygenhub#129).
2317298×
        if attestation.is_some() {
2318190×
            for k in [self.signing_key(), self.config.author_key]
231995×
                .into_iter()
232095×
                .flatten()
2321
            {
2322190×
                if let Ok(id) = self.identity(&k) {
2323190×
                    let body = id.encode();
2324190×
                    if !bundle
2325190×
                        .objects
2326190×
                        .iter()
2327225×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
232822×
                    {
232922×
                        bundle.objects.push((ObjectType::Identity, body));
2330168×
                    }
23310×
                }
2332
            }
2333
            // A short-lived signing key's certificate goes with it (§14.7).
233495×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
233595×
            self.attach_certificates_for(&mut bundle, &signers)?;
2336203×
        }
2337298×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
233895×
            AttestBody::Ref { serial, .. } => Some(serial),
23390×
            _ => None,
234095×
        });
2341298×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2342
        // Tag states must be present on the remote: bundle their changes too.
2343298×
        for t in &tags_to_send {
23446×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
23456×
            let extra: Vec<ChangeHash> =
23466×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
23476×
            if !extra.is_empty() {
23480×
                let more = self.bundle_for(&extra)?;
23490×
                bundle.changes.extend(more.changes);
23500×
                bundle.hashes.extend(more.hashes);
23510×
                bundle.attests.extend(more.attests);
23520×
                bundle.objects.extend(more.objects);
23536×
            }
23546×
            bundle.objects.push((
23556×
                ObjectType::State,
23566×
                StateObject::new(t.heads.clone()).encode(),
23576×
            ));
2358
        }
2359298×
        if let Some(l) = &policy_to_send {
236027×
            let remote_serial = resp_policy_serial;
236127×
            bundle.policies = self
236227×
                .policy_history()?
236327×
                .into_iter()
236456×
                .filter(|sp| {
236556×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
236629×
                        && sp.policy.serial < l.policy.serial
236756×
                })
236827×
                .collect();
2369271×
        }
2370298×
        let results = remote.push(
2371298×
            bundle,
2372298×
            vec![RefUpdate {
2373298×
                name: bookmark.clone(),
2374298×
                old_state: remote_state,
2375298×
                new_state,
2376298×
                force,
2377298×
                attestation,
2378298×
            }],
2379298×
            policy_to_send,
2380298×
            tags_to_send,
23817×
        )?;
238227×
        if let (Some(serial), true) = (
2383291×
            sent_serial,
2384297×
            results.iter().any(|r| r.ok && r.name == "policy"),
2385
        ) {
238627×
            self.record_policy_serial(remote_name, serial)?;
2387264×
        }
2388318×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2389267×
            let mut view = op.view.clone();
2390267×
            view.remotes
2391267×
                .entry(remote_name.to_string())
2392267×
                .or_default()
2393267×
                .insert(bookmark.clone(), new_state);
2394267×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2395264×
            if let Some(s) = serial {
239674×
                self.record_serial(remote_name, &bookmark, s)?;
2397190×
            }
239824×
        }
2399286×
        Ok(results)
2400381×
    }
2401
2402
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2403
    /// bookmark set to the remote's, working copy checked out.
2404243×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2405243×
        Self::clone_with(url, dest, None, &[])
2406243×
    }
2407
2408
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2409
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2410
    /// unless a size is given, so out-of-scope binaries are never fetched).
2411246×
    pub fn clone_with(
2412246×
        url: &str,
2413246×
        dest: &Path,
2414246×
        max_blob: Option<u64>,
2415246×
        sparse: &[String],
2416246×
    ) -> Result<Repo> {
2417246×
        Self::clone_full(url, dest, max_blob, sparse, None)
2418246×
    }
2419
2420
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2421
    /// changes within `depth` steps of them; the rest is the boundary.
24221×
    pub fn clone_shallow(
24231×
        url: &str,
24241×
        dest: &Path,
24251×
        depth: u32,
24261×
        max_blob: Option<u64>,
24271×
        sparse: &[String],
24281×
    ) -> Result<Repo> {
24291×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
24301×
    }
2431
2432247×
    fn clone_full(
2433247×
        url: &str,
2434247×
        dest: &Path,
2435247×
        max_blob: Option<u64>,
2436247×
        sparse: &[String],
2437247×
        depth: Option<u32>,
2438247×
    ) -> Result<Repo> {
2439247×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2440247×
    }
2441
2442
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2443
    /// `depth`), also returning the bookmarks the fetch left out because
2444
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2445
    /// for the caller to warn about. The bookmark checked out is never one
2446
    /// of them: that fails the clone.
2447253×
    pub fn clone_reporting(
2448253×
        url: &str,
2449253×
        dest: &Path,
2450253×
        max_blob: Option<u64>,
2451253×
        sparse: &[String],
2452253×
        depth: Option<u32>,
2453253×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2454253×
        let options = crate::credentials::Credentials::user().options_for(url);
2455253×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2456253×
    }
2457
2458
    /// Clone a subrepo with the credentials the parent would use for its
2459
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2460
    /// subrepo: it finds the same ones again through its parent.
246110×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
246210×
        let options = self.credentials_for(url);
246310×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
246410×
    }
2465
2466
    /// The name of a remote of this repository on the same hub (scheme,
2467
    /// host and port) as `url`.
246823×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
246927×
        let origin = |u: &str| -> Option<String> {
247027×
            let (scheme, rest) = u.split_once("://")?;
24718×
            if !matches!(scheme, "http" | "https") {
24720×
                return None;
24738×
            }
24748×
            let host = rest.split('/').next()?;
24758×
            Some(format!(
24768×
                "{}://{}",
24778×
                scheme.to_ascii_lowercase(),
24788×
                host.to_ascii_lowercase()
24798×
            ))
248027×
        };
248123×
        let want = origin(url)?;
24824×
        self.config
24834×
            .remotes
24844×
            .iter()
24854×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
24864×
            .map(|(name, _)| name.clone())
248723×
    }
2488
2489
    /// The token and CA to reach `url` with: those of a remote of this
2490
    /// repository on the same hub (scheme, host and port), else the
2491
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2492
    /// and enclosing checkouts', as a clone would use them.
249323×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
249423×
        match self.remote_on_same_hub(url) {
24951×
            Some(name) => RemoteOptions {
24961×
                repo_id: None,
24971×
                cache_dir: None,
24981×
                ..self.remote_options(&name)
24991×
            },
2500
            None => {
250122×
                let mut options = RemoteOptions::default();
250222×
                self.fill_credentials(url, &mut options);
250322×
                options
2504
            }
2505
        }
250623×
    }
2507
2508263×
    fn clone_using(
2509263×
        url: &str,
2510263×
        dest: &Path,
2511263×
        max_blob: Option<u64>,
2512263×
        sparse: &[String],
2513263×
        depth: Option<u32>,
2514263×
        options: &RemoteOptions,
2515263×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2516263×
        let remote = open_remote(url, options)?;
2517263×
        let id = remote.repo_id()?;
2518259×
        if id == crate::protocol::UNBOUND_ID {
25192×
            return fail(format!(
2520
                "{url} is empty and unbound: push a repository to it first"
2521
            ));
2522257×
        }
2523257×
        let mut repo = Repo::init_with_id(dest, id)?;
2524257×
        repo.config
2525257×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2526257×
        if let Some(m) = max_blob {
25272×
            repo.config.set("filter.max-blob", &m.to_string())?;
2528255×
        } else if !sparse.is_empty() {
25291×
            repo.config.set("filter.max-blob", "0")?;
2530254×
        }
2531257×
        if !sparse.is_empty() {
25321×
            repo.config.set("filter.paths", &sparse.join(","))?;
2533256×
        }
2534257×
        repo.save_config()?;
2535257×
        let skipped = if let Some(depth) = depth {
25361×
            repo.fetch_shallow("origin", depth)?;
25371×
            Vec::new()
2538
        } else {
2539256×
            repo.fetch("origin")?.skipped
2540
        };
2541255×
        let (op_ref, op) = repo.head_op()?;
2542
        // The remote's default bookmark, else ours (main), else its only
2543
        // one; a bookmark the fetch skipped counts, so the clone fails
2544
        // rather than check out another (oxygenhub#266).
2545255×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2546255×
        for (name, _) in &skipped {
25472×
            theirs.insert(name.clone(), ObjectRef::ZERO);
25482×
        }
2549
        // Asked of the remote as now configured, so a store-backed one
2550
        // answers from the mirror the fetch just filled.
2551255×
        let advertised = repo
2552255×
            .open_named_remote("origin")
2553255×
            .ok()
2554255×
            .and_then(|r| r.refs().ok())
2555255×
            .and_then(|r| r.default_bookmark);
2556255×
        let bookmark = advertised
2557255×
            .filter(|b| theirs.contains_key(b))
2558255×
            .or_else(|| {
25597×
                theirs
25607×
                    .contains_key(&repo.config.bookmark)
25617×
                    .then(|| repo.config.bookmark.clone())
25627×
            })
2563255×
            .or_else(|| {
25640×
                (theirs.len() == 1)
25650×
                    .then(|| theirs.keys().next().cloned())
25660×
                    .flatten()
25670×
            })
2568255×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2569255×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
25700×
            return fail(format!("cannot check out {bookmark}: {why}"));
2571255×
        }
2572255×
        let initial = repo.config.bookmark.clone();
2573255×
        if bookmark != repo.config.bookmark {
25741×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
25751×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
25761×
            repo.config.bookmark = bookmark.clone();
2577254×
        }
2578255×
        if let Some(state) = theirs.get(&bookmark).copied() {
2579255×
            let heads = repo.store.get_state(&state)?.heads;
2580255×
            let mut view = op.view.clone();
2581
            // The empty bookmark `init` made goes when another is checked out.
2582255×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
25831×
                view.bookmarks.remove(&initial);
2584254×
            }
2585255×
            view.bookmarks.insert(bookmark, state);
2586255×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2587255×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
25880×
        }
2589255×
        Ok((repo, skipped))
2590263×
    }
2591
}
2592
2593
/// The serial of a reference's next attestation: one more than the last the
2594
/// remote reports, or, for a bookmark the remote does not have, the clock in
2595
/// milliseconds, so a bookmark created again after a deletion goes past the
2596
/// deletion's serial the remote keeps.
259796×
fn next_serial(last: Option<u64>) -> u64 {
259896×
    match last {
259958×
        Some(l) => l + 1,
260038×
        None => Hlc::now().wall_ms.max(1),
2601
    }
260296×
}