OXYGENHUB

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

1901 of 2108 lines run, 311 of 406 functions · run #366 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::tags::TagCheck;
4
use super::*;
5
6
/// What a push did, for hosts (hub spec §6.12).
7
#[derive(Clone, Debug, Default)]
8
pub struct PushReport {
9
    pub results: Vec<RefResult>,
10
    /// Accepted reference updates, in request order.
11
    pub updated: Vec<RefUpdated>,
12
    /// Changes this push stored that were not already present.
13
    pub imported: Vec<ChangeHash>,
14
}
15
16
#[derive(Clone, Debug)]
17
pub struct RefUpdated {
18
    pub name: String,
19
    pub old_state: ObjectRef,
20
    pub new_state: ObjectRef,
21
    pub heads: Vec<ChangeHash>,
22
}
23
24
/// What a fetch brought in.
25
#[derive(Debug, Clone, PartialEq, Eq, Default)]
26
pub struct FetchReport {
27
    /// Bookmark name, its heads, and how many changes were new.
28
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
29
    /// Tags adopted from the remote.
30
    pub new_tags: usize,
31
    /// The remote has never presented a policy, so nothing was verified
32
    /// against one (spec §14.5: warn loudly).
33
    pub unverified: bool,
34
    /// What checking the host's transparency log found short of a fork
35
    /// (spec §14.8): attestations not logged yet, a log that could not be
36
    /// read. A fork fails the fetch instead.
37
    pub log_notes: Vec<String>,
38
    /// Bookmarks left as they were because their attestation could not be
39
    /// verified (its signer unknown here, or its signature bad), each with
40
    /// why (oxygenhub#266). The current bookmark is never skipped: its
41
    /// fetch fails instead.
42
    pub skipped: Vec<(String, String)>,
43
}
44
45
#[derive(Debug, Clone, PartialEq, Eq)]
46
pub struct PullReport {
47
    /// The current bookmark's heads after the pull.
48
    pub heads: Vec<ChangeHash>,
49
    /// Whether the current bookmark changed.
50
    pub changed: bool,
51
    pub checked_out: bool,
52
    /// Other bookmarks the pull moved: each local bookmark tracks the
53
    /// remote's of the same name.
54
    pub others: Vec<String>,
55
    /// What the fetch left as it was ([`FetchReport::skipped`]).
56
    pub skipped: Vec<(String, String)>,
57
}
58
59
/// The result a push of objects alone reports (a batch of a long history):
60
/// not a reference.
61
pub const OBJECTS_RESULT: &str = "objects";
62
63
impl Repo {
64
    // ------------------------------------------------------------ serving (spec §16)
65
661837×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
671837×
        self.oxy.join("attest").join(name_file(bookmark))
681837×
    }
69
70
    /// The latest reference attestation stored for a bookmark.
711423×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
721423×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
73334×
            Ok(h) => {
74334×
                let r = ObjectRef::from_hex(h.trim())
75334×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
76
                Ok(Some((
77334×
                    r,
78
                    SignedAttest {
79334×
                        attest: self.store.get_attest(&r)?,
80334×
                        sigs: self.store.signatures(&r)?,
81
                    },
82
                )))
83
            }
841089×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
850×
            Err(e) => Err(e.into()),
86
        }
871423×
    }
88
89107×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
90107×
        fs::create_dir_all(self.oxy.join("attest"))?;
91107×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
92107×
    }
93
941136×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
951136×
        let view = self.view()?;
961136×
        let mut out = Vec::new();
971189×
        for (name, state) in &view.bookmarks {
981189×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
991189×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
100220×
                AttestBody::Ref { serial, .. } => Some(serial),
1010×
                _ => None,
102220×
            });
1031189×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
1041189×
            let accepted = match &attestation {
105209×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
106980×
                None => None,
107
            };
1081189×
            out.push(RemoteRef {
1091189×
                name: name.clone(),
1101189×
                state: *state,
1111189×
                heads: self.store.get_state(state)?.heads,
1121189×
                attestation,
1131189×
                last_serial,
1141189×
                accepted,
1151189×
                logged: None,
1161189×
                integration: vec![],
117
            });
118
        }
1191136×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1201136×
        let history = self
1211136×
            .policy_history()?
1221136×
            .into_iter()
1231136×
            .filter(|sp| {
124211×
                policy
125211×
                    .as_ref()
126211×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
127211×
            })
1281136×
            .collect();
129
        Ok(RefsResponse {
1301136×
            refs: out,
1311136×
            policy,
1321136×
            tags: self.tag_refs()?,
1331136×
            history,
1341136×
            default_bookmark: Some(self.config.bookmark.clone()),
1351136×
            log: None,
1361136×
            witnesses: vec![],
137
        })
1381136×
    }
139
140
    /// Every change reachable from `heads` that is in the store.
1411545×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1421545×
        let mut seen = BTreeSet::new();
1431545×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1445329×
        while let Some(h) = stack.pop() {
1453784×
            if seen.contains(&h) || !self.store.has(&h) {
1461144×
                continue;
1472640×
            }
1482640×
            seen.insert(h);
1492640×
            stack.extend(self.store.get_change_meta(&h)?.deps);
150
        }
1511545×
        Ok(seen)
1521545×
    }
153
154
    /// The changes within `depth` dependency steps of `heads` (spec §17),
155
    /// nearest first; depth 1 is the heads themselves.
1563×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1573×
        let mut out = Vec::new();
1583×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1593×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1603×
        for _ in 0..depth.max(1) {
1618×
            let mut next = Vec::new();
16212×
            for h in layer {
16312×
                if !seen.insert(h) || !self.store.has(&h) {
1642×
                    continue;
16510×
                }
16610×
                let c = self.store.get_change(&h)?;
16710×
                next.extend(c.deps.iter().copied());
16810×
                out.push(h);
169
            }
1708×
            if next.is_empty() {
1711×
                break;
1727×
            }
1737×
            layer = next;
174
        }
1753×
        out.reverse();
1763×
        Ok(out)
1773×
    }
178
1792176×
    fn shallow_path(&self) -> PathBuf {
1802176×
        self.oxy.join("shallow")
1812176×
    }
182
183
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1842173×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1852173×
        fs::read_to_string(self.shallow_path())
1862173×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1872173×
            .unwrap_or_default()
1882173×
    }
189
190190×
    pub fn is_shallow(&self) -> bool {
191190×
        !self.boundary().is_empty()
192190×
    }
193
1943×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1953×
        if boundary.is_empty() {
1961×
            let _ = fs::remove_file(self.shallow_path());
1971×
            return Ok(());
1982×
        }
1992×
        let text: String = boundary
2002×
            .iter()
2012×
            .map(|h| format!("{}\n", h.to_hex()))
2022×
            .collect();
2032×
        write_atomic(&self.shallow_path(), text.as_bytes())
2043×
    }
205
206
    /// Recompute the boundary from what is stored: every dependency of a
207
    /// stored change that is not itself stored.
2083×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
2093×
        let mut boundary = self.boundary();
2103×
        boundary.retain(|h| !self.store.has(h));
21110×
        for h in imported {
21213×
            for d in self.store.get_change_meta(h)?.deps {
21313×
                if !self.store.has(&d) {
2142×
                    boundary.insert(d);
21511×
                }
216
            }
217
        }
2183×
        self.write_boundary(&boundary)
2193×
    }
220
221
    /// Fetch `depth` more levels of history below the shallow boundary.
2222×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2232×
        let boundary = self.boundary();
2242×
        if boundary.is_empty() {
2250×
            return Ok(0);
2262×
        }
2272×
        let remote = self.open_named_remote(remote_name)?;
2282×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2292×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2302×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2312×
        if self.config.max_blob.is_some() {
2320×
            self.register_missing_blobs(&imported, remote_name)?;
2332×
        }
2342×
        self.refresh_boundary(&imported)?;
2352×
        Ok(imported.len())
2362×
    }
237
238
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
239896×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
240896×
        let have = self.closure_in_store(have)?;
241
        // In a shallow repository the walk stops at the boundary, whose
242
        // changes the remote is assumed to hold.
243896×
        let boundary = self.boundary();
244896×
        let mut out = Vec::new();
245896×
        let mut done: BTreeSet<ChangeHash> = have.clone();
246896×
        done.extend(boundary.iter().copied());
247
        // Iterative post-order DFS.
2481406×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2493658×
        while let Some((h, expanded)) = stack.pop() {
2502762×
            if done.contains(&h) {
251486×
                continue;
2522276×
            }
2532276×
            if !self.store.has(&h) {
2540×
                return fail(format!("change {} is not in this repository", h.short(12)));
2552276×
            }
2562276×
            if expanded {
2571138×
                done.insert(h);
2581138×
                out.push(h);
2591138×
                continue;
2601138×
            }
2611138×
            stack.push((h, true));
2621138×
            for d in self.store.get_change_meta(&h)?.deps {
263792×
                if !done.contains(&d) {
264218×
                    stack.push((d, false));
265574×
                }
266
            }
267
        }
268896×
        Ok(out)
269896×
    }
270
271
    /// Bundle changes (in the given dependency order) with their signatures,
272
    /// seals, identities, blobs, chunks.
273341×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
274341×
        self.bundle_of(changes, None, false, false)
275341×
    }
276
277
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2784×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2794×
        let mut out = Vec::new();
2804×
        for r in refs {
2814×
            let (ty, body) = match self.store.get(r) {
2824×
                Ok(x) => x,
2830×
                Err(StoreError::NotFound(_)) => continue,
2840×
                Err(e) => return Err(e.into()),
285
            };
2864×
            if ty == ObjectType::Blob {
2875×
                for c in Blob::decode(&body)?.chunks {
2885×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2895×
                        out.push((cty, cb));
2905×
                    }
291
                }
2920×
            }
2934×
            out.push((ty, body));
294
        }
2954×
        Ok(out)
2964×
    }
297
298
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
299
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
300
    ///
301
    /// This is what a server answers a fetch with, so it also carries what
302
    /// verifies the attestations it serves beside it (see
303
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
30456×
    pub fn bundle_for_filtered(
30556×
        &self,
30656×
        changes: &[ChangeHash],
30756×
        max_blob: Option<u64>,
30856×
    ) -> Result<Bundle> {
30956×
        self.bundle_of(changes, max_blob, false, true)
31056×
    }
311
312
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
313
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
314
    /// with their text blobs and chunks among the objects, so neither side
315
    /// decodes or encodes their text.
316383×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
317383×
        self.bundle_of(changes, max_blob, true, true)
318383×
    }
319
320
    /// The keys that signed the attestations this repository serves with
321
    /// its references: each bookmark's latest and each tag's. A fetch
322
    /// bundle carries their identities and certificates (spec §16.2), so a
323
    /// client can check an attestation whose signer signed none of the
324
    /// changes it receives, a delegate or a short-lived key that only
325
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
326
    /// list per reference, computed once per operation head and kept
327
    /// (every bookmark move and tag is an operation): a client sends one
328
    /// fetch per bookmark, and on a bucket store each signature list is a
329
    /// LIST request, so recomputing per fetch cost metalgear2 (145
330
    /// bookmarks) 14 s a fetch.
331439×
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
332
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
333
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
334439×
        let key = (self.oxy.clone(), self.head_op()?.0);
335439×
        if let Some(keys) = SERVED
336439×
            .lock()
337439×
            .unwrap_or_else(|p| p.into_inner())
338439×
            .as_ref()
339439×
            .and_then(|m| m.get(&key))
340
        {
341142×
            return Ok(keys.clone());
342297×
        }
343297×
        let keys = self.attest_signers_now()?;
