OXYGENHUB

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

1489 of 1671 lines run, 213 of 304 functions · run #263 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
541261×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551261×
        self.oxy.join("attest").join(name_file(bookmark))
561261×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591187×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601187×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61195×
            Ok(h) => {
62195×
                let r = ObjectRef::from_hex(h.trim())
63195×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65195×
                    r,
66
                    SignedAttest {
67195×
                        attest: self.store.get_attest(&r)?,
68195×
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
71
            }
72992×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751187×
    }
76
7774×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7874×
        fs::create_dir_all(self.oxy.join("attest"))?;
7974×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8074×
    }
81
82980×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
83980×
        let view = self.view()?;
84980×
        let mut out = Vec::new();
851002×
        for (name, state) in &view.bookmarks {
861002×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
871002×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88104×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90104×
            });
911002×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
921002×
            out.push(RemoteRef {
931002×
                name: name.clone(),
941002×
                state: *state,
951002×
                heads: self.store.get_state(state)?.heads,
961002×
                attestation,
971002×
                last_serial,
98
            });
99
        }
100980×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
101980×
        let history = self
102980×
            .policy_history()?
103980×
            .into_iter()
104980×
            .filter(|sp| {
10566×
                policy
10666×
                    .as_ref()
10766×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10866×
            })
109980×
            .collect();
110
        Ok(RefsResponse {
111980×
            refs: out,
112980×
            policy,
113980×
            tags: self.tag_refs()?,
114980×
            history,
115980×
            default_bookmark: Some(self.config.bookmark.clone()),
116
        })
117980×
    }
118
119
    /// Every change reachable from `heads` that is in the store.
1201282×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1211282×
        let mut seen = BTreeSet::new();
1221282×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1234501×
        while let Some(h) = stack.pop() {
1243219×
            if seen.contains(&h) || !self.store.has(&h) {
125931×
                continue;
1262288×
            }
1272288×
            seen.insert(h);
1282288×
            stack.extend(self.store.get_change_meta(&h)?.deps);
129
        }
1301282×
        Ok(seen)
1311282×
    }
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
1581856×
    fn shallow_path(&self) -> PathBuf {
1591856×
        self.oxy.join("shallow")
1601856×
    }
161
162
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1631853×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1641853×
        fs::read_to_string(self.shallow_path())
1651853×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1661853×
            .unwrap_or_default()
1671853×
    }
168
169176×
    pub fn is_shallow(&self) -> bool {
170176×
        !self.boundary().is_empty()
171176×
    }
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).
218732×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
219732×
        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.
222732×
        let boundary = self.boundary();
223732×
        let mut out = Vec::new();
224732×
        let mut done: BTreeSet<ChangeHash> = have.clone();
225732×
        done.extend(boundary.iter().copied());
226
        // Iterative post-order DFS.
2271164×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2283065×
        while let Some((h, expanded)) = stack.pop() {
2292333×
            if done.contains(&h) {
230393×
                continue;
2311940×
            }
2321940×
            if !self.store.has(&h) {
2330×
                return fail(format!("change {} is not in this repository", h.short(12)));
2341940×
            }
2351940×
            if expanded {
236970×
                done.insert(h);
237970×
                out.push(h);
238970×
                continue;
239970×
            }
240970×
            stack.push((h, true));
241970×
            for d in self.store.get_change_meta(&h)?.deps {
242678×
                if !done.contains(&d) {
243199×
                    stack.push((d, false));
244479×
                }
245
            }
246
        }
247732×
        Ok(out)
248732×
    }
249
250
    /// Bundle changes (in the given dependency order) with their signatures,
251
    /// seals, identities, blobs, chunks.
252287×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
253287×
        self.bundle_for_filtered(changes, None)
254287×
    }
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).
279332×
    pub fn bundle_for_filtered(
280332×
        &self,
281332×
        changes: &[ChangeHash],
282332×
        max_blob: Option<u64>,
283332×
    ) -> Result<Bundle> {
284332×
        self.bundle_of(changes, max_blob, false)
285332×
    }
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.
291315×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
292315×
        self.bundle_of(changes, max_blob, true)
293315×
    }
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();
304982×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
305982×
            if !r.is_zero() && self.store.has(r) {
306166×
                objects.insert(*r);
307816×
            }
308982×
        };
309901×
        for h in changes {
310
            // Raw: the stored bytes, and a skeleton for the rest.
311901×
            let (c, encoded) = if raw {
312482×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
313482×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3144955×
                for t in texts {
3154955×
                    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);
3194952×
                    }
320
                }
321482×
                (skel, Some(bytes))
322
            } else {
323419×
                (self.store.get_change(h)?, None)
324
            };
325901×
            let sigs = self.store.signatures(h)?;
326901×
            add_object(&c.author, &mut objects);
327901×
            for s in &sigs {
32820×
                add_object(&s.key, &mut objects);
32920×
            }
3305913×
            for e in &c.edits {
3315913×
                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
                    }
3455901×
                }
346
            }
347901×
            for s in self.store.seals_for(h)? {
34865×
                seals.insert(s);
34965×
            }
350901×
            match encoded {
351482×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
352419×
                None => {
353419×
                    bundle.changes.push((c, sigs));
354419×
                    bundle.hashes.push(*h);
355419×
                }
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 {
367103×
            let (ty, body) = self.store.get(&r)?;
368103×
            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).
375690×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
376690×
        self.import_bundle_inner(bundle, strict, false)
377690×
    }
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
385693×
    fn import_bundle_inner(
386693×
        &self,
387693×
        bundle: &Bundle,
388693×
        strict: bool,
389693×
        shallow: bool,
390693×
    ) -> Result<Vec<ChangeHash>> {
391693×
        let batch = self.store.begin_batch()?;
392693×
        let result = self.import_bundle_batched(bundle, strict, shallow);
393693×
        batch.finish()?;
394691×
        result
395693×
    }
396
397693×
    fn import_bundle_batched(
398693×
        &self,
399693×
        bundle: &Bundle,
400693×
        strict: bool,
401693×
        shallow: bool,
402693×
    ) -> Result<Vec<ChangeHash>> {
403693×
        for (ty, _) in &bundle.objects {
4040×
            if !matches!(
405448×
                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()));
413448×
            }
414
        }
415
        // All at once: in a large batch they are compressed on every core.
416693×
        let objects: Vec<(ObjectType, &[u8])> = bundle
417693×
            .objects
418693×
            .iter()
419693×
            .map(|(ty, body)| (*ty, body.as_slice()))
420693×
            .collect();
421693×
        self.store.put_many(&objects)?;
422693×
        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).
436693×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
437684×
            bundle.hashes.clone()
438
        } else {
4399×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
440
        };
441693×
        let raw_hashes: Vec<ChangeHash> = bundle
442693×
            .raw_changes
443693×
            .iter()
444693×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
445693×
            .collect();
446693×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
447693×
        let boundary = self.boundary();
448693×
        let mut imported = Vec::new();
449
        // Changes as stored: checked, then stored as they are, their text
450
        // blobs having come with the objects.
451693×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
452483×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
453483×
            for d in &skel.deps {
454357×
                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
                    ));
