OXYGENHUB

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

1546 of 1731 lines run, 226 of 318 functions · run #295 on main · run missed

1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
}
34
35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub struct PullReport {
37
    /// The current bookmark's heads after the pull.
38
    pub heads: Vec<ChangeHash>,
39
    /// Whether the current bookmark changed.
40
    pub changed: bool,
41
    pub checked_out: bool,
42
    /// Other bookmarks the pull moved: each local bookmark tracks the
43
    /// remote's of the same name.
44
    pub others: Vec<String>,
45
}
46
47
/// The result a push of objects alone reports (a batch of a long history):
48
/// not a reference.
49
pub const OBJECTS_RESULT: &str = "objects";
50
51
impl Repo {
52
    // ------------------------------------------------------------ serving (spec §16)
53
541269×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551269×
        self.oxy.join("attest").join(name_file(bookmark))
561269×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591192×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601192×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61198×
            Ok(h) => {
62198×
                let r = ObjectRef::from_hex(h.trim())
63198×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65198×
                    r,
66
                    SignedAttest {
67198×
                        attest: self.store.get_attest(&r)?,
68198×
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
71
            }
72994×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751192×
    }
76
7777×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7877×
        fs::create_dir_all(self.oxy.join("attest"))?;
7977×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8077×
    }
81
82976×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
83976×
        let view = self.view()?;
84976×
        let mut out = Vec::new();
85998×
        for (name, state) in &view.bookmarks {
86998×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
87998×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88106×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90106×
            });
91998×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
92998×
            out.push(RemoteRef {
93998×
                name: name.clone(),
94998×
                state: *state,
95998×
                heads: self.store.get_state(state)?.heads,
96998×
                attestation,
97998×
                last_serial,
98
            });
99
        }
100976×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
101976×
        let history = self
102976×
            .policy_history()?
103976×
            .into_iter()
104976×
            .filter(|sp| {
10569×
                policy
10669×
                    .as_ref()
10769×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10869×
            })
109976×
            .collect();
110
        Ok(RefsResponse {
111976×
            refs: out,
112976×
            policy,
113976×
            tags: self.tag_refs()?,
114976×
            history,
115976×
            default_bookmark: Some(self.config.bookmark.clone()),
116
        })
117976×
    }
118
119
    /// Every change reachable from `heads` that is in the store.
1201293×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1211293×
        let mut seen = BTreeSet::new();
1221293×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1234488×
        while let Some(h) = stack.pop() {
1243195×
            if seen.contains(&h) || !self.store.has(&h) {
125917×
                continue;
1262278×
            }
1272278×
            seen.insert(h);
1282278×
            stack.extend(self.store.get_change_meta(&h)?.deps);
129
        }
1301293×
        Ok(seen)
1311293×
    }
132
133
    /// The changes within `depth` dependency steps of `heads` (spec §17),
134
    /// nearest first; depth 1 is the heads themselves.
1353×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1363×
        let mut out = Vec::new();
1373×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1383×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1393×
        for _ in 0..depth.max(1) {
1408×
            let mut next = Vec::new();
14112×
            for h in layer {
14212×
                if !seen.insert(h) || !self.store.has(&h) {
1432×
                    continue;
14410×
                }
14510×
                let c = self.store.get_change(&h)?;
14610×
                next.extend(c.deps.iter().copied());
14710×
                out.push(h);
148
            }
1498×
            if next.is_empty() {
1501×
                break;
1517×
            }
1527×
            layer = next;
153
        }
1543×
        out.reverse();
1553×
        Ok(out)
1563×
    }
157
1581872×
    fn shallow_path(&self) -> PathBuf {
1591872×
        self.oxy.join("shallow")
1601872×
    }
161
162
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1631869×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1641869×
        fs::read_to_string(self.shallow_path())
1651869×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1661869×
            .unwrap_or_default()
1671869×
    }
168
169183×
    pub fn is_shallow(&self) -> bool {
170183×
        !self.boundary().is_empty()
171183×
    }
172
1733×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1743×
        if boundary.is_empty() {
1751×
            let _ = fs::remove_file(self.shallow_path());
1761×
            return Ok(());
1772×
        }
1782×
        let text: String = boundary
1792×
            .iter()
1802×
            .map(|h| format!("{}\n", h.to_hex()))
1812×
            .collect();
1822×
        write_atomic(&self.shallow_path(), text.as_bytes())
1833×
    }
184
185
    /// Recompute the boundary from what is stored: every dependency of a
186
    /// stored change that is not itself stored.
1873×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1883×
        let mut boundary = self.boundary();
1893×
        boundary.retain(|h| !self.store.has(h));
19010×
        for h in imported {
19113×
            for d in self.store.get_change_meta(h)?.deps {
19213×
                if !self.store.has(&d) {
1932×
                    boundary.insert(d);
19411×
                }
195
            }
196
        }
1973×
        self.write_boundary(&boundary)
1983×
    }
199
200
    /// Fetch `depth` more levels of history below the shallow boundary.
2012×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2022×
        let boundary = self.boundary();
2032×
        if boundary.is_empty() {
2040×
            return Ok(0);
2052×
        }
2062×
        let remote = self.open_named_remote(remote_name)?;
2072×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2082×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2092×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2102×
        if self.config.max_blob.is_some() {
2110×
            self.register_missing_blobs(&imported, remote_name)?;
2122×
        }
2132×
        self.refresh_boundary(&imported)?;
2142×
        Ok(imported.len())
2152×
    }
216
217
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
218735×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
219735×
        let have = self.closure_in_store(have)?;
220
        // In a shallow repository the walk stops at the boundary, whose
221
        // changes the remote is assumed to hold.
222735×
        let boundary = self.boundary();
223735×
        let mut out = Vec::new();
224735×
        let mut done: BTreeSet<ChangeHash> = have.clone();
225735×
        done.extend(boundary.iter().copied());
226
        // Iterative post-order DFS.
2271167×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2283072×
        while let Some((h, expanded)) = stack.pop() {
2292337×
            if done.contains(&h) {
230369×
                continue;
2311968×
            }
2321968×
            if !self.store.has(&h) {
2330×
                return fail(format!("change {} is not in this repository", h.short(12)));
2341968×
            }
2351968×
            if expanded {
236984×
                done.insert(h);
237984×
                out.push(h);
238984×
                continue;
239984×
            }
240984×
            stack.push((h, true));
241984×
            for d in self.store.get_change_meta(&h)?.deps {
242672×
                if !done.contains(&d) {
243186×
                    stack.push((d, false));
244486×
                }
245
            }
246
        }
247735×
        Ok(out)
248735×
    }
249
250
    /// Bundle changes (in the given dependency order) with their signatures,
251
    /// seals, identities, blobs, chunks.
252291×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
253291×
        self.bundle_for_filtered(changes, None)
254291×
    }
255
256
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2574×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2584×
        let mut out = Vec::new();
2594×
        for r in refs {
2604×
            let (ty, body) = match self.store.get(r) {
2614×
                Ok(x) => x,
2620×
                Err(StoreError::NotFound(_)) => continue,
2630×
                Err(e) => return Err(e.into()),
264
            };
2654×
            if ty == ObjectType::Blob {
2665×
                for c in Blob::decode(&body)?.chunks {
2675×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2685×
                        out.push((cty, cb));
2695×
                    }
270
                }
2710×
            }
2724×
            out.push((ty, body));
273
        }
2744×
        Ok(out)
2754×
    }
276
277
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
278
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
279335×
    pub fn bundle_for_filtered(
280335×
        &self,
281335×
        changes: &[ChangeHash],
282335×
        max_blob: Option<u64>,
283335×
    ) -> Result<Bundle> {
284335×
        self.bundle_of(changes, max_blob, false)
285335×
    }
286
287
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
288
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
289
    /// with their text blobs and chunks among the objects, so neither side
290
    /// decodes or encodes their text.
291312×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
292312×
        self.bundle_of(changes, max_blob, true)
293312×
    }
294
295647×
    fn bundle_of(
296647×
        &self,
297647×
        changes: &[ChangeHash],
298647×
        max_blob: Option<u64>,
299647×
        raw: bool,
300647×
    ) -> Result<Bundle> {
301647×
        let mut bundle = Bundle::default();
302647×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
303647×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
304996×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
305996×
            if !r.is_zero() && self.store.has(r) {
306170×
                objects.insert(*r);
307826×
            }
308996×
        };
309913×
        for h in changes {
310
            // Raw: the stored bytes, and a skeleton for the rest.
311913×
            let (c, encoded) = if raw {
312483×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
313483×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3144946×
                for t in texts {
3154946×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3163×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3173×
                        objects.insert(r);
3183×
                        objects.extend(blob.chunks);
3194943×
                    }
320
                }
321483×
                (skel, Some(bytes))
322
            } else {
323430×
                (self.store.get_change(h)?, None)
324
            };
325913×
            let sigs = self.store.signatures(h)?;
326913×
            add_object(&c.author, &mut objects);
327913×
            for s in &sigs {
32822×
                add_object(&s.key, &mut objects);
32922×
            }