344297×
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
345297×
        let map = served.get_or_insert_with(Default::default);
346
        // One entry per repository: an older operation head is never asked
347
        // for again once a newer one is current.
3485959×
        map.retain(|(oxy, _), _| *oxy != key.0);
349297×
        if map.len() >= 1024 {
3500×
            map.clear();
351297×
        }
352297×
        map.insert(key, keys.clone());
353297×
        Ok(keys)
354439×
    }
355
356297×
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
357297×
        let view = self.view()?;
358297×
        let pointers = view
359297×
            .bookmarks
360297×
            .keys()
361307×
            .map(|b| self.ref_attest_path(b))
362297×
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
363297×
        let mut keys = BTreeSet::new();
364326×
        for p in pointers {
365326×
            let Ok(text) = fs::read_to_string(&p) else {
366268×
                continue;
367
            };
36858×
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
3690×
                continue;
370
            };
37158×
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
372
        }
373297×
        Ok(keys)
374297×
    }
375
376
    /// `serving`: a fetch's answer, which carries the identities and
377
    /// certificates of [`Repo::served_attest_signers`] too.
378780×
    fn bundle_of(
379780×
        &self,
380780×
        changes: &[ChangeHash],
381780×
        max_blob: Option<u64>,
382780×
        raw: bool,
383780×
        serving: bool,
384780×
    ) -> Result<Bundle> {
385780×
        let mut bundle = Bundle::default();
386780×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
387780×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3881307×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3891307×
            if !r.is_zero() && self.store.has(r) {
390375×
                objects.insert(*r);
391932×
            }
3921307×
        };
3931055×
        for h in changes {
394
            // Raw: the stored bytes, and a skeleton for the rest.
3951055×
            let (c, encoded) = if raw {
396576×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
397576×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3985074×
                for t in texts {
3995074×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
4003×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
4013×
                        objects.insert(r);
4023×
                        objects.extend(blob.chunks);
4035071×
                    }
404
                }
405576×
                (skel, Some(bytes))
406
            } else {
407479×
                (self.store.get_change(h)?, None)
408
            };
4091055×
            let sigs = self.store.signatures(h)?;
4101055×
            add_object(&c.author, &mut objects);
4111055×
            for s in &sigs {
41237×
                add_object(&s.key, &mut objects);
41337×
            }
4146177×
            for e in &c.edits {
4156177×
                if let Edit::Replace { old, new, .. } = e {
41614×
                    for b in [old, new].into_iter().flatten() {
41714×
                        if self.store.has(b) {
41814×
                            if let Ok(blob) =
41914×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
420
                            {
42114×
                                if max_blob.is_some_and(|m| blob.length > m) {
4224×
                                    continue;
42310×
                                }
42410×
                                objects.insert(*b);
42510×
                                objects.extend(blob.chunks.iter().copied());
4260×
                            }
4270×
                        }
428
                    }
4296165×
                }
430
            }
4311055×
            for s in self.store.seals_for(h)? {
432107×
                seals.insert(s);
433107×
            }
4341055×
            match encoded {
435576×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
436479×
                None => {
437479×
                    bundle.changes.push((c, sigs));
438479×
                    bundle.hashes.push(*h);
439479×
                }
440
            }
441
        }
442780×
        for r in seals {
443102×
            let attest = self.store.get_attest(&r)?;
444102×
            let sigs = self.store.signatures(&r)?;
445102×
            for s in &sigs {
446102×
                add_object(&s.key, &mut objects);
447102×
            }
448102×
            bundle.attests.push(SignedAttest { attest, sigs });
449
        }
450780×
        let signers: Vec<KeyId> = if serving {
451439×
            let signers = self.served_attest_signers()?;
452439×
            for k in &signers {
453113×
                add_object(k, &mut objects);
454113×
            }
455439×
            signers.into_iter().collect()
456
        } else {
457341×
            Vec::new()
458
        };
459780×
        for r in objects {
460221×
            let (ty, body) = self.store.get(&r)?;
461221×
            bundle.objects.push((ty, body));
462
        }
463780×
        self.attach_certificates_for(&mut bundle, &signers)?;
464780×
        Ok(bundle)
465780×
    }
466
467
    /// Add the certificates of short-lived keys that signed what `bundle`
468
    /// carries, and their issuers' identities, so a receiver can tell who
469
    /// they stand for (spec §14.7). `also` names more signers (a reference
470
    /// attestation sent beside the bundle).
471901×
    pub(crate) fn attach_certificates_for(
472901×
        &self,
473901×
        bundle: &mut Bundle,
474901×
        also: &[KeyId],
475901×
    ) -> Result<()> {
476901×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
477901×
        keys.extend(
478901×
            bundle
479901×
                .changes
480901×
                .iter()
481901×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
482
        );
483901×
        keys.extend(
484901×
            bundle
485901×
                .raw_changes
486901×
                .iter()
487901×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
488
        );
489901×
        keys.extend(
490901×
            bundle
491901×
                .attests
492901×
                .iter()
493901×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
494
        );
495901×
        for k in keys {
496340×
            let Some(r) = self.store.certificate_of(&k)? else {
497291×
                continue;
498
            };
49949×
            let cert = self.store.get_certificate(&r)?;
50049×
            if bundle
50149×
                .certificates
50249×
                .iter()
50349×
                .any(|c| c.cert.hash() == cert.cert.hash())
504
            {
50512×
                continue;
50637×
            }
507
            // An agent's certificate brings its grant's signer too, so the
508
            // receiver can check the grant (oxygen#134).
50937×
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
51081×
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
51181×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
51280×
                    if !bundle
51380×
                        .objects
51480×
                        .iter()
515145×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
51635×
                    {
51735×
                        bundle.objects.push((ObjectType::Identity, body));
51845×
                    }
5191×
                }
520
            }
52137×
            bundle.certificates.push(cert);
522
        }
523901×
        Ok(())
524901×
    }
525
526
    /// Keep the certificates a bundle brings once each verifies with the
527
    /// identity of the issuer it names; one that does not refuses the bundle.
528821×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
529821×
        for c in certs {
53036×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
5310×
                RepoError::Msg(format!(
5320×
                    "a certificate names issuer {}, whose identity did not come with it",
5330×
                    c.cert.issuer.short(12)
5340×
                ))
5350×
            })?;
53636×
            c.verify(&issuer)
53736×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
53836×
            self.store.put_identity(&c.cert.key)?;
53936×
            self.store.put_certificate(c)?;
540
        }
541821×
        Ok(())
542821×
    }
543
544
    /// A signer authorized for `reference` by what an issuer certified it
545
    /// as (spec §14.7): a short-lived key with a kept certificate that
546
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
547
    /// signer did not choose) and names a subject the policy grants.
54857×
    pub(crate) fn certified_authorized(
54957×
        &self,
55057×
        p: &crate::policy::Policy,
55157×
        signer: &KeyId,
55257×
        reference: &str,
55357×
        scope: Scope,
55457×
        at_ms: u64,
55557×
    ) -> bool {
55657×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
5575×
            return false;
558
        };
55952×
        let Ok(c) = self.store.get_certificate(&r) else {
5600×
            return false;
561
        };
56252×
        let Some(issuer) = p
56352×
            .identity(&c.cert.issuer)
56452×
            .cloned()
56552×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
566
        else {
5670×
            return false;
568
        };
56952×
        c.verify(&issuer).is_ok()
57052×
            && c.cert.key_id() == *signer
57152×
            && c.cert.covers(scope, at_ms)
57242×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
57357×
    }
574
575
    /// Store a bundle's contents. With `strict`, every change must
576
    /// authenticate (signature or seal by its author or a delegate).
577818×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
578818×
        self.import_bundle_inner(bundle, strict, false)
579818×
    }
580
581
    /// Like `import_bundle`, accepting changes whose dependencies are absent
582
    /// (they join the shallow boundary).
5833×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
5843×
        self.import_bundle_inner(bundle, strict, true)
5853×
    }
586
587821×
    fn import_bundle_inner(
588821×
        &self,
589821×
        bundle: &Bundle,
590821×
        strict: bool,
591821×
        shallow: bool,
592821×
    ) -> Result<Vec<ChangeHash>> {
593821×
        let batch = self.store.begin_batch()?;
594821×
        let result = self.import_bundle_batched(bundle, strict, shallow);
595821×
        batch.finish()?;
596819×
        result
597821×
    }
598
599821×
    fn import_bundle_batched(
600821×
        &self,
601821×
        bundle: &Bundle,
602821×
        strict: bool,
603821×
        shallow: bool,
604821×
    ) -> Result<Vec<ChangeHash>> {
605821×
        for (ty, _) in &bundle.objects {
6060×
            if !matches!(
607687×
                ty,
608
                ObjectType::Chunk
609
                    | ObjectType::Blob
610
                    | ObjectType::Identity
611
                    | ObjectType::State
612
                    | ObjectType::Checkpoint
613
            ) {
6140×
                return fail(format!("bundle may not carry {} objects", ty.name()));
615687×
            }
616
        }
617
        // All at once: in a large batch they are compressed on every core.
618821×
        let objects: Vec<(ObjectType, &[u8])> = bundle
619821×
            .objects
620821×
            .iter()
621821×
            .map(|(ty, body)| (*ty, body.as_slice()))
622821×
            .collect();
623821×
        self.store.put_many(&objects)?;
624821×
        self.adopt_certificates(&bundle.certificates)?;
625821×
        for sa in &bundle.attests {
626105×
            let r = self.store.put_attest(&sa.attest)?;
627105×
            for sig in &sa.sigs {
628105×
                self.store.put_signature(&r, sig)?;
629
            }
630105×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
631110×
                for h in hashes {
632110×
                    self.store.index_seal(h, &r)?;
633
                }
6340×
            }
635
        }
636
        // Each change's hash: from the bundle when its maker knew it, else
637
        // worked out once (for a change adding a whole tree, hashing is
638
        // chunking all its text).
639821×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
640812×
            bundle.hashes.clone()
641
        } else {
6429×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
643
        };
644821×
        let raw_hashes: Vec<ChangeHash> = bundle
645821×
            .raw_changes
646821×
            .iter()
647821×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
648821×
            .collect();
649821×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
650821×
        let boundary = self.boundary();
651821×
        let mut imported = Vec::new();
652
        // Changes as stored: checked, then stored as they are, their text
653
        // blobs having come with the objects.
654821×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
655577×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
656577×
            for d in &skel.deps {
657436×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
658
                {
6590×
                    return fail(format!(
660
                        "change {} depends on {}, which is neither stored nor in the bundle",
6610×
                        h.short(12),
6620×
                        d.short(12)
663
                    ));
664436×
                }
665
            }
6665075×
            for t in texts {
6675075×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
6684×
                    if !self.store.has(&r) {
6691×
                        return fail(format!(
670
                            "change {} came without its text blob {}",
6711×
                            h.short(12),
6721×
                            r.short(12)
673
                        ));
6743×
                    }
6755071×
                }
676
            }
677576×
            self.store.put(ObjectType::Change, bytes)?;
678576×
            for sig in sigs {
67913×
                self.store.put_signature(&h, sig)?;
680
            }
681576×
            imported.push(h);
682
        }
683820×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
684506×
            for d in &c.deps {
685310×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
686
                {
6873×
                    return fail(format!(
688
                        "change {} depends on {}, which is neither stored nor in the bundle",
6893×
                        h.short(12),
6903×
                        d.short(12)
691
                    ));
692307×
                }
693
            }
694503×
            let stored = self.store.put_change(c)?;
695503×
            if stored != h {
6960×
                return fail(format!(
697
                    "change {} is not the change the bundle names",
6980×
                    h.short(12)
699
                ));
700503×
            }