461357×
                }
462
            }
4634956×
            for t in texts {
4644956×
                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×
                    }
4724952×
                }
473
            }
474482×
            self.store.put(ObjectType::Change, bytes)?;
475482×
            for sig in sigs {
4764×
                self.store.put_signature(&h, sig)?;
477
            }
478482×
            imported.push(h);
479
        }
480692×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
481448×
            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
            }
491445×
            let stored = self.store.put_change(c)?;
492445×
            if stored != h {
4930×
                return fail(format!(
494
                    "change {} is not the change the bundle names",
4950×
                    h.short(12)
496
                ));
497445×
            }
498445×
            for sig in sigs {
49925×
                self.store.put_signature(&h, sig)?;
500
            }
501445×
            imported.push(h);
502
        }
503689×
        if strict {
50428×
            for h in &imported {
50519×
                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
                    ));
51018×
                }
511
            }
512661×
        }
513688×
        Ok(imported)
514693×
    }
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.
5246×
    pub(crate) fn delegate_authorized(
5256×
        &self,
5266×
        p: &crate::policy::Policy,
5276×
        signer: &KeyId,
5286×
        reference: &str,
5296×
        at_ms: u64,
5306×
    ) -> bool {
5316×
        if p.is_revoked(signer) {
5321×
            return false;
5335×
        }
5345×
        let Some(rule) = p.rule_for(reference) else {
5350×
            return false;
536
        };
5376×
        rule.keys.iter().any(|k| {
5386×
            !p.is_revoked(k)
5396×
                && p.identity(k)
5406×
                    .cloned()
5416×
                    .or_else(|| self.store.get_identity(k).ok())
5426×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
5436×
        })
5446×
    }
545
54693×
    fn check_ref_attest(
54793×
        &self,
54893×
        sa: &SignedAttest,
54993×
        name: &str,
55093×
        old_state: &ObjectRef,
55193×
        new_state: &ObjectRef,
55293×
        last_serial: Option<u64>,
55393×
        allow_equal: bool,
55493×
    ) -> std::result::Result<u64, String> {
555
        let AttestBody::Ref {
55693×
            name: n,
55793×
            old_state: o,
55893×
            new_state: nw,
55993×
            serial,
56093×
        } = &sa.attest.body
561
        else {
5620×
            return Err("attestation is not a ref attestation".into());
563
        };
56493×
        if n != name || o != old_state || nw != new_state {
5651×
            return Err("attestation does not describe this update".into());
56692×
        }
56792×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
5680×
            return Err("attestation is for a different repository".into());
56992×
        }
57092×
        if let Some(last) = last_serial {
57159×
            if *serial < last || (*serial == last && !allow_equal) {
5721×
                return Err(format!(
5731×
                    "attestation serial {serial} is not greater than the last seen {last}"
5741×
                ));
57558×
            }
57633×
        }
57791×
        let r = sa.attest.hash();
57891×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
57991×
        let id = self
58091×
            .store
58191×
            .get_identity(&sig.key)
58291×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
58391×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
58491×
        Ok(*serial)
58593×
    }
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.
592270×
    pub fn receive_push(
593270×
        &self,
594270×
        bundle: Bundle,
595270×
        updates: Vec<RefUpdate>,
596270×
        policy: Option<SignedPolicy>,
597270×
        tags: Vec<crate::protocol::TagRef>,
598270×
    ) -> Result<Vec<RefResult>> {
599270×
        Ok(self
600270×
            .receive_push_report(bundle, updates, policy, tags)?
601
            .results)
602270×
    }
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).
607306×
    pub fn receive_push_report(
608306×
        &self,
609306×
        bundle: Bundle,
610306×
        updates: Vec<RefUpdate>,
611306×
        policy: Option<SignedPolicy>,
612306×
        tags: Vec<crate::protocol::TagRef>,
613306×
    ) -> Result<PushReport> {
614306×
        let mut report = PushReport::default();
615306×
        let results = &mut report.results;
616306×
        if let Some(sp) = policy {
61718×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
61816×
                Ok(()) => {
61916×
                    results.push(RefResult {
62016×
                        name: "policy".into(),
62116×
                        ok: true,
62216×
                        reason: format!("serial {}", sp.policy.serial),
62316×
                    });
62416×
                }
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
            }
641288×
        }
642304×
        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`.
645304×
        let objects_only = updates.is_empty() && tags.is_empty();
646304×
        match self.import_bundle(&bundle, policy.is_some()) {
647301×
            Ok(imported) => {
648301×
                if objects_only {
6497×
                    results.push(RefResult {
6507×
                        name: OBJECTS_RESULT.into(),
6517×
                        ok: true,
6527×
                        reason: format!("{} changes stored", imported.len()),
6537×
                    });
654294×
                }
655301×
                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
        }
675301×
        let (op_ref, op) = self.head_op()?;
676301×
        let mut view = op.view.clone();
677301×
        let mut names = Vec::new();
678301×
        for u in updates {
679292×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
680292×
            let (ok, reason) = match outcome {
681271×
                Ok(()) => (true, String::new()),
68221×
                Err(e) => (false, e),
683
            };
684292×
            if ok {
685271×
                names.push(u.name.clone());
686271×
                let heads = self
687271×
                    .store
688271×
                    .get_state(&u.new_state)
689271×
                    .map(|s| s.heads)
690271×
                    .unwrap_or_default();
691271×
                report.updated.push(RefUpdated {
692271×
                    name: u.name.clone(),
693271×
                    old_state: u.old_state,
694271×
                    new_state: u.new_state,
695271×
                    heads,
696271×
                });
69721×
            }
698292×
            results.push(RefResult {
699292×
                name: u.name,
700292×
                ok,
701292×
                reason,
702292×
            });
703
        }
704301×
        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
        }
734301×
        if !names.is_empty() {
735271×
            self.record_op(
736271×
                &[op_ref],
737271×
                &format!("push received: {}", names.join(" ")),
738271×
                view,
7393×
            )?;
74030×
        }
741298×
        Ok(report)
742306×
    }
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.
74874×
    fn record_update_attest(
74974×
        &self,
75074×
        u: &RefUpdate,
75174×
        sa: &SignedAttest,
75274×
    ) -> std::result::Result<(), String> {
75374×
        let name = &u.name;
75474×
        let last = self
75574×
            .latest_ref_attest(name)
75674×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
75774×
            .and_then(|(_, a)| match a.attest.body {
75849×
                AttestBody::Ref { serial, .. } => Some(serial),
7590×
                _ => None,
76049×
            });
76174×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
76272×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
76372×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
76471×
        for sig in &sa.sigs {
76571×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
766
        }
76771×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
76874×
    }
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
824292×
    fn apply_update(
825292×
        &self,
826292×
        view: &mut View,
827292×
        u: &RefUpdate,
828292×
        policy: Option<&crate::policy::Policy>,
829292×
    ) -> std::result::Result<(), String> {
830292×
        if u.name == "policy" {
8310×
            return Err(
8320×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
8330×
            );
834292×
        }
835292×
        let empty = self
836292×
            .store
837292×
            .put_state(&StateObject::new(vec![]))
838292×
            .map_err(|e| e.to_string())?;
839292×
        if u.new_state.is_zero() {
8403×
            return self.apply_deletion(view, u, policy);
841289×
        }
842289×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
843289×
        if current != u.old_state {
8446×
            return Err("stale: the remote bookmark has moved; pull first".into());
845283×
        }
846283×
        let new_state = self
847283×
            .store
848283×
            .get_state(&u.new_state)
849283×
            .map_err(|_| "new state object is missing".to_string())?;
850552×
        for h in &new_state.heads {
851552×
            if !self.store.has(h) {
8521×
                return Err(format!("head {} is missing", h.short(12)));
853551×
            }
854
        }
855282×
        if !u.force {
856281×
            let old_heads = self
857281×
                .store
858281×
                .get_state(&current)
859281×
                .map_err(|e| e.to_string())?
860
                .heads;
861281×
            let closure = self
862281×
                .closure_in_store(&new_state.heads)
863281×
                .map_err(|e| e.to_string())?;
864307×
            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×
                ));
869280×
            }
8701×
        }
871281×
        if let Some(p) = policy {
87226×
            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
            };
87825×
            let signer = sa
87925×
                .sigs
88025×
                .first()
88125×
                .map(|s| s.key)
88225×
                .ok_or("attestation carries no signature")?;
88325×
            if !p.authorizes(&signer, &u.name)
8846×
                && !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×
                ));
89120×
            }
89220×
            let old_heads = self
89320×
                .store
89420×
                .get_state(&current)
89520×
                .map_err(|e| e.to_string())?
896
                .heads;
89720×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
898255×
        }
899275×
        if let Some(sa) = &u.attestation {
90073×
            self.record_update_attest(u, sa)?;
901202×
        }
902269×
        view.bookmarks.insert(u.name.clone(), u.new_state);
903269×
        Ok(())
904292×
    }
905
906
    // ------------------------------------------------------------ client side
907
908958×
    fn remote_url(&self, name: &str) -> Result<String> {
909958×
        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×
        })
925958×
    }
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).
930714×
    fn check_remote_id(
931714×
        &self,
932714×
        remote: &dyn crate::protocol::Remote,
933714×
        remote_name: &str,
934714×
        allow_unbound: bool,
935714×
    ) -> Result<()> {
936714×
        let theirs = remote.repo_id()?;
937713×
        if theirs == self.id()? {
938692×
            return Ok(());
93921×
        }
94021×
        if theirs == crate::protocol::UNBOUND_ID {
94118×
            if allow_unbound {
94217×
                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
        ))
951714×
    }
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`]).
956974×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
957974×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
958974×
        let mut options = RemoteOptions {
959974×
            repo_id: self.id().ok(),
960974×
            token: self.config.remote_tokens.get(name).cloned(),
961974×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
962974×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
963974×
        };