3305851×
            for e in &c.edits {
3315851×
                if let Edit::Replace { old, new, .. } = e {
33214×
                    for b in [old, new].into_iter().flatten() {
33314×
                        if self.store.has(b) {
33414×
                            if let Ok(blob) =
33514×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
336
                            {
33714×
                                if max_blob.is_some_and(|m| blob.length > m) {
3384×
                                    continue;
33910×
                                }
34010×
                                objects.insert(*b);
34110×
                                objects.extend(blob.chunks.iter().copied());
3420×
                            }
3430×
                        }
344
                    }
3455839×
                }
346
            }
347913×
            for s in self.store.seals_for(h)? {
34865×
                seals.insert(s);
34965×
            }
350913×
            match encoded {
351483×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
352430×
                None => {
353430×
                    bundle.changes.push((c, sigs));
354430×
                    bundle.hashes.push(*h);
355430×
                }
356
            }
357
        }
358647×
        for r in seals {
35961×
            let attest = self.store.get_attest(&r)?;
36061×
            let sigs = self.store.signatures(&r)?;
36161×
            for s in &sigs {
36261×
                add_object(&s.key, &mut objects);
36361×
            }
36461×
            bundle.attests.push(SignedAttest { attest, sigs });
365
        }
366647×
        for r in objects {
367105×
            let (ty, body) = self.store.get(&r)?;
368105×
            bundle.objects.push((ty, body));
369
        }
370647×
        Ok(bundle)
371647×
    }
372
373
    /// Store a bundle's contents. With `strict`, every change must
374
    /// authenticate (signature or seal by its author or a delegate).
375689×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
376689×
        self.import_bundle_inner(bundle, strict, false)
377689×
    }
378
379
    /// Like `import_bundle`, accepting changes whose dependencies are absent
380
    /// (they join the shallow boundary).
3813×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
3823×
        self.import_bundle_inner(bundle, strict, true)
3833×
    }
384
385692×
    fn import_bundle_inner(
386692×
        &self,
387692×
        bundle: &Bundle,
388692×
        strict: bool,
389692×
        shallow: bool,
390692×
    ) -> Result<Vec<ChangeHash>> {
391692×
        let batch = self.store.begin_batch()?;
392692×
        let result = self.import_bundle_batched(bundle, strict, shallow);
393692×
        batch.finish()?;
394690×
        result
395692×
    }
396
397692×
    fn import_bundle_batched(
398692×
        &self,
399692×
        bundle: &Bundle,
400692×
        strict: bool,
401692×
        shallow: bool,
402692×
    ) -> Result<Vec<ChangeHash>> {
403692×
        for (ty, _) in &bundle.objects {
4040×
            if !matches!(
405467×
                ty,
406
                ObjectType::Chunk
407
                    | ObjectType::Blob
408
                    | ObjectType::Identity
409
                    | ObjectType::State
410
                    | ObjectType::Checkpoint
411
            ) {
4120×
                return fail(format!("bundle may not carry {} objects", ty.name()));
413467×
            }
414
        }
415
        // All at once: in a large batch they are compressed on every core.
416692×
        let objects: Vec<(ObjectType, &[u8])> = bundle
417692×
            .objects
418692×
            .iter()
419692×
            .map(|(ty, body)| (*ty, body.as_slice()))
420692×
            .collect();
421692×
        self.store.put_many(&objects)?;
422692×
        for sa in &bundle.attests {
42364×
            let r = self.store.put_attest(&sa.attest)?;
42464×
            for sig in &sa.sigs {
42564×
                self.store.put_signature(&r, sig)?;
426
            }
42764×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
42868×
                for h in hashes {
42968×
                    self.store.index_seal(h, &r)?;
430
                }
4310×
            }
432
        }
433
        // Each change's hash: from the bundle when its maker knew it, else
434
        // worked out once (for a change adding a whole tree, hashing is
435
        // chunking all its text).
436692×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
437683×
            bundle.hashes.clone()
438
        } else {
4399×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
440
        };
441692×
        let raw_hashes: Vec<ChangeHash> = bundle
442692×
            .raw_changes
443692×
            .iter()
444692×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
445692×
            .collect();
446692×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
447692×
        let boundary = self.boundary();
448692×
        let mut imported = Vec::new();
449
        // Changes as stored: checked, then stored as they are, their text
450
        // blobs having come with the objects.
451692×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
452484×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
453484×
            for d in &skel.deps {
454351×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
455
                {
4560×
                    return fail(format!(
457
                        "change {} depends on {}, which is neither stored nor in the bundle",
4580×
                        h.short(12),
4590×
                        d.short(12)
460
                    ));
461351×
                }
462
            }
4634947×
            for t in texts {
4644947×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
4654×
                    if !self.store.has(&r) {
4661×
                        return fail(format!(
467
                            "change {} came without its text blob {}",
4681×
                            h.short(12),
4691×
                            r.short(12)
470
                        ));
4713×
                    }
4724943×
                }
473
            }
474483×
            self.store.put(ObjectType::Change, bytes)?;
475483×
            for sig in sigs {
4764×
                self.store.put_signature(&h, sig)?;
477
            }
478483×
            imported.push(h);
479
        }
480691×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
481458×
            for d in &c.deps {
482275×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
483
                {
4843×
                    return fail(format!(
485
                        "change {} depends on {}, which is neither stored nor in the bundle",
4863×
                        h.short(12),
4873×
                        d.short(12)
488
                    ));
489272×
                }
490
            }
491455×
            let stored = self.store.put_change(c)?;
492455×
            if stored != h {
4930×
                return fail(format!(
494
                    "change {} is not the change the bundle names",
4950×
                    h.short(12)
496
                ));
497455×
            }
498455×
            for sig in sigs {
49927×
                self.store.put_signature(&h, sig)?;
500
            }
501455×
            imported.push(h);
502
        }
503688×
        if strict {
50431×
            for h in &imported {
50521×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
5061×
                    return fail(format!(
507
                        "change {} is not authenticated by its author",
5081×
                        h.short(12)
509
                    ));
51020×
                }
511
            }
512657×
        }
513687×
        Ok(imported)
514692×
    }
515
516
    /// Verify a reference attestation against an update it claims to describe.
517
    /// `allow_equal` lets a client re-read the attestation it already has; a
518
    /// server receiving a push requires a strictly greater serial.
519
    /// A reference attestation signed by a delegate of an identity the
520
    /// rule lists is authorized as that identity (spec §14.5): the identity
521
    /// named the delegate with the `refs` scope, still in force at `at_ms`
522
    /// (the attestation's wall time), and the policy names the identity.
523
    /// Revoked keys authorize nothing either way.
5247×
    pub(crate) fn delegate_authorized(
5257×
        &self,
5267×
        p: &crate::policy::Policy,
5277×
        signer: &KeyId,
5287×
        reference: &str,
5297×
        at_ms: u64,
5307×
    ) -> bool {
5317×
        if p.is_revoked(signer) {
5321×
            return false;
5336×
        }
5346×
        let Some(rule) = p.rule_for(reference) else {
5350×
            return false;
536
        };
5377×
        rule.keys.iter().any(|k| {
5387×
            !p.is_revoked(k)
5397×
                && p.identity(k)
5407×
                    .cloned()
5417×
                    .or_else(|| self.store.get_identity(k).ok())
5427×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
5437×
        })
5447×
    }
545
54696×
    fn check_ref_attest(
54796×
        &self,
54896×
        sa: &SignedAttest,
54996×
        name: &str,
55096×
        old_state: &ObjectRef,
55196×
        new_state: &ObjectRef,
55296×
        last_serial: Option<u64>,
55396×
        allow_equal: bool,
55496×
    ) -> std::result::Result<u64, String> {
555
        let AttestBody::Ref {
55696×
            name: n,
55796×
            old_state: o,
55896×
            new_state: nw,
55996×
            serial,
56096×
        } = &sa.attest.body
561
        else {
5620×
            return Err("attestation is not a ref attestation".into());
563
        };
56496×
        if n != name || o != old_state || nw != new_state {
5651×
            return Err("attestation does not describe this update".into());
56695×
        }
56795×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
5680×
            return Err("attestation is for a different repository".into());
56995×
        }
57095×
        if let Some(last) = last_serial {
57160×
            if *serial < last || (*serial == last && !allow_equal) {
5721×
                return Err(format!(
5731×
                    "attestation serial {serial} is not greater than the last seen {last}"
5741×
                ));
57559×
            }
57635×
        }
57794×
        let r = sa.attest.hash();
57894×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
57994×
        let id = self
58094×
            .store
58194×
            .get_identity(&sig.key)
58294×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
58394×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
58494×
        Ok(*serial)
58596×
    }
586
587
    /// Accept a push (spec §16.4). Without a trust policy every repository
588
    /// is unverified, so unsigned changes and unattested updates are accepted;
589
    /// attestations that are present must still be valid. With a policy,
590
    /// every change and update is checked against it. A newer policy in the
591
    /// push is applied first when it is signed by the current roots.