701503×
            for sig in sigs {
70233×
                self.store.put_signature(&h, sig)?;
703
            }
704503×
            imported.push(h);
705
        }
706817×
        if strict {
70762×
            for h in &imported {
70838×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
7094×
                    return fail(format!(
710
                        "change {} is not authenticated by its author",
7114×
                        h.short(12)
712
                    ));
71334×
                }
714
            }
715755×
        }
716813×
        Ok(imported)
717821×
    }
718
719
    /// Verify a reference attestation against an update it claims to describe.
720
    /// `allow_equal` lets a client re-read the attestation it already has; a
721
    /// server receiving a push requires a strictly greater serial.
722
    /// A reference attestation signed by a delegate of an identity the
723
    /// rule lists is authorized as that identity (spec §14.5): the identity
724
    /// named the delegate with the `refs` scope, still in force at `at_ms`
725
    /// (the attestation's wall time), and the policy names the identity.
726
    /// Revoked keys authorize nothing either way.
72771×
    pub(crate) fn delegate_authorized(
72871×
        &self,
72971×
        p: &crate::policy::Policy,
73071×
        signer: &KeyId,
73171×
        reference: &str,
73271×
        at_ms: u64,
73371×
    ) -> bool {
73471×
        if p.is_revoked(signer) {
7351×
            return false;
73670×
        }
73770×
        let Some(rule) = p.rule_for(reference) else {
7380×
            return false;
739
        };
74071×
        rule.keys.iter().any(|k| {
74171×
            !p.is_revoked(k)
74271×
                && p.identity(k)
74371×
                    .cloned()
74471×
                    .or_else(|| self.store.get_identity(k).ok())
74571×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
74671×
        })
74771×
    }
748
749
    /// A lasting attestation (a tag) signed by a key the policy has since
750
    /// rotated away from (spec §14.2) is authorized as the key that
751
    /// succeeded it: a key the rule lists reaches the signer through
752
    /// `previous` links, and the attestation is dated (`at_ms`) before the
753
    /// signer's successor was made, so a superseded key makes nothing new.
754
    /// Revoked keys authorize nothing.
75526×
    pub(crate) fn predecessor_authorized(
75626×
        &self,
75726×
        p: &crate::policy::Policy,
75826×
        signer: &KeyId,
75926×
        reference: &str,
76026×
        at_ms: u64,
76126×
    ) -> bool {
76226×
        if p.is_revoked(signer) {
7630×
            return false;
76426×
        }
76526×
        let Some(rule) = p.rule_for(reference) else {
7660×
            return false;
767
        };
76827×
        let identity = |k: &KeyId| {
76927×
            p.identity(k)
77027×
                .cloned()
77127×
                .or_else(|| self.store.get_identity(k).ok())
77227×
        };
77326×
        rule.keys.iter().any(|k| {
77426×
            if p.is_revoked(k) {
7750×
                return false;
77626×
            }
77726×
            let mut cur = identity(k);
77826×
            for _ in 0..32 {
77927×
                let Some(id) = cur else {
7800×
                    return false;
781
                };
7821×
                match id.previous {
7836×
                    Some(prev) if prev == *signer => return at_ms < id.created,
7841×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
78521×
                    _ => return false,
786
                }
787
            }
7880×
            false
78926×
        })
79026×
    }
791
792104×
    fn check_ref_attest(
793104×
        &self,
794104×
        sa: &SignedAttest,
795104×
        name: &str,
796104×
        old_state: &ObjectRef,
797104×
        new_state: &ObjectRef,
798104×
        last_serial: Option<u64>,
799104×
        allow_equal: bool,
800104×
    ) -> std::result::Result<u64, String> {
801102×
        let serial =
802104×
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
803102×
        self.verify_attest_signature(sa)?;
804102×
        Ok(serial)
805104×
    }
806
807
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
808
    /// attestation describes this update of this repository with a serial
809
    /// past the last seen.
810174×
    fn check_ref_attest_body(
811174×
        &self,
812174×
        sa: &SignedAttest,
813174×
        name: &str,
814174×
        old_state: &ObjectRef,
815174×
        new_state: &ObjectRef,
816174×
        last_serial: Option<u64>,
817174×
        allow_equal: bool,
818174×
    ) -> std::result::Result<u64, String> {
819
        let AttestBody::Ref {
820174×
            name: n,
821174×
            old_state: o,
822174×
            new_state: nw,
823174×
            serial,
824174×
        } = &sa.attest.body
825
        else {
8260×
            return Err("attestation is not a ref attestation".into());
827
        };
828174×
        if n != name || o != old_state || nw != new_state {
8291×
            return Err("attestation does not describe this update".into());
830173×
        }
831173×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
8320×
            return Err("attestation is for a different repository".into());
833173×
        }
834173×
        if let Some(last) = last_serial {
83591×
            if *serial < last || (*serial == last && !allow_equal) {
8361×
                return Err(format!(
8371×
                    "attestation serial {serial} is not greater than the last seen {last}"
8381×
                ));
83990×
            }
84082×
        }
841172×
        Ok(*serial)
842174×
    }
843
844
    /// An attestation's first signature verifies with its signer's
845
    /// identity, which must be stored here.
846172×
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
847172×
        let r = sa.attest.hash();
848172×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
849172×
        let id = self
850172×
            .store
851172×
            .get_identity(&sig.key)
852172×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
853166×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
854172×
    }
855
856
    /// Accept a push (spec §16.4). Without a trust policy every repository
857
    /// is unverified, so unsigned changes and unattested updates are accepted;
858
    /// attestations that are present must still be valid. With a policy,
859
    /// every change and update is checked against it. A newer policy in the
860
    /// push is applied first when it is signed by the current roots.
861312×
    pub fn receive_push(
862312×
        &self,
863312×
        bundle: Bundle,
864312×
        updates: Vec<RefUpdate>,
865312×
        policy: Option<SignedPolicy>,
866312×
        tags: Vec<crate::protocol::TagRef>,
867312×
    ) -> Result<Vec<RefResult>> {
868312×
        Ok(self
869312×
            .receive_push_report(bundle, updates, policy, tags)?
870
            .results)
871312×
    }
872
873
    /// `receive_push` with what a host wants to log: each accepted
874
    /// reference's old and new state and heads, and the changes this push
875
    /// stored (hub spec §6.12).
876358×
    pub fn receive_push_report(
877358×
        &self,
878358×
        bundle: Bundle,
879358×
        updates: Vec<RefUpdate>,
880358×
        policy: Option<SignedPolicy>,
881358×
        tags: Vec<crate::protocol::TagRef>,
882358×
    ) -> Result<PushReport> {
883
        // Updates are checked against the head as it is now, not as this
884
        // handle first read it (oxygenhub#249): another push may have
885
        // landed since.
886358×
        self.refresh()?;
887358×
        let mut report = PushReport::default();
888358×
        let results = &mut report.results;
889358×
        if let Some(sp) = policy {
89035×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
89133×
                Ok(()) => {
89233×
                    results.push(RefResult {
89333×
                        name: "policy".into(),
89433×
                        ok: true,
89533×
                        reason: format!("serial {}", sp.policy.serial),
89633×
                    });
89733×
                }
8982×
                Err(e) => {
8992×
                    results.push(RefResult {
9002×
                        name: "policy".into(),
9012×
                        ok: false,
9022×
                        reason: e,
9032×
                    });
9042×
                    for u in updates {
9050×
                        results.push(RefResult {
9060×
                            name: u.name,
9070×
                            ok: false,
9080×
                            reason: "policy update was rejected".into(),
9090×
                        });
9100×
                    }
9112×
                    return Ok(report);
912
                }
913
            }
914323×
        }
915356×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
916
        // A push of objects alone (one batch of a long history, oxygen#95)
917
        // names no reference: its outcome is reported as `objects`.
918356×
        let objects_only = updates.is_empty() && tags.is_empty();
919356×
        match self.import_bundle(&bundle, policy.is_some()) {
920350×
            Ok(imported) => {
921350×
                if objects_only {
9227×
                    results.push(RefResult {
9237×
                        name: OBJECTS_RESULT.into(),
9247×
                        ok: true,
9257×
                        reason: format!("{} changes stored", imported.len()),
9267×
                    });
927343×
                }
928350×
                report.imported = imported;
929
            }
9306×
            Err(e) => {
9316×
                if objects_only {
9320×
                    results.push(RefResult {
9330×
                        name: OBJECTS_RESULT.into(),
9340×
                        ok: false,
9350×
                        reason: e.to_string(),
9360×
                    });
9376×
                }
9386×
                for u in updates {
9396×
                    results.push(RefResult {
9406×
                        name: u.name,
9416×
                        ok: false,
9426×
                        reason: e.to_string(),
9436×
                    });
9446×
                }
9456×
                return Ok(report);
946
            }
947
        }
948350×
        let (op_ref, op) = self.head_op()?;
949350×
        let mut view = op.view.clone();
950350×
        let mut names = Vec::new();
951350×
        for u in updates {
952341×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
953341×
            let (ok, reason) = match outcome {
954311×
                Ok(()) => (true, String::new()),
95530×
                Err(e) => (false, e),
956
            };
957341×
            if ok {
958311×
                names.push(u.name.clone());
959311×
                let heads = self
960311×
                    .store
961311×
                    .get_state(&u.new_state)
962311×
                    .map(|s| s.heads)
963311×
                    .unwrap_or_default();
964311×
                report.updated.push(RefUpdated {
965311×
                    name: u.name.clone(),
966311×
                    old_state: u.old_state,
967311×
                    new_state: u.new_state,
968311×
                    heads,
969311×
                });
97030×
            }
971341×
            results.push(RefResult {
972341×
                name: u.name,
973341×
                ok,
974341×
                reason,
975341×
            });
976
        }
977350×
        for t in &tags {
97816×
            let name = format!("tags/{}", t.name);
97916×
            let new = !view.tags.contains_key(&t.name);
98016×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
981
                Ok(()) => {
982
                    // A tag new here is an update too, so a hub can start
983
                    // its pipeline's tag jobs (oxygenflow#24); one it
984
                    // already had, sent again, is not.
98512×
                    if new {
98611×
                        report.updated.push(RefUpdated {
98711×
                            name: name.clone(),
98811×
                            old_state: ObjectRef::ZERO,
98911×
                            new_state: t.state,
99011×
                            heads: t.heads.clone(),
99111×
                        });
99211×
                    }
99312×
                    names.push(name.clone());
99412×
                    results.push(RefResult {
99512×
                        name,
99612×
                        ok: true,
99712×
                        reason: String::new(),
99812×
                    });
999
                }
10004×
                Err(e) => results.push(RefResult {
10014×
                    name,
10024×
                    ok: false,
10034×
                    reason: e.reason,
10044×
                }),
1005
            }
1006
        }
1007350×
        if !names.is_empty() {
1008312×
            self.record_op(
1009312×
                &[op_ref],
1010312×
                &format!("push received: {}", names.join(" ")),
1011312×
                view,
10123×
            )?;
101338×
        }
1014347×
        Ok(report)
1015358×
    }
1016
1017
    /// Check an update's attestation against the latest one for its
1018
    /// reference and store it as the new latest. Failures say what was
1019
    /// being done, for which reference, so a refused push can be diagnosed
1020
    /// from its reason alone.