964974×
        self.fill_credentials(&url, &mut options);
965974×
        options
966974×
    }
967
968
    /// The user's credential store (`credentials.toml` beside the user
969
    /// configuration file).
970991×
    pub fn credentials(&self) -> crate::credentials::Credentials {
971991×
        crate::credentials::Credentials::at(
972991×
            self.user_config
973991×
                .parent()
974991×
                .map(Path::to_path_buf)
975991×
                .unwrap_or_else(default_home),
976
        )
977991×
    }
978
979
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
980
    /// then the user's credential store for its hub, then a remote on the
981
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
982992×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
983992×
        if options.token.is_some() && options.ca.is_some() {
9841×
            return;
985991×
        }
986991×
        let stored = self.credentials().options_for(url);
987991×
        options.token = options.token.take().or(stored.token);
988991×
        options.ca = options.ca.take().or(stored.ca);
989991×
        if options.token.is_some() && options.ca.is_some() {
9900×
            return;
991991×
        }
992991×
        let Some(hub) = crate::credentials::hub_of(url) else {
993862×
            return;
994
        };
995129×
        let mut at = self.root.parent();
996514×
        while let Some(dir) = at {
997385×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
9980×
                break;
999
            };
1000385×
            for (key, remote_url) in &cfg {
10015×
                let Some(name) = key
10025×
                    .strip_prefix("remote.")
10035×
                    .and_then(|k| k.strip_suffix(".url"))
1004
                else {
10052×
                    continue;
1006
                };
10073×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
10081×
                    continue;
10092×
                }
10102×
                if options.token.is_none() {
10112×
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
10122×
                }
10132×
                if options.ca.is_none() {
10142×
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
10152×
                }
1016
            }
1017385×
            if options.token.is_some() && options.ca.is_some() {
10180×
                return;
1019385×
            }
1020385×
            at = dir.parent();
1021
        }
1022992×
    }
1023
1024
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1025
    /// no changes and no reference updates, which the receiver stores.
10260×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
10270×
        let remote = self.open_named_remote(remote_name)?;
10280×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
10290×
        let mut bundle = Bundle::default();
10300×
        for r in seals {
10310×
            let attest = self.store.get_attest(r)?;
10320×
            let sigs = self.store.signatures(r)?;
10330×
            bundle
10340×
                .attests
10350×
                .push(crate::protocol::SignedAttest { attest, sigs });
1036
        }
10370×
        let results = remote.push(bundle, vec![], None, vec![])?;
10380×
        if let Some(r) = results.iter().find(|r| !r.ok) {
10390×
            return fail(format!("{}: {}", r.name, r.reason));
10400×
        }
10410×
        Ok(())
10420×
    }
1043
1044
    /// The remote whose URL starts with `base` (a hub), if configured.
10453×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
10463×
        let base = base.trim_end_matches('/');
10473×
        self.config
10483×
            .remotes
10493×
            .iter()
10503×
            .find(|(_, url)| url.trim_end_matches('/') == base)
10513×
            .map(|(name, _)| name.clone())
10523×
    }
1053
1054
    /// Open a remote by name or, failing that, by URL with the default
1055
    /// credentials (see [`Repo::credentials_for`]).
10560×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
10570×
        if let Some(name) = self.remote_for_url(url) {
10580×
            return Ok((name.clone(), self.open_named_remote(&name)?));
10590×
        }
10600×
        let options = RemoteOptions {
10610×
            repo_id: self.id().ok(),
10620×
            ..self.credentials_for(url)
10630×
        };
10640×
        Ok((url.to_string(), open_remote(url, &options)?))
10650×
    }
1066
1067
    /// Credentials for a URL: those of the configured remote with that
1068
    /// URL, else the environment's.
10693×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
10703×
        match self.remote_for_url(url) {
10713×
            Some(name) => self.remote_options(&name),
10720×
            None => RemoteOptions {
10730×
                repo_id: self.id().ok(),
10740×
                ..self.credentials_for(url)
10750×
            },
1076
        }
10773×
    }
1078
1079958×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1080958×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1081958×
    }
1082
108392×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
108492×
        self.oxy
108592×
            .join("remotes")
108692×
            .join(remote)
108792×
            .join(format!("{bookmark}.serial"))
108892×
    }
1089
109019×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
109119×
        fs::read_to_string(self.serial_path(remote, bookmark))