592273×
    pub fn receive_push(
593273×
        &self,
594273×
        bundle: Bundle,
595273×
        updates: Vec<RefUpdate>,
596273×
        policy: Option<SignedPolicy>,
597273×
        tags: Vec<crate::protocol::TagRef>,
598273×
    ) -> Result<Vec<RefResult>> {
599273×
        Ok(self
600273×
            .receive_push_report(bundle, updates, policy, tags)?
601
            .results)
602273×
    }
603
604
    /// `receive_push` with what a host wants to log: each accepted
605
    /// reference's old and new state and heads, and the changes this push
606
    /// stored (hub spec §6.12).
607309×
    pub fn receive_push_report(
608309×
        &self,
609309×
        bundle: Bundle,
610309×
        updates: Vec<RefUpdate>,
611309×
        policy: Option<SignedPolicy>,
612309×
        tags: Vec<crate::protocol::TagRef>,
613309×
    ) -> Result<PushReport> {
614309×
        let mut report = PushReport::default();
615309×
        let results = &mut report.results;
616309×
        if let Some(sp) = policy {
61720×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
61818×
                Ok(()) => {
61918×
                    results.push(RefResult {
62018×
                        name: "policy".into(),
62118×
                        ok: true,
62218×
                        reason: format!("serial {}", sp.policy.serial),
62318×
                    });
62418×
                }
6252×
                Err(e) => {
6262×
                    results.push(RefResult {
6272×
                        name: "policy".into(),
6282×
                        ok: false,
6292×
                        reason: e,
6302×
                    });
6312×
                    for u in updates {
6320×
                        results.push(RefResult {
6330×
                            name: u.name,
6340×
                            ok: false,
6350×
                            reason: "policy update was rejected".into(),
6360×
                        });
6370×
                    }
6382×
                    return Ok(report);
639
                }
640
            }
641289×
        }
642307×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
643
        // A push of objects alone (one batch of a long history, oxygen#95)
644
        // names no reference: its outcome is reported as `objects`.
645307×
        let objects_only = updates.is_empty() && tags.is_empty();
646307×
        match self.import_bundle(&bundle, policy.is_some()) {
647304×
            Ok(imported) => {
648304×
                if objects_only {
6497×
                    results.push(RefResult {
6507×
                        name: OBJECTS_RESULT.into(),
6517×
                        ok: true,
6527×
                        reason: format!("{} changes stored", imported.len()),
6537×
                    });
654297×
                }
655304×
                report.imported = imported;
656
            }
6573×
            Err(e) => {
6583×
                if objects_only {
6590×
                    results.push(RefResult {
6600×
                        name: OBJECTS_RESULT.into(),
6610×
                        ok: false,
6620×
                        reason: e.to_string(),
6630×
                    });
6643×
                }
6653×
                for u in updates {
6663×
                    results.push(RefResult {
6673×
                        name: u.name,
6683×
                        ok: false,
6693×
                        reason: e.to_string(),
6703×
                    });
6713×
                }
6723×
                return Ok(report);
673
            }
674
        }
675304×
        let (op_ref, op) = self.head_op()?;
676304×
        let mut view = op.view.clone();
677304×
        let mut names = Vec::new();
678304×
        for u in updates {
679295×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
680295×
            let (ok, reason) = match outcome {
681275×
                Ok(()) => (true, String::new()),
68220×
                Err(e) => (false, e),
683
            };
684295×
            if ok {
685275×
                names.push(u.name.clone());
686275×
                let heads = self
687275×
                    .store
688275×
                    .get_state(&u.new_state)
689275×
                    .map(|s| s.heads)
690275×
                    .unwrap_or_default();
691275×
                report.updated.push(RefUpdated {
692275×
                    name: u.name.clone(),
693275×
                    old_state: u.old_state,
694275×
                    new_state: u.new_state,
695275×
                    heads,
696275×
                });
69720×
            }
698295×
            results.push(RefResult {
699295×
                name: u.name,
700295×
                ok,
701295×
                reason,
702295×
            });
703
        }
704304×
        for t in &tags {
7058×
            let name = format!("tags/{}", t.name);
7068×
            let new = !view.tags.contains_key(&t.name);
7078×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
708
                Ok(()) => {
709
                    // A tag new here is an update too, so a hub can start
710
                    // its pipeline's tag jobs (oxygenflow#24); one it
711
                    // already had, sent again, is not.
7126×
                    if new {
7136×
                        report.updated.push(RefUpdated {
7146×
                            name: name.clone(),
7156×
                            old_state: ObjectRef::ZERO,
7166×
                            new_state: t.state,
7176×
                            heads: t.heads.clone(),
7186×
                        });
7196×
                    }
7206×
                    names.push(name.clone());
7216×
                    results.push(RefResult {
7226×
                        name,
7236×
                        ok: true,
7246×
                        reason: String::new(),
7256×
                    });
726
                }
7272×
                Err(e) => results.push(RefResult {
7282×
                    name,
7292×
                    ok: false,
7302×
                    reason: e,
7312×
                }),
732
            }
733
        }
734304×
        if !names.is_empty() {
735275×
            self.record_op(
736275×
                &[op_ref],
737275×
                &format!("push received: {}", names.join(" ")),
738275×
                view,
7393×
            )?;
74029×
        }
741301×
        Ok(report)
742309×
    }
743
744
    /// Check an update's attestation against the latest one for its
745
    /// reference and store it as the new latest. Failures say what was
746
    /// being done, for which reference, so a refused push can be diagnosed
747
    /// from its reason alone.
74877×
    fn record_update_attest(
74977×
        &self,
75077×
        u: &RefUpdate,
75177×
        sa: &SignedAttest,
75277×
    ) -> std::result::Result<(), String> {
75377×
        let name = &u.name;
75477×
        let last = self
75577×
            .latest_ref_attest(name)
75677×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
75777×
            .and_then(|(_, a)| match a.attest.body {
75850×
                AttestBody::Ref { serial, .. } => Some(serial),
7590×
                _ => None,
76050×
            });
76177×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
76275×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
76375×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
76474×
        for sig in &sa.sigs {
76574×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
766
        }
76774×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
76877×
    }
769
770
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
771
    /// at `old_state`, is never the bookmark a non-bare repository has
772
    /// checked out (a bare one's default is its host's to protect, see
773
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
774
    /// an attestation by a key that may update it.
775
    /// The deletion's attestation stays the bookmark's latest, so an older
776
    /// one cannot be replayed to bring it back.
7773×
    fn apply_deletion(
7783×
        &self,
7793×
        view: &mut View,
7803×
        u: &RefUpdate,
7813×
        policy: Option<&crate::policy::Policy>,
7823×
    ) -> std::result::Result<(), String> {
7833×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
7840×
            return Err(format!("no bookmark {:?} to delete", u.name));
785
        };
7863×
        if current != u.old_state {
7870×
            return Err("stale: the remote bookmark has moved; pull first".into());
7883×
        }
7893×
        if !self.is_bare() && u.name == self.config.bookmark {
7901×
            return Err(format!(
7911×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
7921×
                u.name
7931×
            ));
7942×
        }
7952×
        if let Some(p) = policy {
7960×
            let Some(sa) = &u.attestation else {
7970×
                return Err(format!(
7980×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
7990×
                    u.name
8000×
                ));
801
            };
8020×
            let signer = sa
8030×
                .sigs
8040×
                .first()
8050×
                .map(|s| s.key)
8060×
                .ok_or("attestation carries no signature")?;
8070×
            if !p.authorizes(&signer, &u.name)
8080×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
809
            {
8100×
                return Err(format!(
8110×
                    "key {} may not delete {:?} under this repository's policy",
8120×
                    signer.short(12),
8130×
                    u.name
8140×
                ));
8150×
            }
8162×
        }
8172×
        if let Some(sa) = &u.attestation {
8181×
            self.record_update_attest(u, sa)?;
8191×
        }
8202×
        view.bookmarks.remove(&u.name);
8212×
        Ok(())
8223×
    }
823
824295×
    fn apply_update(
825295×
        &self,
826295×
        view: &mut View,
827295×
        u: &RefUpdate,
828295×
        policy: Option<&crate::policy::Policy>,
829295×
    ) -> std::result::Result<(), String> {
830295×
        if u.name == "policy" {
8310×
            return Err(
8320×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
8330×
            );
834295×
        }
835295×
        let empty = self
836295×
            .store
837295×
            .put_state(&StateObject::new(vec![]))
838295×
            .map_err(|e| e.to_string())?;
839295×
        if u.new_state.is_zero() {
8403×
            return self.apply_deletion(view, u, policy);
841292×
        }
842292×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
843292×
        if current != u.old_state {
8445×
            return Err("stale: the remote bookmark has moved; pull first".into());
845287×
        }
846287×
        let new_state = self
847287×
            .store
848287×
            .get_state(&u.new_state)
849287×
            .map_err(|_| "new state object is missing".to_string())?;
850563×
        for h in &new_state.heads {
851563×
            if !self.store.has(h) {
8521×
                return Err(format!("head {} is missing", h.short(12)));
853562×
            }
854
        }
855286×
        if !u.force {
856285×
            let old_heads = self
857285×
                .store
858285×
                .get_state(&current)
859285×
                .map_err(|e| e.to_string())?
860
                .heads;
861285×
            let closure = self
862285×
                .closure_in_store(&new_state.heads)
863285×
                .map_err(|e| e.to_string())?;
864305×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
8651×
                return Err(format!(
8661×
                    "not a fast-forward: current head {} would be dropped (use --force)",
8671×
                    h.short(12)
8681×
                ));
869284×
            }
8701×
        }