1021104×
    fn record_update_attest(
1022104×
        &self,
1023104×
        u: &RefUpdate,
1024104×
        sa: &SignedAttest,
1025104×
    ) -> std::result::Result<(), String> {
1026104×
        let name = &u.name;
1027104×
        let last = self
1028104×
            .latest_ref_attest(name)
1029104×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1030104×
            .and_then(|(_, a)| match a.attest.body {
103164×
                AttestBody::Ref { serial, .. } => Some(serial),
10320×
                _ => None,
103364×
            });
1034104×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1035102×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1036102×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1037101×
        for sig in &sa.sigs {
1038101×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1039
        }
1040101×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1041
        // Signed by a short-lived key: a host records when it accepted it.
104298×
        let certified = sa
104398×
            .sigs
104498×
            .first()
104598×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
104698×
        if certified {
10476×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
104892×
        }
104998×
        Ok(())
1050104×
    }
1051
1052
    /// Record that this host accepted attestation `r` now, signed with its
1053
    /// acceptor key (spec §14.7); nothing without one.
105411×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
105511×
        let Some(acceptor) = &self.acceptor else {
10567×
            return Ok(());
1057
        };
10584×
        let (id, sk) = (&acceptor.0, &acceptor.1);
10594×
        let attest = Attest {
10604×
            repo: self.id()?,
10614×
            hlc: Hlc::now(),
10624×
            body: AttestBody::Accepted { attest: *r },
1063
        };
10644×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
10654×
        self.store.put_identity(id)?;
10664×
        let a = self.store.put_attest(&attest)?;
10674×
        self.store.put_signature(&a, &sig)?;
10684×
        self.store.index_add_pub("accepted", r, &a)?;
10694×
        Ok(())
107011×
    }
1071
1072
    /// The host's acceptance of attestation `r`, if one was recorded.
1073217×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1074217×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1075196×
            return Ok(None);
1076
        };
1077
        Ok(Some(SignedAttest {
107821×
            attest: self.store.get_attest(&a)?,
107921×
            sigs: self.store.signatures(&a)?,
1080
        }))
1081217×
    }
1082
1083
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1084
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1085
    /// signer's certificate and accepts `sa`; else the attestation's own
1086
    /// time, which the signer chose.
108731×
    pub(crate) fn certified_time(
108831×
        &self,
108931×
        signer: &KeyId,
109031×
        sa: &SignedAttest,
109131×
        accepted: Option<&SignedAttest>,
109231×
    ) -> u64 {
109331×
        self.issuer_acceptance(signer, sa, accepted)
109431×
            .unwrap_or(sa.attest.hlc.wall_ms)
109531×
    }
1096
1097
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1098
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
109991×
    pub(crate) fn issuer_acceptance(
110091×
        &self,
110191×
        signer: &KeyId,
110291×
        sa: &SignedAttest,
110391×
        accepted: Option<&SignedAttest>,
110491×
    ) -> Option<u64> {
110591×
        let acc = accepted?;
110646×
        let c = self.store.certificate_of(signer).ok().flatten()?;
110746×
        let cert = self.store.get_certificate(&c).ok()?;
110846×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
11090×
            return None;
1110
        };
111146×
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
111243×
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
111343×
        (*attest == sa.attest.hash()
111442×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
111543×
        .then_some(acc.attest.hlc.wall_ms)
111691×
    }
1117
1118
    /// Keep an acceptance this repository was given for attestation `r`
1119
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1120
    /// what it accepts.
11219×
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
11229×
        let a = self.store.put_attest(&acc.attest)?;
112311×
        for sig in &acc.sigs {
112411×
            self.store.put_signature(&a, sig)?;
1125
        }
11269×
        self.store.index_add_pub("accepted", r, &a)?;
11279×
        Ok(())
11289×
    }
1129
1130
    /// A fetched bookmark's attestation by a signer the policy does not
1131
    /// list itself: a delegate or a short-lived key, whose authority
1132
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1133
    /// attestation's integrated time when the host's log gives one; else
1134
    /// as before, at the host's acceptance for a certified signer, when it
1135
    /// countersigned one, or at the attestation's own time, and said so
1136
    /// when the host keeps a log. Failing at the integrated time but not
1137
    /// as before is a note while logs are new; a large gap between the
1138
    /// claimed and the integrated time is a note.
1139
    #[allow(clippy::too_many_arguments)]
114027×
    pub(crate) fn authorize_in_time(
114127×
        &self,
114227×
        p: &crate::policy::Policy,
114327×
        remote_name: &str,
114427×
        r: &crate::protocol::RemoteRef,
114527×
        sa: &SignedAttest,
114627×
        signer: &KeyId,
114727×
        log: &super::transparency::LogCheck,
114827×
        notes: &mut Vec<String>,
114927×
    ) -> Result<()> {
1150
        use super::transparency::{gap_note, judge, Timed};
115127×
        let own = sa.attest.hlc.wall_ms;
115227×
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
115327×
        let time = log.time_of(&r.name);
115429×
        let check = |t_delegate: u64, t_cert: u64| {
115529×
            self.delegate_authorized(p, signer, &r.name, t_delegate)
115627×
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
115729×
        };
115827×
        let before = if at != own {
11597×
            "the host's acceptance"
1160
        } else {
116120×
            "the time it claims"
1162
        };
116327×
        let what = format!("{remote_name}/{}", r.name);
116427×
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1165
            Timed::Refused => {
11661×
                return fail(format!(
1167
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
11681×
                    signer.short(12)
1169
                ))
1170
            }
11713×
            Timed::Integrated => {}
11721×
            Timed::Disagrees => notes.push(format!(
1173
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
11741×
                signer.short(12),
11751×
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1176
            )),
11771×
            Timed::Fallback if log.kept => notes.push(format!(
1178
                "{what}: {} checked at {before}, not at a witnessed time: {}",
11791×
                signer.short(12),
11801×
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1181
            )),
118221×
            Timed::Fallback => {}
1183
        }
118426×
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
11852×
            notes.push(format!("{what}'s attestation {n}"));
118624×
        }
118726×
        Ok(())
118827×
    }
1189
1190
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1191
    /// at `old_state`, is never the bookmark a non-bare repository has
1192
    /// checked out (a bare one's default is its host's to protect, see
1193
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1194
    /// an attestation by a key that may update it.
1195
    /// The deletion's attestation stays the bookmark's latest, so an older
1196
    /// one cannot be replayed to bring it back.
11973×
    fn apply_deletion(
11983×
        &self,
11993×
        view: &mut View,
12003×
        u: &RefUpdate,
12013×
        policy: Option<&crate::policy::Policy>,
12023×
    ) -> std::result::Result<(), String> {
12033×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
12040×
            return Err(format!("no bookmark {:?} to delete", u.name));
1205
        };
12063×
        if current != u.old_state {
12070×
            return Err("stale: the remote bookmark has moved; pull first".into());
12083×
        }
12093×
        if !self.is_bare() && u.name == self.config.bookmark {
12101×
            return Err(format!(
12111×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
12121×
                u.name
12131×
            ));
12142×
        }
12152×
        if let Some(p) = policy {
12160×
            let Some(sa) = &u.attestation else {
12170×
                return Err(format!(
12180×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
12190×
                    u.name
12200×
                ));
1221
            };
12220×
            let signer = sa
12230×
                .sigs
12240×
                .first()
12250×
                .map(|s| s.key)
12260×
                .ok_or("attestation carries no signature")?;
1227
            // Received now: the receiver's own clock is the trusted time.
12280×
            let now = Hlc::now().wall_ms;
12290×
            if !p.authorizes(&signer, &u.name)
12300×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
12310×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1232
            {
12330×
                return Err(format!(
12340×
                    "key {} may not delete {:?} under this repository's policy",
12350×
                    signer.short(12),
12360×
                    u.name
12370×
                ));
12380×
            }
12392×
        }
12402×
        if let Some(sa) = &u.attestation {
12411×
            self.record_update_attest(u, sa)?;
12421×
        }
12432×
        view.bookmarks.remove(&u.name);
12442×
        Ok(())
12453×
    }
1246
1247341×
    fn apply_update(
1248341×
        &self,
1249341×
        view: &mut View,
1250341×
        u: &RefUpdate,
1251341×
        policy: Option<&crate::policy::Policy>,
1252341×
    ) -> std::result::Result<(), String> {
1253341×
        if u.name == "policy" {
12540×
            return Err(
12550×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
12560×
            );
1257341×
        }
1258341×
        let empty = self
1259341×
            .store
1260341×
            .put_state(&StateObject::new(vec![]))
1261341×
            .map_err(|e| e.to_string())?;
1262341×
        if u.new_state.is_zero() {
12633×
            return self.apply_deletion(view, u, policy);
1264338×
        }
1265338×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1266338×
        if current != u.old_state {
126710×
            return Err("stale: the remote bookmark has moved; pull first".into());
1268328×
        }
1269328×
        let new_state = self
1270328×
            .store
1271328×
            .get_state(&u.new_state)
1272328×
            .map_err(|_| "new state object is missing".to_string())?;
1273632×
        for h in &new_state.heads {
1274632×
            if !self.store.has(h) {
12751×
                return Err(format!("head {} is missing", h.short(12)));
1276631×
            }
1277
        }
1278327×
        if !u.force {
1279326×
            let old_heads = self
1280326×
                .store
1281326×
                .get_state(&current)
1282326×
                .map_err(|e| e.to_string())?
1283
                .heads;
1284326×
            let closure = self
1285326×
                .closure_in_store(&new_state.heads)
1286326×
                .map_err(|e| e.to_string())?;
1287345×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
12881×
                return Err(format!(
12891×
                    "not a fast-forward: current head {} would be dropped (use --force)",
12901×
                    h.short(12)
12911×
                ));
1292325×
            }
12931×
        }
1294326×
        if let Some(p) = policy {
129557×
            let Some(sa) = &u.attestation else {
12961×
                return Err(format!(
12971×
                    "{:?} requires a signed reference attestation under this repository's policy",
12981×
                    u.name
12991×
                ));
1300
            };
130156×
            let signer = sa
130256×
                .sigs
130356×
                .first()
130456×
                .map(|s| s.key)
130556×
                .ok_or("attestation carries no signature")?;
1306
            // Received now: the receiver's own clock is the trusted time.
130756×
            let now = Hlc::now().wall_ms;
130856×
            if !p.authorizes(&signer, &u.name)
130919×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
131016×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1311
            {
131210×
                return Err(format!(
131310×
                    "key {} may not update {:?} under this repository's policy",
131410×
                    signer.short(12),
131510×
                    u.name
131610×
                ));
131746×
            }
131846×
            let old_heads = self
131946×
                .store
132046×
                .get_state(&current)
132146×
                .map_err(|e| e.to_string())?
1322
                .heads;
132346×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1324269×
        }
1325315×
        if let Some(sa) = &u.attestation {
1326103×
            self.record_update_attest(u, sa)?;
1327212×
        }
1328309×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1329309×
        Ok(())
1330341×
    }
1331
1332
    // ------------------------------------------------------------ client side
1333
13341514×
    fn remote_url(&self, name: &str) -> Result<String> {
13351514×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
13363×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
13373×
            RepoError::Msg(match names.as_slice() {
13383×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
13391×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1340
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
13411×
                    names.join(", "),
13421×
                    names[0],
13431×
                    names[0]
1344
                ),
13450×
                _ => format!(
1346
                    "no remote named {name:?}; this repository has {}",
13470×
                    names.join(", ")
1348
                ),
1349
            })
13503×
        })
13511514×
    }
1352
1353
    /// Refuse a remote that is another repository. An **unbound** remote
1354
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1355
    /// for pushes, which bind it to this repository's id (spec §16.1).