109219×
            .ok()
109319×
            .and_then(|s| s.trim().parse().ok())
109419×
    }
1095
109673×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
109773×
        let p = self.serial_path(remote, bookmark);
109873×
        fs::create_dir_all(p.parent().unwrap())?;
109973×
        write_atomic(&p, serial.to_string().as_bytes())
110073×
    }
1101
1102373×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1103373×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1104373×
    }
1105
1106
    /// The highest policy serial `remote` has ever presented.
1107349×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1108349×
        fs::read_to_string(self.policy_serial_path(remote))
1109349×
            .ok()
1110349×
            .and_then(|s| s.trim().parse().ok())
1111349×
    }
1112
111324×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
111424×
        let p = self.policy_serial_path(remote);
111524×
        fs::create_dir_all(p.parent().unwrap())?;
111624×
        write_atomic(&p, serial.to_string().as_bytes())
111724×
    }
1118
111927×
    fn lazy_dir(&self) -> PathBuf {
112027×
        self.oxy.join("lazy")
112127×
    }
1122
1123
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
11244×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
11254×
        fs::create_dir_all(self.lazy_dir())?;
11264×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
11274×
    }
1128
1129
    /// Which remote promised an absent blob, if any.
113015×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
113115×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
113215×
            .ok()
113315×
            .map(|s| s.trim().to_string())
113415×
    }
1135
1136
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
11374×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
11384×
        let Some(remote_name) = self.lazy_remote(blob) else {
11390×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1140
        };
11414×
        let remote = self.open_named_remote(&remote_name)?;
11424×
        let objects = remote.objects(&[*blob])?;
11439×
        for (ty, body) in objects {
11449×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
11459×
                self.store.put(ty, &body)?;
11460×
            }
1147
        }
11484×
        if !self.store.has(blob) {
11490×
            return fail(format!(
1150
                "{remote_name} did not send blob {}",
11510×
                blob.short(12)
1152
            ));
11534×
        }
11544×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
11554×
        Ok(())
11564×
    }
1157
1158
    /// After importing from `remote`, record every blob the changes reference
1159
    /// that the store lacks as lazily available from that remote.
11604×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
11614×
        let mut n = 0;
11624×
        for h in changes {
11634×
            let c = self.store.get_change(h)?;
116413×
            for e in &c.edits {
116513×
                if let Edit::Replace { old, new, .. } = e {
11666×
                    for b in [old, new].into_iter().flatten() {
11676×
                        if !self.store.has(b) {
11684×
                            self.register_lazy(b, remote)?;
11694×
                            n += 1;
11702×
                        }
1171
                    }
11727×
                }
1173
            }
1174
        }
11754×
        Ok(n)
11764×
    }
1177
1178
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1179349×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1180349×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1181473×
        for st in view
1182349×
            .bookmarks
1183349×
            .values()
1184349×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1185
        {
1186473×
            if let Ok(s) = self.store.get_state(st) {
1187473×
                have.extend(s.heads);
1188473×
            }
1189
        }
1190349×
        have.extend(view.workspaces.values().copied());
1191349×
        Ok(have.into_iter().collect())
1192349×
    }
1193
1194
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1195355×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1196355×
        let remote = self.open_named_remote(remote_name)?;
1197352×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1198350×
        let resp = remote.refs()?;
1199
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1200
        // and signed by roots we trust, or on first contact. A remote that
1201
        // once presented a policy may never present none or an older one:
1202
        // that is a downgrade. A remote that never presented one is
1203
        // unverified, and this fetch is checked only as far as possible.
1204349×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1205349×
        let seen = self.remote_policy_serial(remote_name);
1206349×
        let mut unverified = false;
1207349×
        match &resp.policy {
12088×
            Some(sp) => {
12098×
                if seen.is_some_and(|s| sp.policy.serial < s) {
12100×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
12118×
                }
12125×
                match &local_policy {
12135×
                    Some(l) if sp.policy.serial < l.serial => {}
12145×
                    Some(l) if sp.policy.serial == l.serial => {
12151×
                        if sp.policy.hash() != l.hash() {
12160×
                            return fail(format!(
1217
                                "{remote_name} presents a different policy with the same serial {}",
1218
                                l.serial
1219
                            ));
12201×
                        }
1221
                    }
1222
                    _ => {
12237×
                        self.adopt_policy_chain(
12247×
                            &resp.history,
12257×
                            sp,
12267×
                            &format!("oxy fetch {remote_name}"),
1227
                        )
12287×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1229
                    }
1230
                }
12318×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1232
            }
1233
            None => {
1234341×
                if seen.is_some() {
12350×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1236341×
                }
1237341×
                unverified = true;
1238
            }
1239
        }
1240349×
        let policy = if unverified {
1241341×
            None
1242
        } else {
12438×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1244
        };
1245349×
        let (op_ref, op) = self.head_op()?;
1246349×
        let mut view = op.view.clone();
1247349×
        let have = self.known_heads(&view)?;
1248349×
        let mut report = Vec::new();
1249349×
        let max_blob = self.config.max_blob;
1250356×
        for r in resp.refs {
1251356×
            let needed = {
1252356×
                let _t = crate::timing::phase("fetch: negotiate");
1253356×
                remote.negotiate(&have, &r.heads)?
1254
            };
1255356×
            let bundle = {
1256356×
                let _t = crate::timing::phase("fetch: bundle");
1257356×
                remote.fetch(&needed, max_blob)?
1258
            };
1259
            // Changes are not individually re-verified here: the bookmark's
1260
            // attestation (checked below) binds its whole state, and the
1261
            // receiver of the push verified the added changes at that time.
1262356×
            let imported = {
1263356×
                let _t = crate::timing::phase("fetch: import");
1264356×
                self.import_bundle(&bundle, false)?
1265
            };
1266356×
            if max_blob.is_some() {
12674×
                self.register_missing_blobs(&imported, remote_name)?;
1268352×
            }
1269485×
            for h in &r.heads {
1270485×
                if !self.store.has(h) {
12710×
                    return fail(format!("remote did not send head {}", h.short(12)));
1272485×
                }
1273
            }
1274356×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1275356×
            if state != r.state {
12760×
                return fail(format!(
1277
                    "remote state {} does not match its heads",
12780×
                    r.state.short(12)
1279
                ));
1280356×
            }
1281356×
            if let Some(p) = &policy {
12828×
                let Some(sa) = &r.attestation else {
12830×
                    return fail(format!(
1284
                        "{remote_name}/{} has no attestation, which its policy requires",
1285
                        r.name
1286
                    ));
1287
                };
12888×
                let signer = sa
12898×
                    .sigs
12908×
                    .first()
12918×
                    .map(|s| s.key)
12928×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
12938×
                if !p.authorizes(&signer, &r.name)
12940×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1295
                {
12960×
                    return fail(format!(
1297
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1298
                        r.name,
12990×
                        signer.short(12)
1300
                    ));
13018×
                }
1302348×
            }
1303356×
            if let Some(sa) = &r.attestation {
1304
                let AttestBody::Ref {
130519×
                    old_state,
130619×
                    new_state,
1307
                    ..
130819×
                } = &sa.attest.body
1309
                else {
13100×
                    return fail("remote sent a non-ref attestation for a bookmark");
1311
                };
131219×
                let (old_state, new_state) = (*old_state, *new_state);
131319×
                let serial = self
131419×
                    .check_ref_attest(
131519×
                        sa,
131619×
                        &r.name,
131719×
                        &old_state,
131819×
                        &new_state,
131919×
                        self.last_seen_serial(remote_name, &r.name),
1320
                        true,
1321
                    )
132219×
                    .map_err(|e| {
13230×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
13240×
                    })?;
132519×
                if new_state != r.state {
13260×
                    return fail(format!(
1327
                        "attestation for {}/{} does not cover its current state",
1328
                        remote_name, r.name
1329
                    ));
133019×
                }
133119×
                let ar = self.store.put_attest(&sa.attest)?;
133219×
                for sig in &sa.sigs {
133319×
                    self.store.put_signature(&ar, sig)?;
1334
                }
133519×
                self.record_serial(remote_name, &r.name, serial)?;
1336337×
            }
1337356×
            view.remotes
1338356×
                .entry(remote_name.to_string())
1339356×
                .or_default()
1340356×
                .insert(r.name.clone(), state);
1341356×
            report.push((r.name, r.heads, imported.len()));
1342
        }