871285×
        if let Some(p) = policy {
87229×
            let Some(sa) = &u.attestation else {
8731×
                return Err(format!(
8741×
                    "{:?} requires a signed reference attestation under this repository's policy",
8751×
                    u.name
8761×
                ));
877
            };
87828×
            let signer = sa
87928×
                .sigs
88028×
                .first()
88128×
                .map(|s| s.key)
88228×
                .ok_or("attestation carries no signature")?;
88328×
            if !p.authorizes(&signer, &u.name)
8847×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
885
            {
8865×
                return Err(format!(
8875×
                    "key {} may not update {:?} under this repository's policy",
8885×
                    signer.short(12),
8895×
                    u.name
8905×
                ));
89123×
            }
89223×
            let old_heads = self
89323×
                .store
89423×
                .get_state(&current)
89523×
                .map_err(|e| e.to_string())?
896
                .heads;
89723×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
898256×
        }
899279×
        if let Some(sa) = &u.attestation {
90076×
            self.record_update_attest(u, sa)?;
901203×
        }
902273×
        view.bookmarks.insert(u.name.clone(), u.new_state);
903273×
        Ok(())
904295×
    }
905
906
    // ------------------------------------------------------------ client side
907
908954×
    fn remote_url(&self, name: &str) -> Result<String> {
909954×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
9103×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
9113×
            RepoError::Msg(match names.as_slice() {
9123×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
9131×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
914
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
9151×
                    names.join(", "),
9161×
                    names[0],
9171×
                    names[0]
918
                ),
9190×
                _ => format!(
920
                    "no remote named {name:?}; this repository has {}",
9210×
                    names.join(", ")
922
                ),
923
            })
9243×
        })
925954×
    }
926
927
    /// Refuse a remote that is another repository. An **unbound** remote
928
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
929
    /// for pushes, which bind it to this repository's id (spec §16.1).
930708×
    fn check_remote_id(
931708×
        &self,
932708×
        remote: &dyn crate::protocol::Remote,
933708×
        remote_name: &str,
934708×
        allow_unbound: bool,
935708×
    ) -> Result<()> {
936708×
        let theirs = remote.repo_id()?;
937707×
        if theirs == self.id()? {
938684×
            return Ok(());
93923×
        }
94023×
        if theirs == crate::protocol::UNBOUND_ID {
94120×
            if allow_unbound {
94219×
                return Ok(());
9431×
            }
9441×
            return fail(format!(
945
                "remote {remote_name:?} is empty and unbound: push to it first"
946
            ));
9473×
        }
9483×
        fail(format!(
949
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
950
        ))
951708×
    }
952
953
    /// Credentials and trust for a remote: `remote.<name>.token` and
954
    /// `remote.<name>.ca`, else the defaults for its URL
955
    /// ([`Repo::fill_credentials`]).
956971×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
957971×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
958971×
        let mut options = RemoteOptions {
959971×
            repo_id: self.id().ok(),
960971×
            token: self.config.remote_tokens.get(name).cloned(),
961971×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
962971×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
963971×
            ..RemoteOptions::default()
964971×
        };
965971×
        self.fill_credentials(&url, &mut options);
966971×
        options
967971×
    }
968
969
    /// The user's credential store (`credentials.toml` beside the user
970
    /// configuration file).
971990×
    pub fn credentials(&self) -> crate::credentials::Credentials {
972990×
        crate::credentials::Credentials::at(
973990×
            self.user_config
974990×
                .parent()
975990×
                .map(Path::to_path_buf)
976990×
                .unwrap_or_else(default_home),
977
        )
978990×
    }
979
980
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
981
    /// then the user's credential store for its hub, then a remote on the
982
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
983
    /// When the token is not this remote's own or the environment's, the
984
    /// other tokens enclosing checkouts hold for the hub are kept to try
985
    /// if it is refused: a stale stored login must not hide a parent's
986
    /// good token (oxygen#112).
987991×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
988991×
        if options.token.is_some() && options.ca.is_some() {
9891×
            return;
990990×
        }
991990×
        let explicit =
992990×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
993990×
        let stored = self.credentials().options_for(url);
994990×
        options.token = options.token.take().or(stored.token);
995990×
        options.ca = options.ca.take().or(stored.ca);
996990×
        let enclosing = self.enclosing_credentials(url);
997990×
        if options.token.is_none() {
998980×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
99910×
        }
1000990×
        if options.ca.is_none() {
1001931×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
100259×
        }
1003990×
        if !explicit {
1004983×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
10055×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
10062×
                    options.fallback_tokens.push(t);
10073×
                }
1008
            }
10097×
        }
1010991×
    }
1011
1012
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1013
    /// checkouts, nearest first.
1014990×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
1015990×
        let mut out = Vec::new();
1016990×
        let Some(hub) = crate::credentials::hub_of(url) else {
1017860×
            return out;
1018
        };
1019130×
        let mut at = self.root.parent();
1020528×
        while let Some(dir) = at {
1021398×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
10220×
                break;
1023
            };
1024398×
            for (key, remote_url) in &cfg {
102515×
                let Some(name) = key
102615×
                    .strip_prefix("remote.")
102715×
                    .and_then(|k| k.strip_suffix(".url"))
1028
                else {
10297×
                    continue;
1030
                };
10318×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
10321×
                    continue;
10337×
                }
10347×
                out.push((
10357×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
10367×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
10377×
                ));
1038
            }
1039398×
            at = dir.parent();
1040
        }
1041130×
        out
1042990×
    }
1043
1044
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1045
    /// no changes and no reference updates, which the receiver stores.
10460×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
10470×
        let remote = self.open_named_remote(remote_name)?;
10480×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
10490×
        let mut bundle = Bundle::default();
10500×
        for r in seals {
10510×
            let attest = self.store.get_attest(r)?;
10520×
            let sigs = self.store.signatures(r)?;
10530×
            bundle
10540×
                .attests
10550×
                .push(crate::protocol::SignedAttest { attest, sigs });
1056
        }
10570×
        let results = remote.push(bundle, vec![], None, vec![])?;
10580×
        if let Some(r) = results.iter().find(|r| !r.ok) {
10590×
            return fail(format!("{}: {}", r.name, r.reason));
10600×
        }
10610×
        Ok(())
10620×
    }
1063
1064
    /// The remote whose URL starts with `base` (a hub), if configured.
10654×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
10664×
        let base = base.trim_end_matches('/');
10674×
        self.config
10684×
            .remotes
10694×
            .iter()
10704×
            .find(|(_, url)| url.trim_end_matches('/') == base)
10714×
            .map(|(name, _)| name.clone())
10724×
    }
1073
1074
    /// Open a remote by name or, failing that, by URL with the default
1075
    /// credentials (see [`Repo::credentials_for`]).
10760×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
10770×
        if let Some(name) = self.remote_for_url(url) {
10780×
            return Ok((name.clone(), self.open_named_remote(&name)?));
10790×
        }
10800×
        let options = RemoteOptions {
10810×
            repo_id: self.id().ok(),
10820×
            ..self.credentials_for(url)
10830×
        };
10840×
        Ok((url.to_string(), open_remote(url, &options)?))
10850×
    }
1086
1087
    /// Credentials for a URL: those of the configured remote with that
1088
    /// URL, else the environment's.
10894×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
10904×
        match self.remote_for_url(url) {
10914×
            Some(name) => self.remote_options(&name),
10920×
            None => RemoteOptions {
10930×
                repo_id: self.id().ok(),
10940×
                ..self.credentials_for(url)
10950×
            },
1096
        }
10974×
    }
1098
1099954×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1100954×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1101954×
    }
1102
110395×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
110495×
        self.oxy
110595×
            .join("remotes")
110695×
            .join(remote)
110795×
            .join(format!("{bookmark}.serial"))
110895×
    }
1109
111019×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
111119×
        fs::read_to_string(self.serial_path(remote, bookmark))
111219×
            .ok()
111319×
            .and_then(|s| s.trim().parse().ok())
111419×
    }
1115
111676×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
111776×
        let p = self.serial_path(remote, bookmark);
111876×
        fs::create_dir_all(p.parent().unwrap())?;
111976×
        write_atomic(&p, serial.to_string().as_bytes())
112076×
    }
1121
1122371×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1123371×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1124371×
    }
1125
1126
    /// The highest policy serial `remote` has ever presented.
1127345×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1128345×
        fs::read_to_string(self.policy_serial_path(remote))
1129345×
            .ok()
1130345×
            .and_then(|s| s.trim().parse().ok())
1131345×
    }
1132
113326×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
113426×
        let p = self.policy_serial_path(remote);
113526×
        fs::create_dir_all(p.parent().unwrap())?;