1356826×
    fn check_remote_id(
1357826×
        &self,
1358826×
        remote: &dyn crate::protocol::Remote,
1359826×
        remote_name: &str,
1360826×
        allow_unbound: bool,
1361826×
    ) -> Result<()> {
1362826×
        let theirs = remote.repo_id()?;
1363825×
        if theirs == self.id()? {
1364798×
            return Ok(());
136527×
        }
136627×
        if theirs == crate::protocol::UNBOUND_ID {
136724×
            if allow_unbound {
136823×
                return Ok(());
13691×
            }
13701×
            return fail(format!(
1371
                "remote {remote_name:?} is empty and unbound: push to it first"
1372
            ));
13733×
        }
13743×
        fail(format!(
1375
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1376
        ))
1377826×
    }
1378
1379
    /// Credentials and trust for a remote: `remote.<name>.token` and
1380
    /// `remote.<name>.ca`, else the defaults for its URL
1381
    /// ([`Repo::fill_credentials`]).
13821125×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
13831125×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
13841125×
        let mut options = RemoteOptions {
13851125×
            repo_id: self.id().ok(),
13861125×
            token: self.config.remote_tokens.get(name).cloned(),
13871125×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
13881125×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
13891125×
            ..RemoteOptions::default()
13901125×
        };
13911125×
        self.fill_credentials(&url, &mut options);
13921125×
        options
13931125×
    }
1394
1395
    /// The user's credential store (`credentials.toml` beside the user
1396
    /// configuration file).
13971146×
    pub fn credentials(&self) -> crate::credentials::Credentials {
13981146×
        crate::credentials::Credentials::at(
13991146×
            self.user_config
14001146×
                .parent()
14011146×
                .map(Path::to_path_buf)
14021146×
                .unwrap_or_else(default_home),
1403
        )
14041146×
    }
1405
1406
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1407
    /// then the user's credential store for its hub, then a remote on the
1408
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1409
    /// When the token is not this remote's own or the environment's, the
1410
    /// other tokens enclosing checkouts hold for the hub are kept to try
1411
    /// if it is refused: a stale stored login must not hide a parent's
1412
    /// good token (oxygen#112).
14131147×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
14141147×
        if options.token.is_some() && options.ca.is_some() {
14151×
            return;
14161146×
        }
14171146×
        let explicit =
14181146×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
14191146×
        let stored = self.credentials().options_for(url);
14201146×
        options.token = options.token.take().or(stored.token);
14211146×
        options.ca = options.ca.take().or(stored.ca);
14221146×
        let enclosing = self.enclosing_credentials(url);
14231146×
        if options.token.is_none() {
14241136×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
142510×
        }
14261146×
        if options.ca.is_none() {
14271130×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
142816×
        }
14291146×
        if !explicit {
14301139×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
14315×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
14322×
                    options.fallback_tokens.push(t);
14333×
                }
1434
            }
14357×
        }
14361147×
    }
1437
1438
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1439
    /// checkouts, nearest first.
14401146×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
14411146×
        let mut out = Vec::new();
14421146×
        let Some(hub) = crate::credentials::hub_of(url) else {
1443990×
            return out;
1444
        };
1445156×
        let mut at = self.root.parent();
1446632×
        while let Some(dir) = at {
1447476×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
14480×
                break;
1449
            };
1450476×
            for (key, remote_url) in &cfg {
145115×
                let Some(name) = key
145215×
                    .strip_prefix("remote.")
145315×
                    .and_then(|k| k.strip_suffix(".url"))
1454
                else {
14557×
                    continue;
1456
                };
14578×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
14581×
                    continue;
14597×
                }
14607×
                out.push((
14617×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
14627×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
14637×
                ));
1464
            }
1465476×
            at = dir.parent();
1466
        }
1467156×
        out
14681146×
    }
1469
1470
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1471
    /// no changes and no reference updates, which the receiver stores.
14720×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
14730×
        let remote = self.open_named_remote(remote_name)?;
14740×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
14750×
        let mut bundle = Bundle::default();
14760×
        for r in seals {
14770×
            let attest = self.store.get_attest(r)?;
14780×
            let sigs = self.store.signatures(r)?;
14790×
            bundle
14800×
                .attests
14810×
                .push(crate::protocol::SignedAttest { attest, sigs });
1482
        }
14830×
        let results = remote.push(bundle, vec![], None, vec![])?;
14840×
        if let Some(r) = results.iter().find(|r| !r.ok) {
14850×
            return fail(format!("{}: {}", r.name, r.reason));
14860×
        }
14870×
        Ok(())
14880×
    }
1489
1490
    /// The remote whose URL starts with `base` (a hub), if configured.
14914×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
14924×
        let base = base.trim_end_matches('/');
14934×
        self.config
14944×
            .remotes
14954×
            .iter()
14964×
            .find(|(_, url)| url.trim_end_matches('/') == base)
14974×
            .map(|(name, _)| name.clone())
14984×
    }
1499
1500
    /// Open a remote by name or, failing that, by URL with the default
1501
    /// credentials (see [`Repo::credentials_for`]).
15020×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
15030×
        if let Some(name) = self.remote_for_url(url) {
15040×
            return Ok((name.clone(), self.open_named_remote(&name)?));
15050×
        }
15060×
        let options = RemoteOptions {
15070×
            repo_id: self.id().ok(),
15080×
            ..self.credentials_for(url)
15090×
        };
15100×
        Ok((url.to_string(), open_remote(url, &options)?))
15110×
    }
1512
1513
    /// Credentials for a URL: those of the configured remote with that
1514
    /// URL, else the environment's.
15154×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
15164×
        match self.remote_for_url(url) {
15174×
            Some(name) => self.remote_options(&name),
15180×
            None => RemoteOptions {
15190×
                repo_id: self.id().ok(),
15200×
                ..self.credentials_for(url)
15210×
            },
1522
        }
15234×
    }
1524
15251108×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
15261108×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
15271108×
    }
1528
1529212×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1530212×
        self.oxy
1531212×
            .join("remotes")
1532212×
            .join(remote)
1533212×
            .join(format!("{bookmark}.serial"))
1534212×
    }
1535
153670×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
153770×
        fs::read_to_string(self.serial_path(remote, bookmark))
153870×
            .ok()
153970×
            .and_then(|s| s.trim().parse().ok())
154070×
    }
1541
1542142×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1543142×
        let p = self.serial_path(remote, bookmark);
1544142×
        fs::create_dir_all(p.parent().unwrap())?;
1545142×
        write_atomic(&p, serial.to_string().as_bytes())
1546142×
    }
1547
1548474×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1549474×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1550474×
    }
1551
1552
    /// The highest policy serial `remote` has ever presented.
1553406×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1554406×
        fs::read_to_string(self.policy_serial_path(remote))
1555406×
            .ok()
1556406×
            .and_then(|s| s.trim().parse().ok())
1557406×
    }
1558
155968×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
156068×
        let p = self.policy_serial_path(remote);
156168×
        fs::create_dir_all(p.parent().unwrap())?;
156268×
        write_atomic(&p, serial.to_string().as_bytes())
156368×
    }
1564
156527×
    fn lazy_dir(&self) -> PathBuf {
156627×
        self.oxy.join("lazy")
156727×
    }
1568
1569
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
15704×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
15714×
        fs::create_dir_all(self.lazy_dir())?;
15724×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
15734×
    }
1574
1575
    /// Which remote promised an absent blob, if any.
157615×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
157715×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
157815×
            .ok()
157915×
            .map(|s| s.trim().to_string())
158015×
    }
1581
1582
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
15834×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
15844×
        let Some(remote_name) = self.lazy_remote(blob) else {
15850×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1586
        };
15874×
        let remote = self.open_named_remote(&remote_name)?;
15884×
        let objects = remote.objects(&[*blob])?;
15899×
        for (ty, body) in objects {
15909×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
15919×
                self.store.put(ty, &body)?;
15920×
            }
1593
        }
15944×
        if !self.store.has(blob) {
15950×
            return fail(format!(
1596
                "{remote_name} did not send blob {}",
15970×
                blob.short(12)
1598
            ));
15994×
        }
16004×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
16014×
        Ok(())
16024×
    }
1603
1604
    /// After importing from `remote`, record every blob the changes reference
1605
    /// that the store lacks as lazily available from that remote.
16064×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
16074×
        let mut n = 0;
16084×
        for h in changes {
16094×
            let c = self.store.get_change(h)?;
161013×
            for e in &c.edits {
161113×
                if let Edit::Replace { old, new, .. } = e {
16126×
                    for b in [old, new].into_iter().flatten() {
16136×
                        if !self.store.has(b) {
16144×
                            self.register_lazy(b, remote)?;
16154×
                            n += 1;
16162×
                        }
1617
                    }
16187×
                }
1619
            }
1620
        }
16214×
        Ok(n)
16224×
    }
1623
1624
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1625406×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1626406×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1627553×
        for st in view
1628406×
            .bookmarks
1629406×
            .values()
1630406×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1631
        {
1632553×
            if let Ok(s) = self.store.get_state(st) {
1633553×
                have.extend(s.heads);
1634553×
            }
1635
        }
1636406×
        have.extend(view.workspaces.values().copied());
1637406×
        Ok(have.into_iter().collect())
1638406×
    }
1639
1640
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1641412×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1642412×
        let remote = self.open_named_remote(remote_name)?;
1643409×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1644407×
        let resp = remote.refs()?;
1645
        // The host's transparency log (spec §14.8): a fork fails here.
1646406×
        let log = self.check_log(
1647406×
            &self.remote_url(remote_name)?,
1648406×
            self.config.remote_cas.get(remote_name).map(Path::new),
1649406×
            &resp,
16500×
        )?;
1651406×
        let mut log_notes = log.notes.clone();
1652
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1653
        // and signed by roots we trust, or on first contact. A remote that
1654
        // once presented a policy may never present none or an older one:
1655
        // that is a downgrade. A remote that never presented one is
1656
        // unverified, and this fetch is checked only as far as possible.
1657406×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1658406×
        let seen = self.remote_policy_serial(remote_name);
1659406×
        let mut unverified = false;
1660406×
        match &resp.policy {
166135×
            Some(sp) => {
166235×
                if seen.is_some_and(|s| sp.policy.serial < s) {
16630×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
166435×
                }
166513×
                match &local_policy {
166613×
                    Some(l) if sp.policy.serial < l.serial => {}
166713×
                    Some(l) if sp.policy.serial == l.serial => {
16689×
                        if sp.policy.hash() != l.hash() {
16690×
                            return fail(format!(
1670
                                "{remote_name} presents a different policy with the same serial {}",
1671
                                l.serial
1672
                            ));
16739×
                        }
1674
                    }
1675
                    _ => {
167626×
                        self.adopt_policy_chain(
167726×
                            &resp.history,
167826×
                            sp,
167926×
                            &format!("oxy fetch {remote_name}"),
1680
                        )
168126×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1682
                    }
1683
                }
168435×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1685
            }
1686
            None => {
1687371×
                if seen.is_some() {
16880×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1689371×
                }
1690371×
                unverified = true;
1691
            }
1692
        }
1693406×
        let policy = if unverified {
1694371×
            None
1695
        } else {
169635×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1697
        };
1698406×
        let (op_ref, op) = self.head_op()?;
1699406×
        let mut view = op.view.clone();
1700406×
        let have = self.known_heads(&view)?;
1701406×
        let mut report = Vec::new();
1702406×
        let mut skipped = Vec::new();
1703406×
        let max_blob = self.config.max_blob;