1343349×
        let mut new_tags = 0;
1344349×
        for t in &resp.tags {
134510×
            if view.tags.contains_key(&t.name) {
13464×
                continue;
13476×
            }
1348
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
13496×
            let missing: Vec<ChangeHash> = t
13506×
                .heads
13516×
                .iter()
13526×
                .filter(|h| !self.store.has(h))
13536×
                .copied()
13546×
                .collect();
13556×
            if !missing.is_empty() {
13560×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
13570×
                let bundle = remote.fetch(&needed, max_blob)?;
13580×
                self.import_bundle(&bundle, false)?;
13596×
            }
13606×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
13616×
            self.adopt_tag(&mut view, t, policy.as_ref())
13626×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
13636×
            new_tags += 1;
1364
        }
1365349×
        if view != op.view {
1366339×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
136710×
        }
1368349×
        let _ = self.run_hook(
1369349×
            "post-fetch",
1370349×
            &format!(
1371
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1372349×
                json_str(remote_name),
1373356×
                json_array(report.iter().map(|(n, heads, _)| format!(
1374
                    "{{\"name\":{},\"heads\":{}}}",
1375356×
                    json_str(n),
1376485×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1377
                )))
1378
            ),
1379
        );
1380349×
        Ok(FetchReport {
1381349×
            refs: report,
1382349×
            unverified,
1383349×
            new_tags,
1384349×
        })
1385355×
    }
1386
1387
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1388
    /// the changes within `depth` steps of its heads, and the boundary below.
13891×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
13901×
        let remote = self.open_named_remote(remote_name)?;
13911×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13921×
        let resp = remote.refs()?;
13931×
        let bookmark = self.config.bookmark.clone();
13941×
        if let Some(sp) = &resp.policy {
13950×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
13960×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
13970×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
13981×
        }
13991×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
14000×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1401
        };
14021×
        if r.heads.is_empty() {
14030×
            return Ok(0);
14041×
        }
1405
        // Base: the remote's checkpoint of exactly these heads.
14061×
        let cp_bundle = remote.checkpoint(&r.heads)?;
14071×
        let mut cp_ref = None;
14083×
        for (ty, body) in &cp_bundle.objects {
14093×
            let put = self.store.put(*ty, body)?;
14103×
            if *ty == ObjectType::Checkpoint {
14111×
                cp_ref = Some(put);
14122×
            }
1413
        }
14141×
        let Some(cp_ref) = cp_ref else {
14150×
            return fail(format!("{remote_name} sent no checkpoint"));
1416
        };
14171×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1418
        // History window.
14191×
        let wanted = remote.shallow(&r.heads, depth)?;
14201×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
14211×
        let imported = self.import_bundle_shallow(&bundle, false)?;
14221×
        if self.config.max_blob.is_some() {
14230×
            self.register_missing_blobs(&imported, remote_name)?;
14241×
        }
14251×
        self.refresh_boundary(&imported)?;
14261×
        if let Some(sa) = &r.attestation {
14270×
            let ar = self.store.put_attest(&sa.attest)?;
14280×
            for sig in &sa.sigs {
14290×
                self.store.put_signature(&ar, sig)?;
1430
            }
14310×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
14320×
                self.record_serial(remote_name, &r.name, serial)?;
14330×
            }
14341×
        }
14351×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
14361×
        let (op_ref, op) = self.head_op()?;
14371×
        let mut view = op.view.clone();
14381×
        view.remotes
14391×
            .entry(remote_name.to_string())
14401×
            .or_default()
14411×
            .insert(r.name.clone(), state);
14421×
        self.record_op(
14431×
            &[op_ref],
14441×
            &format!("oxy fetch {remote_name} --depth {depth}"),
14451×
            view,
14460×
        )?;
14471×
        Ok(imported.len())
14481×
    }
1449
1450
    /// Fetch, then take the union of the local bookmark's state with the
1451
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1452107×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1453107×
        let _wc = self.lock_working_copy()?;
1454107×
        self.fetch(remote_name)?;
1455104×
        let (op_ref, op) = self.head_op()?;
1456104×
        let current = self.config.bookmark.clone();
1457104×
        let mut local_current = self.heads_of(&op.view, &current)?;
1458104×
        local_current.sort();
1459104×
        let mut view = op.view.clone();
1460104×
        let mut current_heads = local_current.clone();
1461104×
        let mut changed = false;
1462104×
        let mut others = Vec::new();
1463104×
        let tracked = op
1464104×
            .view
1465104×
            .remotes
1466104×
            .get(remote_name)
1467104×
            .cloned()
1468104×
            .unwrap_or_default();
1469108×
        for (name, remote_state) in tracked {
1470
            // Every local bookmark tracks the remote's of the same name;
1471
            // the current one may be new here.
1472108×
            let local_state = op.view.bookmarks.get(&name).copied();
1473108×
            if local_state.is_none() && name != current {
14740×
                continue;
1475108×
            }
1476108×
            if local_state == Some(remote_state) {
14778×
                continue;
1478100×
            }
1479100×
            let local = self.heads_of(&op.view, &name)?;
1480100×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1481124×
            if remote_heads.iter().all(|h| local.contains(h)) {
14820×
                continue;
1483100×
            }
1484100×
            let mut all = local.clone();
1485100×
            all.extend(remote_heads);
1486100×
            let st = self.load_state_history(&all)?;
1487100×
            let mut heads = st.maximal(&all);
1488100×
            heads.sort();
1489100×
            let mut sorted_local = local;
1490100×
            sorted_local.sort();
1491100×
            if heads == sorted_local {
14921×
                continue;
149399×
            }
149499×
            view.bookmarks.insert(
149599×
                name.clone(),
149699×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1497
            );
149899×
            if name == current {
149997×
                changed = true;
150097×
                current_heads = heads;
150197×
            } else {
15022×
                others.push(name);
15032×
            }
1504
        }