113626×
        write_atomic(&p, serial.to_string().as_bytes())
113726×
    }
1138
113927×
    fn lazy_dir(&self) -> PathBuf {
114027×
        self.oxy.join("lazy")
114127×
    }
1142
1143
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
11444×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
11454×
        fs::create_dir_all(self.lazy_dir())?;
11464×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
11474×
    }
1148
1149
    /// Which remote promised an absent blob, if any.
115015×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
115115×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
115215×
            .ok()
115315×
            .map(|s| s.trim().to_string())
115415×
    }
1155
1156
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
11574×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
11584×
        let Some(remote_name) = self.lazy_remote(blob) else {
11590×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1160
        };
11614×
        let remote = self.open_named_remote(&remote_name)?;
11624×
        let objects = remote.objects(&[*blob])?;
11639×
        for (ty, body) in objects {
11649×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
11659×
                self.store.put(ty, &body)?;
11660×
            }
1167
        }
11684×
        if !self.store.has(blob) {
11690×
            return fail(format!(
1170
                "{remote_name} did not send blob {}",
11710×
                blob.short(12)
1172
            ));
11734×
        }
11744×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
11754×
        Ok(())
11764×
    }
1177
1178
    /// After importing from `remote`, record every blob the changes reference
1179
    /// that the store lacks as lazily available from that remote.
11804×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
11814×
        let mut n = 0;
11824×
        for h in changes {
11834×
            let c = self.store.get_change(h)?;
118413×
            for e in &c.edits {
118513×
                if let Edit::Replace { old, new, .. } = e {
11866×
                    for b in [old, new].into_iter().flatten() {
11876×
                        if !self.store.has(b) {
11884×
                            self.register_lazy(b, remote)?;
11894×
                            n += 1;
11902×
                        }
1191
                    }
11927×
                }
1193
            }
1194
        }
11954×
        Ok(n)
11964×
    }
1197
1198
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1199345×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1200345×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1201463×
        for st in view
1202345×
            .bookmarks
1203345×
            .values()
1204345×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1205
        {
1206463×
            if let Ok(s) = self.store.get_state(st) {
1207463×
                have.extend(s.heads);
1208463×
            }
1209
        }
1210345×
        have.extend(view.workspaces.values().copied());
1211345×
        Ok(have.into_iter().collect())
1212345×
    }
1213
1214
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1215351×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1216351×
        let remote = self.open_named_remote(remote_name)?;
1217348×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1218346×
        let resp = remote.refs()?;
1219
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1220
        // and signed by roots we trust, or on first contact. A remote that
1221
        // once presented a policy may never present none or an older one:
1222
        // that is a downgrade. A remote that never presented one is
1223
        // unverified, and this fetch is checked only as far as possible.
1224345×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1225345×
        let seen = self.remote_policy_serial(remote_name);
1226345×
        let mut unverified = false;
1227345×
        match &resp.policy {
12288×
            Some(sp) => {
12298×
                if seen.is_some_and(|s| sp.policy.serial < s) {
12300×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
12318×
                }
12325×
                match &local_policy {
12335×
                    Some(l) if sp.policy.serial < l.serial => {}
12345×
                    Some(l) if sp.policy.serial == l.serial => {
12351×
                        if sp.policy.hash() != l.hash() {
12360×
                            return fail(format!(
1237
                                "{remote_name} presents a different policy with the same serial {}",
1238
                                l.serial
1239
                            ));
12401×
                        }
1241
                    }
1242
                    _ => {
12437×
                        self.adopt_policy_chain(
12447×
                            &resp.history,
12457×
                            sp,
12467×
                            &format!("oxy fetch {remote_name}"),
1247
                        )
12487×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1249
                    }
1250
                }
12518×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1252
            }
1253
            None => {
1254337×
                if seen.is_some() {
12550×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1256337×
                }
1257337×
                unverified = true;
1258
            }
1259
        }
1260345×
        let policy = if unverified {
1261337×
            None
1262
        } else {
12638×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1264
        };
1265345×
        let (op_ref, op) = self.head_op()?;
1266345×
        let mut view = op.view.clone();
1267345×
        let have = self.known_heads(&view)?;
1268345×
        let mut report = Vec::new();
1269345×
        let max_blob = self.config.max_blob;
1270352×
        for r in resp.refs {
1271352×
            let needed = {
1272352×
                let _t = crate::timing::phase("fetch: negotiate");
1273352×
                remote.negotiate(&have, &r.heads)?
1274
            };
1275352×
            let bundle = {
1276352×
                let _t = crate::timing::phase("fetch: bundle");
1277352×
                remote.fetch(&needed, max_blob)?
1278
            };
1279
            // Changes are not individually re-verified here: the bookmark's
1280
            // attestation (checked below) binds its whole state, and the
1281
            // receiver of the push verified the added changes at that time.
1282352×
            let imported = {
1283352×
                let _t = crate::timing::phase("fetch: import");
1284352×
                self.import_bundle(&bundle, false)?
1285
            };
1286352×
            if max_blob.is_some() {
12874×
                self.register_missing_blobs(&imported, remote_name)?;
1288348×
            }
1289482×
            for h in &r.heads {
1290482×
                if !self.store.has(h) {
12910×
                    return fail(format!("remote did not send head {}", h.short(12)));
1292482×
                }
1293
            }
1294352×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1295352×
            if state != r.state {
12960×
                return fail(format!(
1297
                    "remote state {} does not match its heads",
12980×
                    r.state.short(12)
1299
                ));
1300352×
            }
1301352×
            if let Some(p) = &policy {
13028×
                let Some(sa) = &r.attestation else {
13030×
                    return fail(format!(
1304
                        "{remote_name}/{} has no attestation, which its policy requires",
1305
                        r.name
1306
                    ));
1307
                };
13088×
                let signer = sa
13098×
                    .sigs
13108×
                    .first()
13118×
                    .map(|s| s.key)
13128×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
13138×
                if !p.authorizes(&signer, &r.name)
13140×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1315
                {
13160×
                    return fail(format!(
1317
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1318
                        r.name,
13190×
                        signer.short(12)
1320
                    ));
13218×
                }
1322344×
            }
1323352×
            if let Some(sa) = &r.attestation {
1324
                let AttestBody::Ref {
132519×
                    old_state,
132619×
                    new_state,
1327
                    ..
132819×
                } = &sa.attest.body
1329
                else {
13300×
                    return fail("remote sent a non-ref attestation for a bookmark");
1331
                };
133219×
                let (old_state, new_state) = (*old_state, *new_state);
133319×
                let serial = self
133419×
                    .check_ref_attest(
133519×
                        sa,
133619×
                        &r.name,
133719×
                        &old_state,
133819×
                        &new_state,
133919×
                        self.last_seen_serial(remote_name, &r.name),
1340
                        true,
1341
                    )
134219×
                    .map_err(|e| {
13430×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
13440×
                    })?;
134519×
                if new_state != r.state {
13460×
                    return fail(format!(
1347
                        "attestation for {}/{} does not cover its current state",
1348
                        remote_name, r.name
1349
                    ));
135019×
                }
135119×
                let ar = self.store.put_attest(&sa.attest)?;
135219×
                for sig in &sa.sigs {
135319×
                    self.store.put_signature(&ar, sig)?;
1354
                }
135519×
                self.record_serial(remote_name, &r.name, serial)?;
1356333×
            }
1357352×
            view.remotes
1358352×
                .entry(remote_name.to_string())
1359352×
                .or_default()
1360352×
                .insert(r.name.clone(), state);
1361352×
            report.push((r.name, r.heads, imported.len()));
1362
        }
1363345×
        let mut new_tags = 0;
1364345×
        for t in &resp.tags {
136510×
            if view.tags.contains_key(&t.name) {
13664×
                continue;
13676×
            }
1368
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
13696×
            let missing: Vec<ChangeHash> = t
13706×
                .heads
13716×
                .iter()
13726×
                .filter(|h| !self.store.has(h))
13736×
                .copied()
13746×
                .collect();
13756×
            if !missing.is_empty() {
13760×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
13770×
                let bundle = remote.fetch(&needed, max_blob)?;
13780×
                self.import_bundle(&bundle, false)?;
13796×
            }
13806×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
13816×
            self.adopt_tag(&mut view, t, policy.as_ref())
13826×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
13836×
            new_tags += 1;
1384
        }
1385345×
        if view != op.view {
1386335×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
138710×
        }
1388345×
        let _ = self.run_hook(
1389345×
            "post-fetch",
1390345×
            &format!(
1391
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1392345×
                json_str(remote_name),
1393352×
                json_array(report.iter().map(|(n, heads, _)| format!(
1394
                    "{{\"name\":{},\"heads\":{}}}",
1395352×
                    json_str(n),
1396482×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1397
                )))
1398
            ),
1399
        );
1400345×
        Ok(FetchReport {
1401345×
            refs: report,
1402345×
            unverified,
1403345×
            new_tags,
1404345×
        })
1405351×
    }
1406
1407
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1408
    /// the changes within `depth` steps of its heads, and the boundary below.
14091×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
14101×
        let remote = self.open_named_remote(remote_name)?;