1704432×
        for r in resp.refs {
1705432×
            let needed = {
1706432×
                let _t = crate::timing::phase("fetch: negotiate");
1707432×
                remote.negotiate(&have, &r.heads)?
1708
            };
1709432×
            let bundle = {
1710432×
                let _t = crate::timing::phase("fetch: bundle");
1711432×
                remote.fetch(&needed, max_blob)?
1712
            };
1713
            // Changes are not individually re-verified here: the bookmark's
1714
            // attestation (checked below) binds its whole state, and the
1715
            // receiver of the push verified the added changes at that time.
1716432×
            let imported = {
1717432×
                let _t = crate::timing::phase("fetch: import");
1718432×
                self.import_bundle(&bundle, false)?
1719
            };
1720432×
            if max_blob.is_some() {
17214×
                self.register_missing_blobs(&imported, remote_name)?;
1722428×
            }
1723594×
            for h in &r.heads {
1724594×
                if !self.store.has(h) {
17250×
                    return fail(format!("remote did not send head {}", h.short(12)));
1726594×
                }
1727
            }
1728432×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1729432×
            if state != r.state {
17300×
                return fail(format!(
1731
                    "remote state {} does not match its heads",
17320×
                    r.state.short(12)
1733
                ));
1734432×
            }
1735432×
            if let Some(p) = &policy {
173638×
                let Some(sa) = &r.attestation else {
17370×
                    return fail(format!(
1738
                        "{remote_name}/{} has no attestation, which its policy requires",
1739
                        r.name
1740
                    ));
1741
                };
174238×
                let signer = sa
174338×
                    .sigs
174438×
                    .first()
174538×
                    .map(|s| s.key)
174638×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
174738×
                if !p.authorizes(&signer, &r.name) {
174820×
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
174918×
                }
1750394×
            }
1751432×
            if let Some(sa) = &r.attestation {
1752
                let AttestBody::Ref {
175370×
                    old_state,
175470×
                    new_state,
1755
                    ..
175670×
                } = &sa.attest.body
1757
                else {
17580×
                    return fail("remote sent a non-ref attestation for a bookmark");
1759
                };
176070×
                let (old_state, new_state) = (*old_state, *new_state);
176170×
                let serial = self
176270×
                    .check_ref_attest_body(
176370×
                        sa,
176470×
                        &r.name,
176570×
                        &old_state,
176670×
                        &new_state,
176770×
                        self.last_seen_serial(remote_name, &r.name),
1768
                        true,
1769
                    )
177070×
                    .map_err(|e| {
17710×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
17720×
                    })?;
177370×
                if new_state != r.state {
17740×
                    return fail(format!(
1775
                        "attestation for {}/{} does not cover its current state",
1776
                        remote_name, r.name
1777
                    ));
177870×
                }
1779
                // A signature this client cannot verify (its signer unknown
1780
                // here, as from a host that did not send the identity, or
1781
                // bad) fails that bookmark alone: it stays as it was and
1782
                // the rest are fetched (oxygenhub#266). The current
1783
                // bookmark, which a pull would take, still fails the fetch.
1784
                // A policy's requirements were checked above and still fail.
178570×
                if let Err(e) = self.verify_attest_signature(sa) {
178612×
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
178712×
                    if r.name == self.config.bookmark {
17883×
                        return fail(why);
17899×
                    }
17909×
                    skipped.push((r.name, why));
17919×
                    continue;
179258×
                }
179358×
                let ar = self.store.put_attest(&sa.attest)?;
179458×
                for sig in &sa.sigs {
179558×
                    self.store.put_signature(&ar, sig)?;
1796
                }
179758×
                self.record_serial(remote_name, &r.name, serial)?;
1798362×
            }
1799420×
            view.remotes
1800420×
                .entry(remote_name.to_string())
1801420×
                .or_default()
1802420×
                .insert(r.name.clone(), state);
1803420×
            report.push((r.name, r.heads, imported.len()));
1804
        }
1805403×
        let mut new_tags = 0;
1806403×
        for t in &resp.tags {
180726×
            if view.tags.contains_key(&t.name) {
18086×
                continue;
180920×
            }
1810
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
181120×
            let missing: Vec<ChangeHash> = t
181220×
                .heads
181320×
                .iter()
181420×
                .filter(|h| !self.store.has(h))
181520×
                .copied()
181620×
                .collect();
181720×
            if !missing.is_empty() {
18180×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
18190×
                let bundle = remote.fetch(&needed, max_blob)?;
18200×
                self.import_bundle(&bundle, false)?;
182120×
            }
182220×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
182320×
            let mut check = TagCheck::Fetched {
182420×
                remote: remote_name,
182520×
                log: &log,
182620×
                notes: &mut log_notes,
182720×
            };
182820×
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
182918×
                Ok(()) => new_tags += 1,
1830
                // Nothing says when a short-lived key signed it: the tag is
1831
                // left out, said so, and the rest is fetched (oxygen#129).
18322×
                Err(e) if e.untimed => {
18332×
                    skipped.push((format!("tags/{}", t.name), e.reason));
18342×
                }
18350×
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1836
            }
1837
        }
1838403×
        if view != op.view {
1839387×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
184016×
        }
1841403×
        let _ = self.run_hook(
1842403×
            "post-fetch",
1843403×
            &format!(
1844
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1845403×
                json_str(remote_name),
1846417×
                json_array(report.iter().map(|(n, heads, _)| format!(
1847
                    "{{\"name\":{},\"heads\":{}}}",
1848417×
                    json_str(n),
1849579×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1850
                )))
1851
            ),
1852
        );
1853403×
        Ok(FetchReport {
1854403×
            refs: report,
1855403×
            unverified,
1856403×
            new_tags,
1857403×
            log_notes,
1858403×
            skipped,
1859403×
        })
1860412×
    }
1861
1862
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1863
    /// the changes within `depth` steps of its heads, and the boundary below.
18641×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
18651×
        let remote = self.open_named_remote(remote_name)?;
18661×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
18671×
        let resp = remote.refs()?;
18681×
        let bookmark = self.config.bookmark.clone();
18691×
        if let Some(sp) = &resp.policy {
18700×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
18710×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
18720×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
18731×
        }
18741×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
18750×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1876
        };
18771×
        if r.heads.is_empty() {
18780×
            return Ok(0);
18791×
        }
1880
        // Base: the remote's checkpoint of exactly these heads.
18811×
        let cp_bundle = remote.checkpoint(&r.heads)?;
18821×
        let mut cp_ref = None;
18833×
        for (ty, body) in &cp_bundle.objects {
18843×
            let put = self.store.put(*ty, body)?;
18853×
            if *ty == ObjectType::Checkpoint {
18861×
                cp_ref = Some(put);
18872×
            }
1888
        }
18891×
        let Some(cp_ref) = cp_ref else {
18900×
            return fail(format!("{remote_name} sent no checkpoint"));
1891
        };
18921×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1893
        // History window.
18941×
        let wanted = remote.shallow(&r.heads, depth)?;
18951×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
18961×
        let imported = self.import_bundle_shallow(&bundle, false)?;
18971×
        if self.config.max_blob.is_some() {
18980×
            self.register_missing_blobs(&imported, remote_name)?;
18991×
        }
19001×
        self.refresh_boundary(&imported)?;
19011×
        if let Some(sa) = &r.attestation {
19020×
            let ar = self.store.put_attest(&sa.attest)?;
19030×
            for sig in &sa.sigs {
19040×
                self.store.put_signature(&ar, sig)?;
1905
            }
19060×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
19070×
                self.record_serial(remote_name, &r.name, serial)?;
19080×
            }
19091×
        }
19101×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
19111×
        let (op_ref, op) = self.head_op()?;
19121×
        let mut view = op.view.clone();
19131×
        view.remotes
19141×
            .entry(remote_name.to_string())
19151×
            .or_default()
19161×
            .insert(r.name.clone(), state);
19171×
        self.record_op(
19181×
            &[op_ref],
19191×
            &format!("oxy fetch {remote_name} --depth {depth}"),
19201×
            view,
19210×
        )?;
19221×
        Ok(imported.len())
19231×
    }
1924
1925
    /// Fetch, then take the union of the local bookmark's state with the
1926
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1927118×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1928118×
        let _wc = self.lock_working_copy()?;
1929118×
        let skipped = self.fetch(remote_name)?.skipped;
1930114×
        let (op_ref, op) = self.head_op()?;
1931114×
        let current = self.config.bookmark.clone();
1932114×
        let mut local_current = self.heads_of(&op.view, &current)?;
1933114×
        local_current.sort();
1934114×
        let mut view = op.view.clone();
1935114×
        let mut current_heads = local_current.clone();
1936114×
        let mut changed = false;
1937114×
        let mut others = Vec::new();
1938114×
        let tracked = op
1939114×
            .view
1940114×
            .remotes
1941114×
            .get(remote_name)
1942114×
            .cloned()
1943114×
            .unwrap_or_default();
1944119×
        for (name, remote_state) in tracked {
1945
            // Every local bookmark tracks the remote's of the same name;
1946
            // the current one may be new here.
1947119×
            let local_state = op.view.bookmarks.get(&name).copied();
1948119×
            if local_state.is_none() && name != current {
19491×
                continue;
1950118×
            }
1951118×
            if local_state == Some(remote_state) {
195210×
                continue;
1953108×
            }
1954108×
            let local = self.heads_of(&op.view, &name)?;
1955108×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1956160×
            if remote_heads.iter().all(|h| local.contains(h)) {
19570×
                continue;
1958108×
            }
1959108×
            let mut all = local.clone();
1960108×
            all.extend(remote_heads);
1961108×
            let st = self.load_state_history(&all)?;
1962108×
            let mut heads = st.maximal(&all);
1963108×
            heads.sort();
1964108×
            let mut sorted_local = local;
1965108×
            sorted_local.sort();
1966108×
            if heads == sorted_local {
19671×
                continue;
1968107×
            }
1969107×
            view.bookmarks.insert(
1970107×
                name.clone(),
1971107×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1972
            );
1973107×
            if name == current {
1974105×
                changed = true;
1975105×
                current_heads = heads;
1976105×
            } else {
19772×
                others.push(name);
19782×
            }
1979
        }
1980114×
        if changed || !others.is_empty() {
1981106×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
19828×
        }
1983
        // The working copy follows its bookmark whenever nothing would be
1984
        // lost, also when this pull brought nothing new but it had been
1985
        // left behind (oxygen#89).
1986114×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1987
        Ok(PullReport {
1988114×
            heads: if changed {
1989105×
                current_heads
1990
            } else {
19919×
                local_current
1992
            },
1993114×
            changed,
1994114×
            checked_out,
1995114×
            others,
1996114×
            skipped,
1997
        })
1998118×
    }
1999
2000
    /// How many changes the working copy's bookmark has that its base
2001
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2002
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2003
    /// the bookmark or holds changes the bookmark lacks. History is read
2004
    /// only when the base and the bookmark's heads differ (oxygen#89).
20057×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
20067×
        let (_, wc) = self.working_copy()?;
20077×
        let mut base = wc.deps.clone();
20087×
        base.sort();
20097×
        let mut heads = self.bookmark_heads()?;
20107×
        heads.sort();
20117×
        if base == heads || heads.is_empty() {
20126×
            return Ok(None);
20131×
        }
20141×
        let state = self.load_state_history(&heads)?;
20151×
        if !base.iter().all(|h| state.contains(h)) {
20160×
            return Ok(None);
20171×
        }
20181×
        let had = if base.is_empty() {
20190×
            0
2020
        } else {
20211×
            self.load_state_history(&base)?.len()
2022
        };
20231×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
20247×
    }
2025
2026
    /// Bring the working copy to `heads`, the state of its bookmark
2027
    /// `bookmark`, when nothing would be lost: its base is part of that