1505104×
        if changed || !others.is_empty() {
150698×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
15076×
        }
1508
        // The working copy follows its bookmark whenever nothing would be
1509
        // lost, also when this pull brought nothing new but it had been
1510
        // left behind (oxygen#89).
1511104×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1512
        Ok(PullReport {
1513104×
            heads: if changed {
151497×
                current_heads
1515
            } else {
15167×
                local_current
1517
            },
1518104×
            changed,
1519104×
            checked_out,
1520104×
            others,
1521
        })
1522107×
    }
1523
1524
    /// How many changes the working copy's bookmark has that its base
1525
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1526
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1527
    /// the bookmark or holds changes the bookmark lacks. History is read
1528
    /// only when the base and the bookmark's heads differ (oxygen#89).
15297×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
15307×
        let (_, wc) = self.working_copy()?;
15317×
        let mut base = wc.deps.clone();
15327×
        base.sort();
15337×
        let mut heads = self.bookmark_heads()?;
15347×
        heads.sort();
15357×
        if base == heads || heads.is_empty() {
15366×
            return Ok(None);
15371×
        }
15381×
        let state = self.load_state_history(&heads)?;
15391×
        if !base.iter().all(|h| state.contains(h)) {
15400×
            return Ok(None);
15411×
        }
15421×
        let had = if base.is_empty() {
15430×
            0
1544
        } else {
15451×
            self.load_state_history(&base)?.len()
1546
        };
15471×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
15487×
    }
1549
1550
    /// Bring the working copy to `heads`, the state of its bookmark
1551
    /// `bookmark`, when nothing would be lost: its base is part of that
1552
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1553
    /// with uncommitted work, the work comes along when the new changes
1554
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1555
    /// it followed only from exactly the bookmark's old heads, so a working
1556
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1557
    /// or a pull from another workspace) never caught up, and nothing said
1558
    /// so (oxygen#74, #89). Returns whether it moved.
1559104×
    pub fn follow_bookmark(
1560104×
        &self,
1561104×
        heads: &[ChangeHash],
1562104×
        bookmark: &str,
1563104×
        command: &str,
1564104×
    ) -> Result<bool> {
1565104×
        let snap = self.snapshot(command)?;
1566104×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1567104×
        let mut base = snap.base.maximal(&snap.wc.deps);
1568104×
        base.sort();
1569104×
        let mut target = heads.to_vec();
1570104×
        target.sort();
1571104×
        if base == target {
15726×
            return Ok(false);
157398×
        }
157498×
        let state = self.load_state_history(heads)?;
1575172×
        if !base.iter().all(|h| state.contains(h)) {
1576
            // The working copy holds changes the bookmark lacks: not ours to move.
15770×
            return Ok(false);
157898×
        }
157998×
        if clean {
158098×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
158198×
            Ok(true)
1582
        } else {
15830×
            Ok(self
15840×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
15850×
                .is_ok())
1586
        }
1587104×
    }
1588
1589
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1590
    /// changes and attesting the reference when a key is available.
1591
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1592
    /// state, attested when we have an identity. The local bookmark, if
1593
    /// any, is kept; only the remote-tracking entry goes.
15945×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
15955×
        let remote = self.open_named_remote(remote_name)?;
15965×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
15975×
        let resp = remote.refs()?;
15987×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
15991×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1600
        };
16014×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
16020×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
16034×
        }
16044×
        let attestation = match self.secret_key()? {
16052×
            Some(_) => Some(self.sign_attest(&Attest {
16062×
                repo: self.id()?,
16072×
                hlc: Hlc::now(),
16082×
                body: AttestBody::Ref {
16092×
                    name: bookmark.to_string(),
16102×
                    old_state: r.state,
16112×
                    new_state: ObjectRef::ZERO,
16122×
                    serial: r.last_serial.unwrap_or(0) + 1,
16132×
                },
16140×
            })?),
16152×
            None => None,
1616
        };
16174×
        let results = remote.push(
16184×
            Bundle::default(),
16194×
            vec![RefUpdate {
16204×
                name: bookmark.to_string(),
16214×
                old_state: r.state,
16224×
                new_state: ObjectRef::ZERO,
16234×
                force: true,
16244×
                attestation,
16254×
            }],
16264×
            None,
16274×
            vec![],
16280×
        )?;
16294×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
16302×
            let (op_ref, op) = self.head_op()?;
16312×
            let mut view = op.view.clone();
16322×
            if let Some(m) = view.remotes.get_mut(remote_name) {
16332×
                m.remove(bookmark);
16342×
            }
16352×
            self.record_op(
16362×
                &[op_ref],
16372×
                &format!("oxy push {remote_name} --delete {bookmark}"),
16382×
                view,
16390×
            )?;
16402×
        }
16414×
        Ok(results)
16425×
    }
1643
1644
    /// `changes`, in dependency order, cut into batches of about
1645
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1646
    /// There is always one, perhaps empty.
1647268×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1648268×
        let blob_len = |r: &ObjectRef| -> u64 {
164929×
            self.store
165029×
                .get_typed(r, ObjectType::Blob)
165129×
                .ok()
165229×
                .and_then(|b| Blob::decode(&b).ok())
165329×
                .map_or(0, |b| b.length)
165429×
        };
1655268×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1656367×
        for h in changes {
1657367×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1658367×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1659367×
            let mut weight = raw.len() as u64;
1660483×
            for t in &texts {
1661483×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
166226×
                    weight += blob_len(r);
1663457×
                }
1664
            }
1665633×
            for e in &c.edits {
16663×
                if let Edit::Replace { new: Some(b), .. } = e {
16673×
                    weight += blob_len(b);
1668630×
                }
1669
            }
1670367×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
16715×
                out.push(std::mem::take(&mut batch));
16725×
                bytes = 0;
1673362×
            }
1674367×
            batch.push(*h);
1675367×
            bytes += weight;
1676
        }
1677268×
        out.push(batch);
1678268×
        Ok(out)
1679268×
    }
1680
1681342×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1682342×
        let bookmark = self.config.bookmark.clone();
1683342×
        self.push_bookmark(remote_name, &bookmark, force)
1684342×
    }
1685
1686
    /// `push` for a named bookmark (`oxy push -b NAME`).
1687349×
    pub fn push_bookmark(
1688349×
        &self,
1689349×
        remote_name: &str,
1690349×
        bookmark: &str,
1691349×
        force: bool,
1692349×
    ) -> Result<Vec<RefResult>> {
1693349×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1694349×
    }
1695
1696
    /// `push_bookmark`, saying how a long push is going: one line per
1697
    /// batch sent (oxygen#95).