14111×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
14121×
        let resp = remote.refs()?;
14131×
        let bookmark = self.config.bookmark.clone();
14141×
        if let Some(sp) = &resp.policy {
14150×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
14160×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
14170×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
14181×
        }
14191×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
14200×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1421
        };
14221×
        if r.heads.is_empty() {
14230×
            return Ok(0);
14241×
        }
1425
        // Base: the remote's checkpoint of exactly these heads.
14261×
        let cp_bundle = remote.checkpoint(&r.heads)?;
14271×
        let mut cp_ref = None;
14283×
        for (ty, body) in &cp_bundle.objects {
14293×
            let put = self.store.put(*ty, body)?;
14303×
            if *ty == ObjectType::Checkpoint {
14311×
                cp_ref = Some(put);
14322×
            }
1433
        }
14341×
        let Some(cp_ref) = cp_ref else {
14350×
            return fail(format!("{remote_name} sent no checkpoint"));
1436
        };
14371×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1438
        // History window.
14391×
        let wanted = remote.shallow(&r.heads, depth)?;
14401×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
14411×
        let imported = self.import_bundle_shallow(&bundle, false)?;
14421×
        if self.config.max_blob.is_some() {
14430×
            self.register_missing_blobs(&imported, remote_name)?;
14441×
        }
14451×
        self.refresh_boundary(&imported)?;
14461×
        if let Some(sa) = &r.attestation {
14470×
            let ar = self.store.put_attest(&sa.attest)?;
14480×
            for sig in &sa.sigs {
14490×
                self.store.put_signature(&ar, sig)?;
1450
            }
14510×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
14520×
                self.record_serial(remote_name, &r.name, serial)?;
14530×
            }
14541×
        }
14551×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
14561×
        let (op_ref, op) = self.head_op()?;
14571×
        let mut view = op.view.clone();
14581×
        view.remotes
14591×
            .entry(remote_name.to_string())
14601×
            .or_default()
14611×
            .insert(r.name.clone(), state);
14621×
        self.record_op(
14631×
            &[op_ref],
14641×
            &format!("oxy fetch {remote_name} --depth {depth}"),
14651×
            view,
14660×
        )?;
14671×
        Ok(imported.len())
14681×
    }
1469
1470
    /// Fetch, then take the union of the local bookmark's state with the
1471
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1472101×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1473101×
        let _wc = self.lock_working_copy()?;
1474101×
        self.fetch(remote_name)?;
147598×
        let (op_ref, op) = self.head_op()?;
147698×
        let current = self.config.bookmark.clone();
147798×
        let mut local_current = self.heads_of(&op.view, &current)?;
147898×
        local_current.sort();
147998×
        let mut view = op.view.clone();
148098×
        let mut current_heads = local_current.clone();
148198×
        let mut changed = false;
148298×
        let mut others = Vec::new();
148398×
        let tracked = op
148498×
            .view
148598×
            .remotes
148698×
            .get(remote_name)
148798×
            .cloned()
148898×
            .unwrap_or_default();
1489102×
        for (name, remote_state) in tracked {
1490
            // Every local bookmark tracks the remote's of the same name;
1491
            // the current one may be new here.
1492102×
            let local_state = op.view.bookmarks.get(&name).copied();
1493102×
            if local_state.is_none() && name != current {
14940×
                continue;
1495102×
            }
1496102×
            if local_state == Some(remote_state) {
14978×
                continue;
149894×
            }
149994×
            let local = self.heads_of(&op.view, &name)?;
150094×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1501118×
            if remote_heads.iter().all(|h| local.contains(h)) {
15020×
                continue;
150394×
            }
150494×
            let mut all = local.clone();
150594×
            all.extend(remote_heads);
150694×
            let st = self.load_state_history(&all)?;
150794×
            let mut heads = st.maximal(&all);
150894×
            heads.sort();
150994×
            let mut sorted_local = local;
151094×
            sorted_local.sort();
151194×
            if heads == sorted_local {
15121×
                continue;
151393×
            }
151493×
            view.bookmarks.insert(
151593×
                name.clone(),
151693×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1517
            );
151893×
            if name == current {
151991×
                changed = true;
152091×
                current_heads = heads;
152191×
            } else {
15222×
                others.push(name);
15232×
            }
1524
        }
152598×
        if changed || !others.is_empty() {
152692×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
15276×
        }
1528
        // The working copy follows its bookmark whenever nothing would be
1529
        // lost, also when this pull brought nothing new but it had been
1530
        // left behind (oxygen#89).
153198×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1532
        Ok(PullReport {
153398×
            heads: if changed {
153491×
                current_heads
1535
            } else {
15367×
                local_current
1537
            },
153898×
            changed,
153998×
            checked_out,
154098×
            others,
1541
        })
1542101×
    }
1543
1544
    /// How many changes the working copy's bookmark has that its base
1545
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1546
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1547
    /// the bookmark or holds changes the bookmark lacks. History is read
1548
    /// only when the base and the bookmark's heads differ (oxygen#89).
15497×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
15507×
        let (_, wc) = self.working_copy()?;
15517×
        let mut base = wc.deps.clone();
15527×
        base.sort();
15537×
        let mut heads = self.bookmark_heads()?;
15547×
        heads.sort();
15557×
        if base == heads || heads.is_empty() {
15566×
            return Ok(None);
15571×
        }
15581×
        let state = self.load_state_history(&heads)?;
15591×
        if !base.iter().all(|h| state.contains(h)) {
15600×
            return Ok(None);
15611×
        }
15621×
        let had = if base.is_empty() {
15630×
            0
1564
        } else {
15651×
            self.load_state_history(&base)?.len()
1566
        };
15671×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
15687×
    }
1569
1570
    /// Bring the working copy to `heads`, the state of its bookmark
1571
    /// `bookmark`, when nothing would be lost: its base is part of that
1572
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1573
    /// with uncommitted work, the work comes along when the new changes
1574
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1575
    /// it followed only from exactly the bookmark's old heads, so a working
1576
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1577
    /// or a pull from another workspace) never caught up, and nothing said
1578
    /// so (oxygen#74, #89). Returns whether it moved.
157998×
    pub fn follow_bookmark(
158098×
        &self,
158198×
        heads: &[ChangeHash],
158298×
        bookmark: &str,
158398×
        command: &str,
158498×
    ) -> Result<bool> {
158598×
        let snap = self.snapshot(command)?;
158698×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
158798×
        let mut base = snap.base.maximal(&snap.wc.deps);
158898×
        base.sort();
158998×
        let mut target = heads.to_vec();
159098×
        target.sort();
159198×
        if base == target {
15926×
            return Ok(false);
159392×
        }
159492×
        let state = self.load_state_history(heads)?;
1595169×
        if !base.iter().all(|h| state.contains(h)) {
1596
            // The working copy holds changes the bookmark lacks: not ours to move.
15970×
            return Ok(false);
159892×
        }
159992×
        if clean {
160092×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
160192×
            Ok(true)
1602
        } else {
16030×
            Ok(self
16040×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
16050×
                .is_ok())
1606
        }
160798×
    }
1608
1609
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1610
    /// changes and attesting the reference when a key is available.
1611
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1612
    /// state, attested when we have an identity. The local bookmark, if
1613
    /// any, is kept; only the remote-tracking entry goes.
16145×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
16155×
        let remote = self.open_named_remote(remote_name)?;
16165×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
16175×
        let resp = remote.refs()?;
16187×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
16191×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1620
        };
16214×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
16220×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
16234×
        }
16244×
        let attestation = match self.secret_key()? {
16252×
            Some(_) => Some(self.sign_attest(&Attest {
16262×
                repo: self.id()?,
16272×
                hlc: Hlc::now(),
16282×
                body: AttestBody::Ref {
16292×
                    name: bookmark.to_string(),
16302×
                    old_state: r.state,
16312×
                    new_state: ObjectRef::ZERO,
16322×
                    serial: r.last_serial.unwrap_or(0) + 1,
16332×
                },
16340×
            })?),
16352×
            None => None,
1636
        };
16374×
        let results = remote.push(
16384×
            Bundle::default(),
16394×
            vec![RefUpdate {
16404×
                name: bookmark.to_string(),
16414×
                old_state: r.state,
16424×
                new_state: ObjectRef::ZERO,
16434×
                force: true,
16444×
                attestation,
16454×
            }],
16464×
            None,
16474×
            vec![],
16480×
        )?;
16494×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
16502×
            let (op_ref, op) = self.head_op()?;
16512×
            let mut view = op.view.clone();
16522×
            if let Some(m) = view.remotes.get_mut(remote_name) {
16532×
                m.remove(bookmark);
16542×
            }
16552×
            self.record_op(
16562×
                &[op_ref],
16572×
                &format!("oxy push {remote_name} --delete {bookmark}"),
16582×
                view,
16590×
            )?;
16602×
        }
16614×
        Ok(results)
16625×
    }
1663
1664
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1665
    /// repository's config (its URL, token, CA and store settings), its
1666
    /// tracking bookmarks in the view, and a store remote's mirror under