2028
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2029
    /// with uncommitted work, the work comes along when the new changes
2030
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2031
    /// it followed only from exactly the bookmark's old heads, so a working
2032
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2033
    /// or a pull from another workspace) never caught up, and nothing said
2034
    /// so (oxygen#74, #89). Returns whether it moved.
2035114×
    pub fn follow_bookmark(
2036114×
        &self,
2037114×
        heads: &[ChangeHash],
2038114×
        bookmark: &str,
2039114×
        command: &str,
2040114×
    ) -> Result<bool> {
2041114×
        let snap = self.snapshot(command)?;
2042114×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2043114×
        let mut base = snap.base.maximal(&snap.wc.deps);
2044114×
        base.sort();
2045114×
        let mut target = heads.to_vec();
2046114×
        target.sort();
2047114×
        if base == target {
20488×
            return Ok(false);
2049106×
        }
2050106×
        let state = self.load_state_history(heads)?;
2051196×
        if !base.iter().all(|h| state.contains(h)) {
2052
            // The working copy holds changes the bookmark lacks: not ours to move.
20530×
            return Ok(false);
2054106×
        }
2055106×
        if clean {
2056106×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
2057106×
            Ok(true)
2058
        } else {
20590×
            Ok(self
20600×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
20610×
                .is_ok())
2062
        }
2063114×
    }
2064
2065
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2066
    /// changes and attesting the reference when a key is available.
2067
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2068
    /// state, attested when we have an identity. The local bookmark, if
2069
    /// any, is kept; only the remote-tracking entry goes.
20705×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
20715×
        let remote = self.open_named_remote(remote_name)?;
20725×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
20735×
        let resp = remote.refs()?;
20747×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
20751×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2076
        };
20774×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
20780×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
20794×
        }
20804×
        let attestation = match self.secret_key()? {
20812×
            Some(_) => Some(self.sign_attest(&Attest {
20822×
                repo: self.id()?,
20832×
                hlc: Hlc::now(),
20842×
                body: AttestBody::Ref {
20852×
                    name: bookmark.to_string(),
20862×
                    old_state: r.state,
20872×
                    new_state: ObjectRef::ZERO,
20882×
                    serial: r.last_serial.unwrap_or(0) + 1,
20892×
                },
20900×
            })?),
20912×
            None => None,
2092
        };
20934×
        let results = remote.push(
20944×
            Bundle::default(),
20954×
            vec![RefUpdate {
20964×
                name: bookmark.to_string(),
20974×
                old_state: r.state,
20984×
                new_state: ObjectRef::ZERO,
20994×
                force: true,
21004×
                attestation,
21014×
            }],
21024×
            None,
21034×
            vec![],
21040×
        )?;
21054×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
21062×
            let (op_ref, op) = self.head_op()?;
21072×
            let mut view = op.view.clone();
21082×
            if let Some(m) = view.remotes.get_mut(remote_name) {
21092×
                m.remove(bookmark);
21102×
            }
21112×
            self.record_op(
21122×
                &[op_ref],
21132×
                &format!("oxy push {remote_name} --delete {bookmark}"),
21142×
                view,
21150×
            )?;
21162×
        }
21174×
        Ok(results)
21185×
    }
2119
2120
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2121
    /// repository's config (its URL, token, CA and store settings), its
2122
    /// tracking bookmarks in the view, and a store remote's mirror under
2123
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
21243×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
21253×
        if !self.config.remotes.contains_key(name) {
21261×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
21272×
        }
21282×
        let prefix = format!("remote.{name}.");
21292×
        let keys: Vec<String> = self
21302×
            .config
21312×
            .repo_layer()
21322×
            .keys()
21334×
            .filter(|k| k.starts_with(&prefix))
21342×
            .cloned()
21352×
            .collect();
21363×
        for k in keys {
21373×
            self.config.set(&k, "")?;
2138
        }
21392×
        self.config.remotes.remove(name);
21402×
        self.save_config()?;
21412×
        let (op_ref, op) = self.head_op()?;
21422×
        if op.view.remotes.contains_key(name) {
21431×
            let mut view = op.view.clone();
21441×
            view.remotes.remove(name);
21451×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
21461×
        }
21472×
        let mirror = self.oxy.join("remotes").join(name);
21482×
        if mirror.is_dir() {
21490×
            fs::remove_dir_all(&mirror)?;
21502×
        }
21512×
        Ok(())
21523×
    }
2153
2154
    /// `changes`, in dependency order, cut into batches of about
2155
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2156
    /// There is always one, perhaps empty.
2157322×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2158322×
        let blob_len = |r: &ObjectRef| -> u64 {
215929×
            self.store
216029×
                .get_typed(r, ObjectType::Blob)
216129×
                .ok()
216229×
                .and_then(|b| Blob::decode(&b).ok())
216329×
                .map_or(0, |b| b.length)
216429×
        };
2165322×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2166424×
        for h in changes {
2167424×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2168424×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2169424×
            let mut weight = raw.len() as u64;
2170547×
            for t in &texts {
2171547×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
217226×
                    weight += blob_len(r);
2173521×
                }
2174
            }
2175724×
            for e in &c.edits {
21763×
                if let Edit::Replace { new: Some(b), .. } = e {
21773×
                    weight += blob_len(b);
2178721×
                }
2179
            }
2180424×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
21815×
                out.push(std::mem::take(&mut batch));
21825×
                bytes = 0;
2183419×
            }
2184424×
            batch.push(*h);
2185424×
            bytes += weight;
2186
        }
2187322×
        out.push(batch);
2188322×
        Ok(out)
2189322×
    }
2190
2191391×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2192391×
        let bookmark = self.config.bookmark.clone();
2193391×
        self.push_bookmark(remote_name, &bookmark, force)
2194391×
    }
2195
2196
    /// `push` for a named bookmark (`oxy push -b NAME`).
2197404×
    pub fn push_bookmark(
2198404×
        &self,
2199404×
        remote_name: &str,
2200404×
        bookmark: &str,
2201404×
        force: bool,
2202404×
    ) -> Result<Vec<RefResult>> {
2203404×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2204404×
    }
2205
2206
    /// `push_bookmark`, saying how a long push is going: one line per
2207
    /// batch sent (oxygen#95).
2208412×
    pub fn push_bookmark_with(
2209412×
        &self,
2210412×
        remote_name: &str,
2211412×
        bookmark: &str,
2212412×
        force: bool,
2213412×
        progress: crate::store::Progress,
2214412×
    ) -> Result<Vec<RefResult>> {
2215412×
        let (op_ref, op) = self.head_op()?;
2216412×
        if !op.view.bookmarks.contains_key(bookmark) {
22170×
            return fail(format!("no bookmark {bookmark}"));
2218412×
        }
2219412×
        let bookmark = bookmark.to_string();
2220412×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2221
        // pre-push hook: may veto before the remote is contacted.
2222412×
        self.run_hook(
2223412×
            "pre-push",
2224412×
            &format!(
2225
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2226412×
                json_str(remote_name),
2227412×
                json_str(&bookmark),
2228814×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2229
            ),
22301×
        )?;
2231411×
        let remote = self.open_named_remote(remote_name)?;
2232411×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2233408×
        let resp = remote.refs()?;
2234408×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2235408×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2236408×
        let policy_to_send = match (&local_policy, &resp.policy) {
223743×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
223815×
            (Some(l), None) => Some(l.clone()),
223925×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
22401×
                return fail(format!(
2241
                    "{remote_name} has a newer policy (serial {}); fetch first",
2242
                    r.policy.serial
2243
                ));
2244
            }
2245374×
            _ => None,
2246
        };
2247407×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2248407×
        if remote_has_policy && self.secret_key()?.is_none() {
22491×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2250406×
        }
2251406×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2252406×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2253406×
            .tag_refs()?
2254406×
            .into_iter()
2255406×
            .filter(|t| !remote_tags.contains(&t.name))
2256406×
            .collect();
2257406×
        let refs = resp.refs;
2258406×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2259406×
        let (remote_state, remote_heads, last_serial) =
2260407×
            match refs.iter().find(|r| r.name == bookmark) {
2261384×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
226222×
                None => (empty, vec![], None),
2263
            };
2264406×
        let new_state = self
2265406×
            .store
2266406×
            .put_state(&StateObject::new(local_heads.clone()))?;
2267
        // A push that carries a policy re-attests the bookmark even when its
2268
        // state is unchanged, so the current attestation is always by a key
2269
        // the current policy authorizes (a revoked key's attestation would
2270
        // otherwise be refused by every later fetch).
2271406×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
22727×
            return Ok(vec![RefResult {
22737×
                name: bookmark,
22747×
                ok: true,
22757×
                reason: "already up to date".into(),
22767×
            }]);
2277399×
        }
2278461×
        for h in &remote_heads {
2279461×
            if !self.store.has(h) {
228076×
                return fail(format!(
2281
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
228276×
                    h.short(12)
2283
                ));
2284385×
            }
2285
        }
2286323×
        if !force {
2287323×
            let closure = self.closure_in_store(&local_heads)?;
2288347×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
22890×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2290323×
            }
22910×
        }
2292323×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2293323×
        let key = self.secret_key()?.map(|(k, _)| k);
2294323×
        if let Some(key) = key {
2295
            // Seal this author's changes that carry no valid authenticator,
2296
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2297
            // are stored, so each batch's bundle carries those it needs.
2298110×
            let mut unsigned = Vec::new();
2299110×
            for h in &to_send {
230091×
                let c = self.store.get_change_meta(h)?;
230191×
                if self.seals_for_author(&c.author, &key)
230286×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
230352×
                {
230452×
                    unsigned.push(*h);
230552×
                }
2306
            }
2307110×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
230849×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2309
            }
2310213×
        }
2311
        // A long history goes in batches, in dependency order, so neither
2312
        // side holds it whole and no request passes the remote's limit:
2313
        // all but the last carry objects alone; the last moves the bookmark
2314
        // (oxygen#95).
2315322×
        let batches = self.push_batches(&to_send)?;
2316322×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2317322×
        for (i, batch) in earlier.iter().enumerate() {
23185×
            progress(&format!(
23195×
                "part {} of {}: {} changes",
23205×
                i + 1,
23215×
                batches.len(),
23225×
                batch.len()
23235×
            ));
23245×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
23255×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
23265×
                Some(r) if r.ok => {}
23270×
                Some(r) => {
23280×
                    return fail(format!(
2329
                        "{remote_name} refused part {} of the push: {}",
23300×
                        i + 1,
2331
                        r.reason
2332
                    ))
2333
                }
2334
                None => {
23350×
                    return fail(format!(
2336
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2337
                    ))
2338
                }
2339
            }
2340
        }
2341322×
        if batches.len() > 1 {
23421×
            progress(&format!(
23431×
                "part {} of {}: {} changes",
23441×
                batches.len(),
23451×
                batches.len(),
23461×
                last.len()
23471×
            ));
2348321×
        }
2349322×
        let mut bundle = self.bundle_for(last)?;
2350322×
        bundle.objects.push((
2351322×
            ObjectType::State,
2352322×
            StateObject::new(local_heads.clone()).encode(),
2353322×
        ));
2354322×
        let attestation = match key {
2355109×
            Some(_) => Some(self.sign_attest(&Attest {
2356109×
                repo: self.id()?,
2357109×
                hlc: Hlc::now(),
2358109×
                body: AttestBody::Ref {
2359109×
                    name: bookmark.clone(),
2360109×
                    old_state: remote_state,
2361109×
                    new_state,
2362109×
                    serial: next_serial(last_serial),
2363109×
                },
23641×
            })?),
2365213×
            None => None,
2366
        };