1698357×
    pub fn push_bookmark_with(
1699357×
        &self,
1700357×
        remote_name: &str,
1701357×
        bookmark: &str,
1702357×
        force: bool,
1703357×
        progress: crate::store::Progress,
1704357×
    ) -> Result<Vec<RefResult>> {
1705357×
        let (op_ref, op) = self.head_op()?;
1706357×
        if !op.view.bookmarks.contains_key(bookmark) {
17070×
            return fail(format!("no bookmark {bookmark}"));
1708357×
        }
1709357×
        let bookmark = bookmark.to_string();
1710357×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1711
        // pre-push hook: may veto before the remote is contacted.
1712357×
        self.run_hook(
1713357×
            "pre-push",
1714357×
            &format!(
1715
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1716357×
                json_str(remote_name),
1717357×
                json_str(&bookmark),
1718701×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1719
            ),
17201×
        )?;
1721356×
        let remote = self.open_named_remote(remote_name)?;
1722356×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1723353×
        let resp = remote.refs()?;
1724353×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1725353×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1726353×
        let policy_to_send = match (&local_policy, &resp.policy) {
172717×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
17287×
            (Some(l), None) => Some(l.clone()),
17298×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
17301×
                return fail(format!(
1731
                    "{remote_name} has a newer policy (serial {}); fetch first",
1732
                    r.policy.serial
1733
                ));
1734
            }
1735336×
            _ => None,
1736
        };
1737352×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1738352×
        if remote_has_policy && self.secret_key()?.is_none() {
17391×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1740351×
        }
1741351×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1742351×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1743351×
            .tag_refs()?
1744351×
            .into_iter()
1745351×
            .filter(|t| !remote_tags.contains(&t.name))
1746351×
            .collect();
1747351×
        let refs = resp.refs;
1748351×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1749351×
        let (remote_state, remote_heads, last_serial) =
1750351×
            match refs.iter().find(|r| r.name == bookmark) {
1751335×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
175216×
                None => (empty, vec![], None),
1753
            };
1754351×
        let new_state = self
1755351×
            .store
1756351×
            .put_state(&StateObject::new(local_heads.clone()))?;
1757
        // A push that carries a policy re-attests the bookmark even when its
1758
        // state is unchanged, so the current attestation is always by a key
1759
        // the current policy authorizes (a revoked key's attestation would
1760
        // otherwise be refused by every later fetch).
1761351×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
17628×
            return Ok(vec![RefResult {
17638×
                name: bookmark,
17648×
                ok: true,
17658×
                reason: "already up to date".into(),
17668×
            }]);
1767343×
        }
1768386×
        for h in &remote_heads {
1769386×
            if !self.store.has(h) {
177074×
                return fail(format!(
1771
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
177274×
                    h.short(12)
1773
                ));
1774312×
            }
1775
        }
1776269×
        if !force {
1777269×
            let closure = self.closure_in_store(&local_heads)?;
1778302×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
17790×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1780269×
            }
17810×
        }
1782269×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1783269×
        let key = self.secret_key()?.map(|(k, _)| k);
1784269×
        if let Some(key) = key {
1785
            // Seal this author's changes that carry no valid authenticator,
1786
            // and adopt anonymous ones (zero author, spec §14.4). The seals
1787
            // are stored, so each batch's bundle carries those it needs.
178872×
            let mut unsigned = Vec::new();
178972×
            for h in &to_send {
179068×
                let c = self.store.get_change_meta(h)?;
179168×
                if (c.author == key || c.author.is_zero())
179265×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
179338×
                {
179438×
                    unsigned.push(*h);
179538×
                }
1796
            }
179772×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
179835×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1799
            }
1800197×
        }
1801
        // A long history goes in batches, in dependency order, so neither
1802
        // side holds it whole and no request passes the remote's limit:
1803
        // all but the last carry objects alone; the last moves the bookmark
1804
        // (oxygen#95).
1805268×
        let batches = self.push_batches(&to_send)?;
1806268×
        let (last, earlier) = batches.split_last().expect("at least one batch");
1807268×
        for (i, batch) in earlier.iter().enumerate() {
18085×
            progress(&format!(
18095×
                "part {} of {}: {} changes",
18105×
                i + 1,
18115×
                batches.len(),
18125×
                batch.len()
18135×
            ));
18145×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
18155×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
18165×
                Some(r) if r.ok => {}
18170×
                Some(r) => {
18180×
                    return fail(format!(
1819
                        "{remote_name} refused part {} of the push: {}",
18200×
                        i + 1,
1821
                        r.reason
1822
                    ))
1823
                }
1824
                None => {
18250×
                    return fail(format!(
1826
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
1827
                    ))
1828
                }
1829
            }
1830
        }
1831268×
        if batches.len() > 1 {
18321×
            progress(&format!(
18331×
                "part {} of {}: {} changes",
18341×
                batches.len(),
18351×
                batches.len(),
18361×
                last.len()
18371×
            ));
1838267×
        }
1839268×
        let mut bundle = self.bundle_for(last)?;
1840268×
        bundle.objects.push((
1841268×
            ObjectType::State,
1842268×
            StateObject::new(local_heads.clone()).encode(),
1843268×
        ));
1844268×
        let attestation = match key {
184571×
            Some(_) => Some(self.sign_attest(&Attest {
184671×
                repo: self.id()?,
184771×
                hlc: Hlc::now(),
184871×
                body: AttestBody::Ref {
184971×
                    name: bookmark.clone(),
185071×
                    old_state: remote_state,
185171×
                    new_state,
185271×
                    serial: next_serial(last_serial),
185371×
                },
18541×
            })?),
1855197×
            None => None,
1856
        };
1857267×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
185870×
            AttestBody::Ref { serial, .. } => Some(serial),
18590×
            _ => None,
186070×
        });
1861267×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1862
        // Tag states must be present on the remote: bundle their changes too.
1863267×
        for t in &tags_to_send {
18646×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
18656×
            let extra: Vec<ChangeHash> =
18666×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
18676×
            if !extra.is_empty() {
18680×
                let more = self.bundle_for(&extra)?;
18690×
                bundle.changes.extend(more.changes);
18700×
                bundle.hashes.extend(more.hashes);
18710×
                bundle.attests.extend(more.attests);
18720×
                bundle.objects.extend(more.objects);
18736×
            }
18746×
            bundle.objects.push((
18756×
                ObjectType::State,
18766×
                StateObject::new(t.heads.clone()).encode(),
18776×
            ));
1878
        }
1879267×
        if let Some(l) = &policy_to_send {
188016×
            let remote_serial = resp_policy_serial;
188116×
            bundle.policies = self
188216×
                .policy_history()?
188316×
                .into_iter()
188439×
                .filter(|sp| {
188539×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
188618×
                        && sp.policy.serial < l.policy.serial
188739×
                })
188816×
                .collect();
1889251×
        }
1890267×
        let results = remote.push(
1891267×
            bundle,
1892267×
            vec![RefUpdate {
1893267×
                name: bookmark.clone(),
1894267×
                old_state: remote_state,
1895267×
                new_state,
1896267×
                force,
1897267×
                attestation,
1898267×
            }],
1899267×
            policy_to_send,
1900267×
            tags_to_send,
19016×
        )?;
190216×
        if let (Some(serial), true) = (
1903261×
            sent_serial,
1904267×
            results.iter().any(|r| r.ok && r.name == "policy"),
1905
        ) {
190616×
            self.record_policy_serial(remote_name, serial)?;
1907245×
        }
1908277×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1909246×
            let mut view = op.view.clone();