1667
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
16683×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
16693×
        if !self.config.remotes.contains_key(name) {
16701×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
16712×
        }
16722×
        let prefix = format!("remote.{name}.");
16732×
        let keys: Vec<String> = self
16742×
            .config
16752×
            .repo_layer()
16762×
            .keys()
16774×
            .filter(|k| k.starts_with(&prefix))
16782×
            .cloned()
16792×
            .collect();
16803×
        for k in keys {
16813×
            self.config.set(&k, "")?;
1682
        }
16832×
        self.config.remotes.remove(name);
16842×
        self.save_config()?;
16852×
        let (op_ref, op) = self.head_op()?;
16862×
        if op.view.remotes.contains_key(name) {
16871×
            let mut view = op.view.clone();
16881×
            view.remotes.remove(name);
16891×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
16901×
        }
16912×
        let mirror = self.oxy.join("remotes").join(name);
16922×
        if mirror.is_dir() {
16930×
            fs::remove_dir_all(&mirror)?;
16942×
        }
16952×
        Ok(())
16963×
    }
1697
1698
    /// `changes`, in dependency order, cut into batches of about
1699
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1700
    /// There is always one, perhaps empty.
1701272×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1702272×
        let blob_len = |r: &ObjectRef| -> u64 {
170329×
            self.store
170429×
                .get_typed(r, ObjectType::Blob)
170529×
                .ok()
170629×
                .and_then(|b| Blob::decode(&b).ok())
170729×
                .map_or(0, |b| b.length)
170829×
        };
1709272×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1710378×
        for h in changes {
1711378×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1712378×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1713378×
            let mut weight = raw.len() as u64;
1714491×
            for t in &texts {
1715491×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
171626×
                    weight += blob_len(r);
1717465×
                }
1718
            }
1719618×
            for e in &c.edits {
17203×
                if let Edit::Replace { new: Some(b), .. } = e {
17213×
                    weight += blob_len(b);
1722615×
                }
1723
            }
1724378×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
17255×
                out.push(std::mem::take(&mut batch));
17265×
                bytes = 0;
1727373×
            }
1728378×
            batch.push(*h);
1729378×
            bytes += weight;
1730
        }
1731272×
        out.push(batch);
1732272×
        Ok(out)
1733272×
    }
1734
1735339×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1736339×
        let bookmark = self.config.bookmark.clone();
1737339×
        self.push_bookmark(remote_name, &bookmark, force)
1738339×
    }
1739
1740
    /// `push` for a named bookmark (`oxy push -b NAME`).
1741347×
    pub fn push_bookmark(
1742347×
        &self,
1743347×
        remote_name: &str,
1744347×
        bookmark: &str,
1745347×
        force: bool,
1746347×
    ) -> Result<Vec<RefResult>> {
1747347×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1748347×
    }
1749
1750
    /// `push_bookmark`, saying how a long push is going: one line per
1751
    /// batch sent (oxygen#95).
1752355×
    pub fn push_bookmark_with(
1753355×
        &self,
1754355×
        remote_name: &str,
1755355×
        bookmark: &str,
1756355×
        force: bool,
1757355×
        progress: crate::store::Progress,
1758355×
    ) -> Result<Vec<RefResult>> {
1759355×
        let (op_ref, op) = self.head_op()?;
1760355×
        if !op.view.bookmarks.contains_key(bookmark) {
17610×
            return fail(format!("no bookmark {bookmark}"));
1762355×
        }
1763355×
        let bookmark = bookmark.to_string();
1764355×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1765
        // pre-push hook: may veto before the remote is contacted.
1766355×
        self.run_hook(
1767355×
            "pre-push",
1768355×
            &format!(
1769
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1770355×
                json_str(remote_name),
1771355×
                json_str(&bookmark),
1772710×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1773
            ),
17741×
        )?;
1775354×
        let remote = self.open_named_remote(remote_name)?;
1776354×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1777351×
        let resp = remote.refs()?;
1778351×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1779351×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1780351×
        let policy_to_send = match (&local_policy, &resp.policy) {
178119×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
17828×
            (Some(l), None) => Some(l.clone()),
17839×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
17841×
                return fail(format!(
1785
                    "{remote_name} has a newer policy (serial {}); fetch first",
1786
                    r.policy.serial
1787
                ));
1788
            }
1789332×
            _ => None,
1790
        };
1791350×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1792350×
        if remote_has_policy && self.secret_key()?.is_none() {
17931×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1794349×
        }
1795349×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1796349×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1797349×
            .tag_refs()?
1798349×
            .into_iter()
1799349×
            .filter(|t| !remote_tags.contains(&t.name))
1800349×
            .collect();
1801349×
        let refs = resp.refs;
1802349×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1803349×
        let (remote_state, remote_heads, last_serial) =
1804349×
            match refs.iter().find(|r| r.name == bookmark) {
1805332×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
180617×
                None => (empty, vec![], None),
1807
            };
1808349×
        let new_state = self
1809349×
            .store
1810349×
            .put_state(&StateObject::new(local_heads.clone()))?;
1811
        // A push that carries a policy re-attests the bookmark even when its
1812
        // state is unchanged, so the current attestation is always by a key
1813
        // the current policy authorizes (a revoked key's attestation would
1814
        // otherwise be refused by every later fetch).
1815349×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
18167×
            return Ok(vec![RefResult {
18177×
                name: bookmark,
18187×
                ok: true,
18197×
                reason: "already up to date".into(),
18207×
            }]);
1821342×
        }
1822381×
        for h in &remote_heads {
1823381×
            if !self.store.has(h) {
182469×
                return fail(format!(
1825
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
182669×
                    h.short(12)
1827
                ));
1828312×
            }
1829
        }
1830273×
        if !force {
1831273×
            let closure = self.closure_in_store(&local_heads)?;
1832292×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
18330×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1834273×
            }
18350×
        }
1836273×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1837273×
        let key = self.secret_key()?.map(|(k, _)| k);
1838273×
        if let Some(key) = key {
1839
            // Seal this author's changes that carry no valid authenticator,
1840
            // and adopt anonymous ones (zero author, spec §14.4). The seals
1841
            // are stored, so each batch's bundle carries those it needs.
184275×
            let mut unsigned = Vec::new();
184375×
            for h in &to_send {
184470×
                let c = self.store.get_change_meta(h)?;
184570×
                if (c.author == key || c.author.is_zero())
184666×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
184738×
                {
184838×
                    unsigned.push(*h);
184938×
                }
1850
            }
185175×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
185235×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1853
            }
1854198×
        }
1855
        // A long history goes in batches, in dependency order, so neither
1856
        // side holds it whole and no request passes the remote's limit:
1857
        // all but the last carry objects alone; the last moves the bookmark
1858
        // (oxygen#95).
1859272×
        let batches = self.push_batches(&to_send)?;
1860272×
        let (last, earlier) = batches.split_last().expect("at least one batch");
1861272×
        for (i, batch) in earlier.iter().enumerate() {
18625×
            progress(&format!(
18635×
                "part {} of {}: {} changes",
18645×
                i + 1,
18655×
                batches.len(),
18665×
                batch.len()
18675×
            ));
18685×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
18695×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
18705×
                Some(r) if r.ok => {}
18710×
                Some(r) => {
18720×
                    return fail(format!(
1873
                        "{remote_name} refused part {} of the push: {}",
18740×
                        i + 1,
1875
                        r.reason
1876
                    ))
1877
                }
1878
                None => {
18790×
                    return fail(format!(
1880
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
1881
                    ))
1882
                }
1883
            }
1884
        }
1885272×
        if batches.len() > 1 {
18861×
            progress(&format!(
18871×
                "part {} of {}: {} changes",
18881×
                batches.len(),
18891×
                batches.len(),
18901×
                last.len()
18911×
            ));
1892271×
        }
1893272×
        let mut bundle = self.bundle_for(last)?;
1894272×
        bundle.objects.push((
1895272×
            ObjectType::State,
1896272×
            StateObject::new(local_heads.clone()).encode(),
1897272×
        ));
1898272×
        let attestation = match key {
189974×
            Some(_) => Some(self.sign_attest(&Attest {
190074×
                repo: self.id()?,
190174×
                hlc: Hlc::now(),
190274×
                body: AttestBody::Ref {
190374×
                    name: bookmark.clone(),
190474×
                    old_state: remote_state,
190574×
                    new_state,
190674×
                    serial: next_serial(last_serial),
190774×
                },
19081×
            })?),
1909198×
            None => None,
1910
        };
1911
        // Whoever signed the move, and whom a delegate acts for, travel with
1912
        // it: a receiver that has never seen a change by this delegate could
1913
        // not otherwise check its signature (oxygenhub#129).
1914271×
        if attestation.is_some() {
1915146×
            for k in [self.signing_key(), self.config.author_key]
191673×
                .into_iter()
191773×
                .flatten()
1918
            {
1919146×
                if let Ok(id) = self.identity(&k) {
1920146×
                    let body = id.encode();
1921146×
                    if !bundle
1922146×
                        .objects
1923146×
                        .iter()
1924170×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
192514×
                    {
192614×
                        bundle.objects.push((ObjectType::Identity, body));
1927132×
                    }
19280×
                }
1929
            }
1930198×
        }