2367
        // Whoever signed the move, and whom a delegate acts for, travel with
2368
        // it: a receiver that has never seen a change by this delegate could
2369
        // not otherwise check its signature (oxygenhub#129).
2370321×
        if attestation.is_some() {
2371216×
            for k in [self.signing_key(), self.config.author_key]
2372108×
                .into_iter()
2373108×
                .flatten()
2374
            {
2375216×
                if let Ok(id) = self.identity(&k) {
2376216×
                    let body = id.encode();
2377216×
                    if !bundle
2378216×
                        .objects
2379216×
                        .iter()
2380262×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
238131×
                    {
238231×
                        bundle.objects.push((ObjectType::Identity, body));
2383185×
                    }
23840×
                }
2385
            }
2386
            // A short-lived signing key's certificate goes with it (§14.7).
2387108×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2388108×
            self.attach_certificates_for(&mut bundle, &signers)?;
2389213×
        }
2390321×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2391108×
            AttestBody::Ref { serial, .. } => Some(serial),
23920×
            _ => None,
2393108×
        });
2394321×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2395
        // Tag states must be present on the remote: bundle their changes too.
2396321×
        for t in &tags_to_send {
239714×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
239814×
            let extra: Vec<ChangeHash> =
239914×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
240014×
            if !extra.is_empty() {
24010×
                let more = self.bundle_for(&extra)?;
24020×
                bundle.changes.extend(more.changes);
24030×
                bundle.hashes.extend(more.hashes);
24040×
                bundle.attests.extend(more.attests);
24050×
                bundle.objects.extend(more.objects);
240614×
            }
240714×
            bundle.objects.push((
240814×
                ObjectType::State,
240914×
                StateObject::new(t.heads.clone()).encode(),
241014×
            ));
2411
        }
2412
        // A tag's signer travels with it, as the bookmark's does: a tag made
2413
        // by `oxy tag create` under a short-lived key was signed by a key the
2414
        // receiver has never seen, so its identity and certificate go too.
2415321×
        let tag_signers: Vec<KeyId> = tags_to_send
2416321×
            .iter()
2417321×
            .filter_map(|t| t.attestation.as_ref())
2418321×
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2419321×
            .collect();
2420321×
        for k in &tag_signers {
242113×
            if let Ok(id) = self.identity(k) {
242213×
                let body = id.encode();
242313×
                if !bundle
242413×
                    .objects
242513×
                    .iter()
242626×
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
24272×
                {
24282×
                    bundle.objects.push((ObjectType::Identity, body));
242911×
                }
24300×
            }
2431
        }
2432321×
        if !tag_signers.is_empty() {
243313×
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2434308×
        }
2435321×
        if let Some(l) = &policy_to_send {
243633×
            let remote_serial = resp_policy_serial;
243733×
            bundle.policies = self
243833×
                .policy_history()?
243933×
                .into_iter()
244065×
                .filter(|sp| {
244165×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
244235×
                        && sp.policy.serial < l.policy.serial
244365×
                })
244433×
                .collect();
2445288×
        }
2446321×
        let results = remote.push(
2447321×
            bundle,
2448321×
            vec![RefUpdate {
2449321×
                name: bookmark.clone(),
2450321×
                old_state: remote_state,
2451321×
                new_state,
2452321×
                force,
2453321×
                attestation,
2454321×
            }],
2455321×
            policy_to_send,
2456321×
            tags_to_send,
24578×
        )?;
245833×
        if let (Some(serial), true) = (
2459313×
            sent_serial,
2460326×
            results.iter().any(|r| r.ok && r.name == "policy"),
2461
        ) {
246233×
            self.record_policy_serial(remote_name, serial)?;
2463280×
        }
2464349×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2465286×
            let mut view = op.view.clone();
2466286×
            view.remotes
2467286×
                .entry(remote_name.to_string())
2468286×
                .or_default()
2469286×
                .insert(bookmark.clone(), new_state);
2470286×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2471283×
            if let Some(s) = serial {
247284×
                self.record_serial(remote_name, &bookmark, s)?;
2473199×
            }
247427×
        }
2475308×
        Ok(results)
2476412×
    }
2477
2478
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2479
    /// bookmark set to the remote's, working copy checked out.
2480261×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2481261×
        Self::clone_with(url, dest, None, &[])
2482261×
    }
2483
2484
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2485
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2486
    /// unless a size is given, so out-of-scope binaries are never fetched).
2487264×
    pub fn clone_with(
2488264×
        url: &str,
2489264×
        dest: &Path,
2490264×
        max_blob: Option<u64>,
2491264×
        sparse: &[String],
2492264×
    ) -> Result<Repo> {
2493264×
        Self::clone_full(url, dest, max_blob, sparse, None)
2494264×
    }
2495
2496
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2497
    /// changes within `depth` steps of them; the rest is the boundary.
24981×
    pub fn clone_shallow(
24991×
        url: &str,
25001×
        dest: &Path,
25011×
        depth: u32,
25021×
        max_blob: Option<u64>,
25031×
        sparse: &[String],
25041×
    ) -> Result<Repo> {
25051×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
25061×
    }
2507
2508265×
    fn clone_full(
2509265×
        url: &str,
2510265×
        dest: &Path,
2511265×
        max_blob: Option<u64>,
2512265×
        sparse: &[String],
2513265×
        depth: Option<u32>,
2514265×
    ) -> Result<Repo> {
2515265×
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2516265×
    }
2517
2518
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2519
    /// `depth`), also returning the bookmarks the fetch left out because
2520
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2521
    /// for the caller to warn about. The bookmark checked out is never one
2522
    /// of them: that fails the clone.
2523271×
    pub fn clone_reporting(
2524271×
        url: &str,
2525271×
        dest: &Path,
2526271×
        max_blob: Option<u64>,
2527271×
        sparse: &[String],
2528271×
        depth: Option<u32>,
2529271×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2530271×
        let options = crate::credentials::Credentials::user().options_for(url);
2531271×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2532271×
    }
2533
2534
    /// Clone a subrepo with the credentials the parent would use for its
2535
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2536
    /// subrepo: it finds the same ones again through its parent.
253710×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
253810×
        let options = self.credentials_for(url);
253910×
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
254010×
    }
2541
2542
    /// The name of a remote of this repository on the same hub (scheme,
2543
    /// host and port) as `url`.
254423×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
254527×
        let origin = |u: &str| -> Option<String> {
254627×
            let (scheme, rest) = u.split_once("://")?;
25478×
            if !matches!(scheme, "http" | "https") {
25480×
                return None;
25498×
            }
25508×
            let host = rest.split('/').next()?;
25518×
            Some(format!(
25528×
                "{}://{}",
25538×
                scheme.to_ascii_lowercase(),
25548×
                host.to_ascii_lowercase()
25558×
            ))
255627×
        };
255723×
        let want = origin(url)?;
25584×
        self.config
25594×
            .remotes
25604×
            .iter()
25614×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
25624×
            .map(|(name, _)| name.clone())
256323×
    }
2564
2565
    /// The token and CA to reach `url` with: those of a remote of this
2566
    /// repository on the same hub (scheme, host and port), else the
2567
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2568
    /// and enclosing checkouts', as a clone would use them.
256923×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
257023×
        match self.remote_on_same_hub(url) {
25711×
            Some(name) => RemoteOptions {
25721×
                repo_id: None,
25731×
                cache_dir: None,
25741×
                ..self.remote_options(&name)
25751×
            },
2576
            None => {
257722×
                let mut options = RemoteOptions::default();
257822×
                self.fill_credentials(url, &mut options);
257922×
                options
2580
            }
2581
        }
258223×
    }
2583
2584281×
    fn clone_using(
2585281×
        url: &str,
2586281×
        dest: &Path,
2587281×
        max_blob: Option<u64>,
2588281×
        sparse: &[String],
2589281×
        depth: Option<u32>,
2590281×
        options: &RemoteOptions,
2591281×
    ) -> Result<(Repo, Vec<(String, String)>)> {
2592281×
        let remote = open_remote(url, options)?;
2593281×
        let id = remote.repo_id()?;
2594277×
        if id == crate::protocol::UNBOUND_ID {
25952×
            return fail(format!(
2596
                "{url} is empty and unbound: push a repository to it first"
2597
            ));
2598275×
        }
2599275×
        let mut repo = Repo::init_with_id(dest, id)?;
2600275×
        repo.config
2601275×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2602275×
        if let Some(m) = max_blob {
26032×
            repo.config.set("filter.max-blob", &m.to_string())?;
2604273×
        } else if !sparse.is_empty() {
26051×
            repo.config.set("filter.max-blob", "0")?;
2606272×
        }
2607275×
        if !sparse.is_empty() {
26081×
            repo.config.set("filter.paths", &sparse.join(","))?;
2609274×
        }
2610275×
        repo.save_config()?;
2611275×
        let skipped = if let Some(depth) = depth {
26121×
            repo.fetch_shallow("origin", depth)?;
26131×
            Vec::new()
2614
        } else {
2615274×
            repo.fetch("origin")?.skipped
2616
        };
2617273×
        let (op_ref, op) = repo.head_op()?;
2618
        // The remote's default bookmark, else ours (main), else its only
2619
        // one; a bookmark the fetch skipped counts, so the clone fails
2620
        // rather than check out another (oxygenhub#266).
2621273×
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2622273×
        for (name, _) in &skipped {
26233×
            theirs.insert(name.clone(), ObjectRef::ZERO);
26243×
        }
2625
        // Asked of the remote as now configured, so a store-backed one
2626
        // answers from the mirror the fetch just filled.
2627273×
        let advertised = repo
2628273×
            .open_named_remote("origin")
2629273×
            .ok()
2630273×
            .and_then(|r| r.refs().ok())
2631273×
            .and_then(|r| r.default_bookmark);
2632273×
        let bookmark = advertised
2633273×
            .filter(|b| theirs.contains_key(b))
2634273×
            .or_else(|| {
26357×
                theirs
26367×
                    .contains_key(&repo.config.bookmark)
26377×
                    .then(|| repo.config.bookmark.clone())
26387×
            })
2639273×
            .or_else(|| {
26400×
                (theirs.len() == 1)
26410×
                    .then(|| theirs.keys().next().cloned())
26420×
                    .flatten()
26430×
            })
2644273×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2645273×
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
26460×
            return fail(format!("cannot check out {bookmark}: {why}"));
2647273×
        }
2648273×
        let initial = repo.config.bookmark.clone();
2649273×
        if bookmark != repo.config.bookmark {
26501×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
26511×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
26521×
            repo.config.bookmark = bookmark.clone();
2653272×
        }
2654273×
        if let Some(state) = theirs.get(&bookmark).copied() {
2655273×
            let heads = repo.store.get_state(&state)?.heads;
2656273×
            let mut view = op.view.clone();
2657
            // The empty bookmark `init` made goes when another is checked out.
2658273×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
26591×
                view.bookmarks.remove(&initial);
2660272×
            }
2661273×
            view.bookmarks.insert(bookmark, state);
2662273×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2663273×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
26640×
        }
2665273×
        Ok((repo, skipped))
2666281×
    }
2667
}
2668
2669
/// The serial of a reference's next attestation: one more than the last the
2670
/// remote reports, or, for a bookmark the remote does not have, the clock in
2671
/// milliseconds, so a bookmark created again after a deletion goes past the
2672
/// deletion's serial the remote keeps.
2673109×
fn next_serial(last: Option<u64>) -> u64 {
2674109×
    match last {
267568×
        Some(l) => l + 1,
267641×
        None => Hlc::now().wall_ms.max(1),
2677
    }
2678109×
}