1910246×
            view.remotes
1911246×
                .entry(remote_name.to_string())
1912246×
                .or_default()
1913246×
                .insert(bookmark.clone(), new_state);
1914246×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1915243×
            if let Some(s) = serial {
191654×
                self.record_serial(remote_name, &bookmark, s)?;
1917189×
            }
191815×
        }
1919256×
        Ok(results)
1920357×
    }
1921
1922
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1923
    /// bookmark set to the remote's, working copy checked out.
1924225×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1925225×
        Self::clone_with(url, dest, None, &[])
1926225×
    }
1927
1928
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1929
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1930
    /// unless a size is given, so out-of-scope binaries are never fetched).
1931233×
    pub fn clone_with(
1932233×
        url: &str,
1933233×
        dest: &Path,
1934233×
        max_blob: Option<u64>,
1935233×
        sparse: &[String],
1936233×
    ) -> Result<Repo> {
1937233×
        Self::clone_full(url, dest, max_blob, sparse, None)
1938233×
    }
1939
1940
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1941
    /// changes within `depth` steps of them; the rest is the boundary.
19421×
    pub fn clone_shallow(
19431×
        url: &str,
19441×
        dest: &Path,
19451×
        depth: u32,
19461×
        max_blob: Option<u64>,
19471×
        sparse: &[String],
19481×
    ) -> Result<Repo> {
19491×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
19501×
    }
1951
1952234×
    fn clone_full(
1953234×
        url: &str,
1954234×
        dest: &Path,
1955234×
        max_blob: Option<u64>,
1956234×
        sparse: &[String],
1957234×
        depth: Option<u32>,
1958234×
    ) -> Result<Repo> {
1959234×
        let options = crate::credentials::Credentials::user().options_for(url);
1960234×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1961234×
    }
1962
1963
    /// Clone a subrepo with the credentials the parent would use for its
1964
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1965
    /// subrepo: it finds the same ones again through its parent.
19668×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
19678×
        let options = self.credentials_for(url);
19688×
        Self::clone_using(url, dest, None, &[], None, &options)
19698×
    }
1970
1971
    /// The name of a remote of this repository on the same hub (scheme,
1972
    /// host and port) as `url`.
197319×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
197423×
        let origin = |u: &str| -> Option<String> {
197523×
            let (scheme, rest) = u.split_once("://")?;
19768×
            if !matches!(scheme, "http" | "https") {
19770×
                return None;
19788×
            }
19798×
            let host = rest.split('/').next()?;
19808×
            Some(format!(
19818×
                "{}://{}",
19828×
                scheme.to_ascii_lowercase(),
19838×
                host.to_ascii_lowercase()
19848×
            ))
198523×
        };
198619×
        let want = origin(url)?;
19874×
        self.config
19884×
            .remotes
19894×
            .iter()
19904×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
19914×
            .map(|(name, _)| name.clone())
199219×
    }
1993
1994
    /// The token and CA to reach `url` with: those of a remote of this
1995
    /// repository on the same hub (scheme, host and port), else the
1996
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
1997
    /// and enclosing checkouts', as a clone would use them.
199819×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
199919×
        match self.remote_on_same_hub(url) {
20001×
            Some(name) => RemoteOptions {
20011×
                repo_id: None,
20021×
                cache_dir: None,
20031×
                ..self.remote_options(&name)
20041×
            },
2005
            None => {
200618×
                let mut options = RemoteOptions::default();
200718×
                self.fill_credentials(url, &mut options);
200818×
                options
2009
            }
2010
        }
201119×
    }
2012
2013242×
    fn clone_using(
2014242×
        url: &str,
2015242×
        dest: &Path,
2016242×
        max_blob: Option<u64>,
2017242×
        sparse: &[String],
2018242×
        depth: Option<u32>,
2019242×
        options: &RemoteOptions,
2020242×
    ) -> Result<Repo> {
2021242×
        let remote = open_remote(url, options)?;
2022242×
        let id = remote.repo_id()?;
2023238×
        if id == crate::protocol::UNBOUND_ID {
20242×
            return fail(format!(
2025
                "{url} is empty and unbound: push a repository to it first"
2026
            ));
2027236×
        }
2028236×
        let mut repo = Repo::init_with_id(dest, id)?;
2029236×
        repo.config
2030236×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2031236×
        if let Some(m) = max_blob {
20322×
            repo.config.set("filter.max-blob", &m.to_string())?;
2033234×
        } else if !sparse.is_empty() {
20341×
            repo.config.set("filter.max-blob", "0")?;
2035233×
        }
2036236×
        if !sparse.is_empty() {
20371×
            repo.config.set("filter.paths", &sparse.join(","))?;
2038235×
        }
2039236×
        repo.save_config()?;
2040236×
        if let Some(depth) = depth {
20411×
            repo.fetch_shallow("origin", depth)?;
2042
        } else {
2043235×
            repo.fetch("origin")?;
2044
        }
2045235×
        let (op_ref, op) = repo.head_op()?;
2046
        // The remote's default bookmark, else ours (main), else its only one.
2047235×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2048
        // Asked of the remote as now configured, so a store-backed one
2049
        // answers from the mirror the fetch just filled.
2050235×
        let advertised = repo
2051235×
            .open_named_remote("origin")
2052235×
            .ok()
2053235×
            .and_then(|r| r.refs().ok())
2054235×
            .and_then(|r| r.default_bookmark);
2055235×
        let bookmark = advertised
2056235×
            .filter(|b| theirs.contains_key(b))
2057235×
            .or_else(|| {
20587×
                theirs
20597×
                    .contains_key(&repo.config.bookmark)
20607×
                    .then(|| repo.config.bookmark.clone())
20617×
            })
2062235×
            .or_else(|| {
20630×
                (theirs.len() == 1)
20640×
                    .then(|| theirs.keys().next().cloned())
20650×
                    .flatten()
20660×
            })
2067235×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2068235×
        let initial = repo.config.bookmark.clone();
2069235×
        if bookmark != repo.config.bookmark {
20701×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
20711×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
20721×
            repo.config.bookmark = bookmark.clone();
2073234×
        }
2074235×
        if let Some(state) = theirs.get(&bookmark).copied() {
2075235×
            let heads = repo.store.get_state(&state)?.heads;
2076235×
            let mut view = op.view.clone();
2077
            // The empty bookmark `init` made goes when another is checked out.
2078235×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
20791×
                view.bookmarks.remove(&initial);
2080234×
            }
2081235×
            view.bookmarks.insert(bookmark, state);
2082235×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2083235×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
20840×
        }
2085235×
        Ok(repo)
2086242×
    }
2087
}
2088
2089
/// The serial of a reference's next attestation: one more than the last the
2090
/// remote reports, or, for a bookmark the remote does not have, the clock in
2091
/// milliseconds, so a bookmark created again after a deletion goes past the
2092
/// deletion's serial the remote keeps.
209371×
fn next_serial(last: Option<u64>) -> u64 {
209471×
    match last {
209545×
        Some(l) => l + 1,
209626×
        None => Hlc::now().wall_ms.max(1),
2097
    }
209871×
}