1931271×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
193273×
            AttestBody::Ref { serial, .. } => Some(serial),
19330×
            _ => None,
193473×
        });
1935271×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1936
        // Tag states must be present on the remote: bundle their changes too.
1937271×
        for t in &tags_to_send {
19386×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
19396×
            let extra: Vec<ChangeHash> =
19406×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
19416×
            if !extra.is_empty() {
19420×
                let more = self.bundle_for(&extra)?;
19430×
                bundle.changes.extend(more.changes);
19440×
                bundle.hashes.extend(more.hashes);
19450×
                bundle.attests.extend(more.attests);
19460×
                bundle.objects.extend(more.objects);
19476×
            }
19486×
            bundle.objects.push((
19496×
                ObjectType::State,
19506×
                StateObject::new(t.heads.clone()).encode(),
19516×
            ));
1952
        }
1953271×
        if let Some(l) = &policy_to_send {
195418×
            let remote_serial = resp_policy_serial;
195518×
            bundle.policies = self
195618×
                .policy_history()?
195718×
                .into_iter()
195842×
                .filter(|sp| {
195942×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
196020×
                        && sp.policy.serial < l.policy.serial
196142×
                })
196218×
                .collect();
1963253×
        }
1964271×
        let results = remote.push(
1965271×
            bundle,
1966271×
            vec![RefUpdate {
1967271×
                name: bookmark.clone(),
1968271×
                old_state: remote_state,
1969271×
                new_state,
1970271×
                force,
1971271×
                attestation,
1972271×
            }],
1973271×
            policy_to_send,
1974271×
            tags_to_send,
19757×
        )?;
197618×
        if let (Some(serial), true) = (
1977264×
            sent_serial,
1978270×
            results.iter().any(|r| r.ok && r.name == "policy"),
1979
        ) {
198018×
            self.record_policy_serial(remote_name, serial)?;
1981246×
        }
1982282×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1983250×
            let mut view = op.view.clone();
1984250×
            view.remotes
1985250×
                .entry(remote_name.to_string())
1986250×
                .or_default()
1987250×
                .insert(bookmark.clone(), new_state);
1988250×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1989247×
            if let Some(s) = serial {
199057×
                self.record_serial(remote_name, &bookmark, s)?;
1991190×
            }
199214×
        }
1993259×
        Ok(results)
1994355×
    }
1995
1996
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1997
    /// bookmark set to the remote's, working copy checked out.
1998226×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1999226×
        Self::clone_with(url, dest, None, &[])
2000226×
    }
2001
2002
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2003
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2004
    /// unless a size is given, so out-of-scope binaries are never fetched).
2005234×
    pub fn clone_with(
2006234×
        url: &str,
2007234×
        dest: &Path,
2008234×
        max_blob: Option<u64>,
2009234×
        sparse: &[String],
2010234×
    ) -> Result<Repo> {
2011234×
        Self::clone_full(url, dest, max_blob, sparse, None)
2012234×
    }
2013
2014
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2015
    /// changes within `depth` steps of them; the rest is the boundary.
20161×
    pub fn clone_shallow(
20171×
        url: &str,
20181×
        dest: &Path,
20191×
        depth: u32,
20201×
        max_blob: Option<u64>,
20211×
        sparse: &[String],
20221×
    ) -> Result<Repo> {
20231×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
20241×
    }
2025
2026235×
    fn clone_full(
2027235×
        url: &str,
2028235×
        dest: &Path,
2029235×
        max_blob: Option<u64>,
2030235×
        sparse: &[String],
2031235×
        depth: Option<u32>,
2032235×
    ) -> Result<Repo> {
2033235×
        let options = crate::credentials::Credentials::user().options_for(url);
2034235×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2035235×
    }
2036
2037
    /// Clone a subrepo with the credentials the parent would use for its
2038
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2039
    /// subrepo: it finds the same ones again through its parent.
20409×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
20419×
        let options = self.credentials_for(url);
20429×
        Self::clone_using(url, dest, None, &[], None, &options)
20439×
    }
2044
2045
    /// The name of a remote of this repository on the same hub (scheme,
2046
    /// host and port) as `url`.
204721×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
204825×
        let origin = |u: &str| -> Option<String> {
204925×
            let (scheme, rest) = u.split_once("://")?;
20508×
            if !matches!(scheme, "http" | "https") {
20510×
                return None;
20528×
            }
20538×
            let host = rest.split('/').next()?;
20548×
            Some(format!(
20558×
                "{}://{}",
20568×
                scheme.to_ascii_lowercase(),
20578×
                host.to_ascii_lowercase()
20588×
            ))
205925×
        };
206021×
        let want = origin(url)?;
20614×
        self.config
20624×
            .remotes
20634×
            .iter()
20644×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
20654×
            .map(|(name, _)| name.clone())
206621×
    }
2067
2068
    /// The token and CA to reach `url` with: those of a remote of this
2069
    /// repository on the same hub (scheme, host and port), else the
2070
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2071
    /// and enclosing checkouts', as a clone would use them.
207221×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
207321×
        match self.remote_on_same_hub(url) {
20741×
            Some(name) => RemoteOptions {
20751×
                repo_id: None,
20761×
                cache_dir: None,
20771×
                ..self.remote_options(&name)
20781×
            },
2079
            None => {
208020×
                let mut options = RemoteOptions::default();
208120×
                self.fill_credentials(url, &mut options);
208220×
                options
2083
            }
2084
        }
208521×
    }
2086
2087244×
    fn clone_using(
2088244×
        url: &str,
2089244×
        dest: &Path,
2090244×
        max_blob: Option<u64>,
2091244×
        sparse: &[String],
2092244×
        depth: Option<u32>,
2093244×
        options: &RemoteOptions,
2094244×
    ) -> Result<Repo> {
2095244×
        let remote = open_remote(url, options)?;
2096244×
        let id = remote.repo_id()?;
2097240×
        if id == crate::protocol::UNBOUND_ID {
20982×
            return fail(format!(
2099
                "{url} is empty and unbound: push a repository to it first"
2100
            ));
2101238×
        }
2102238×
        let mut repo = Repo::init_with_id(dest, id)?;
2103238×
        repo.config
2104238×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2105238×
        if let Some(m) = max_blob {
21062×
            repo.config.set("filter.max-blob", &m.to_string())?;
2107236×
        } else if !sparse.is_empty() {
21081×
            repo.config.set("filter.max-blob", "0")?;
2109235×
        }
2110238×
        if !sparse.is_empty() {
21111×
            repo.config.set("filter.paths", &sparse.join(","))?;
2112237×
        }
2113238×
        repo.save_config()?;
2114238×
        if let Some(depth) = depth {
21151×
            repo.fetch_shallow("origin", depth)?;
2116
        } else {
2117237×
            repo.fetch("origin")?;
2118
        }
2119237×
        let (op_ref, op) = repo.head_op()?;
2120
        // The remote's default bookmark, else ours (main), else its only one.
2121237×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2122
        // Asked of the remote as now configured, so a store-backed one
2123
        // answers from the mirror the fetch just filled.
2124237×
        let advertised = repo
2125237×
            .open_named_remote("origin")
2126237×
            .ok()
2127237×
            .and_then(|r| r.refs().ok())
2128237×
            .and_then(|r| r.default_bookmark);
2129237×
        let bookmark = advertised
2130237×
            .filter(|b| theirs.contains_key(b))
2131237×
            .or_else(|| {
21327×
                theirs
21337×
                    .contains_key(&repo.config.bookmark)
21347×
                    .then(|| repo.config.bookmark.clone())
21357×
            })
2136237×
            .or_else(|| {
21370×
                (theirs.len() == 1)
21380×
                    .then(|| theirs.keys().next().cloned())
21390×
                    .flatten()
21400×
            })
2141237×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2142237×
        let initial = repo.config.bookmark.clone();
2143237×
        if bookmark != repo.config.bookmark {
21441×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
21451×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
21461×
            repo.config.bookmark = bookmark.clone();
2147236×
        }
2148237×
        if let Some(state) = theirs.get(&bookmark).copied() {
2149237×
            let heads = repo.store.get_state(&state)?.heads;
2150237×
            let mut view = op.view.clone();
2151
            // The empty bookmark `init` made goes when another is checked out.
2152237×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
21531×
                view.bookmarks.remove(&initial);
2154236×
            }
2155237×
            view.bookmarks.insert(bookmark, state);
2156237×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2157237×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
21580×
        }
2159237×
        Ok(repo)
2160244×
    }
2161
}
2162
2163
/// The serial of a reference's next attestation: one more than the last the
2164
/// remote reports, or, for a bookmark the remote does not have, the clock in
2165
/// milliseconds, so a bookmark created again after a deletion goes past the
2166
/// deletion's serial the remote keeps.
216774×
fn next_serial(last: Option<u64>) -> u64 {
216874×
    match last {
216946×
        Some(l) => l + 1,
217028×
        None => Hlc::now().wall_ms.max(1),
2171
    }
217274×
}