OXYGENHUB
◆ agents-in-readme oxygen / crates / oxy-core / src / repo / sync.rs
73.5 KiB · Rust · last changed Scoped, expiring delegates, and revocation by the delegator 1 month ago source blame history raw
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
impl Repo {
48
    // ------------------------------------------------------------ serving (spec §16)
49
50
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
51
        self.oxy.join("attest").join(name_file(bookmark))
52
    }
53
54
    /// The latest reference attestation stored for a bookmark.
55
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
56
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
57
            Ok(h) => {
58
                let r = ObjectRef::from_hex(h.trim())
59
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
60
                Ok(Some((
61
                    r,
62
                    SignedAttest {
63
                        attest: self.store.get_attest(&r)?,
64
                        sigs: self.store.signatures(&r)?,
65
                    },
66
                )))
67
            }
68
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
69
            Err(e) => Err(e.into()),
70
        }
71
    }
72
73
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
74
        fs::create_dir_all(self.oxy.join("attest"))?;
75
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
76
    }
77
78
    pub fn remote_refs(&self) -> Result<RefsResponse> {
79
        let view = self.view()?;
80
        let mut out = Vec::new();
81
        for (name, state) in &view.bookmarks {
82
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
83
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
84
                AttestBody::Ref { serial, .. } => Some(serial),
85
                _ => None,
86
            });
87
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
88
            out.push(RemoteRef {
89
                name: name.clone(),
90
                state: *state,
91
                heads: self.store.get_state(state)?.heads,
92
                attestation,
93
                last_serial,
94
            });
95
        }
96
        let policy = self.current_policy()?.map(|(_, sp)| sp);
97
        let history = self
98
            .policy_history()?
99
            .into_iter()
100
            .filter(|sp| {
101
                policy
102
                    .as_ref()
103
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
104
            })
105
            .collect();
106
        Ok(RefsResponse {
107
            refs: out,
108
            policy,
109
            tags: self.tag_refs()?,
110
            history,
111
            default_bookmark: Some(self.config.bookmark.clone()),
112
        })
113
    }
114
115
    /// Every change reachable from `heads` that is in the store.
116
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
117
        let mut seen = BTreeSet::new();
118
        let mut stack: Vec<ChangeHash> = heads.to_vec();
119
        while let Some(h) = stack.pop() {
120
            if seen.contains(&h) || !self.store.has(&h) {
121
                continue;
122
            }
123
            seen.insert(h);
124
            stack.extend(self.store.get_change_meta(&h)?.deps);
125
        }
126
        Ok(seen)
127
    }
128
129
    /// The changes within `depth` dependency steps of `heads` (spec §17),
130
    /// nearest first; depth 1 is the heads themselves.
131
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
132
        let mut out = Vec::new();
133
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
134
        let mut layer: Vec<ChangeHash> = heads.to_vec();
135
        for _ in 0..depth.max(1) {
136
            let mut next = Vec::new();
137
            for h in layer {
138
                if !seen.insert(h) || !self.store.has(&h) {
139
                    continue;
140
                }
141
                let c = self.store.get_change(&h)?;
142
                next.extend(c.deps.iter().copied());
143
                out.push(h);
144
            }
145
            if next.is_empty() {
146
                break;
147
            }
148
            layer = next;
149
        }
150
        out.reverse();
151
        Ok(out)
152
    }
153
154
    fn shallow_path(&self) -> PathBuf {
155
        self.oxy.join("shallow")
156
    }
157
158
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
159
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
160
        fs::read_to_string(self.shallow_path())
161
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
162
            .unwrap_or_default()
163
    }
164
165
    pub fn is_shallow(&self) -> bool {
166
        !self.boundary().is_empty()
167
    }
168
169
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
170
        if boundary.is_empty() {
171
            let _ = fs::remove_file(self.shallow_path());
172
            return Ok(());
173
        }
174
        let text: String = boundary
175
            .iter()
176
            .map(|h| format!("{}\n", h.to_hex()))
177
            .collect();
178
        write_atomic(&self.shallow_path(), text.as_bytes())
179
    }
180
181
    /// Recompute the boundary from what is stored: every dependency of a
182
    /// stored change that is not itself stored.
183
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
184
        let mut boundary = self.boundary();
185
        boundary.retain(|h| !self.store.has(h));
186
        for h in imported {
187
            for d in self.store.get_change_meta(h)?.deps {
188
                if !self.store.has(&d) {
189
                    boundary.insert(d);
190
                }
191
            }
192
        }
193
        self.write_boundary(&boundary)
194
    }
195
196
    /// Fetch `depth` more levels of history below the shallow boundary.
197
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
198
        let boundary = self.boundary();
199
        if boundary.is_empty() {
200
            return Ok(0);
201
        }
202
        let remote = self.open_named_remote(remote_name)?;
203
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
204
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
205
        let imported = self.import_bundle_shallow(&bundle, false)?;
206
        if self.config.max_blob.is_some() {
207
            self.register_missing_blobs(&imported, remote_name)?;
208
        }
209
        self.refresh_boundary(&imported)?;
210
        Ok(imported.len())
211
    }
212
213
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
214
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
215
        let have = self.closure_in_store(have)?;
216
        // In a shallow repository the walk stops at the boundary, whose
217
        // changes the remote is assumed to hold.
218
        let boundary = self.boundary();
219
        let mut out = Vec::new();
220
        let mut done: BTreeSet<ChangeHash> = have.clone();
221
        done.extend(boundary.iter().copied());
222
        // Iterative post-order DFS.
223
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
224
        while let Some((h, expanded)) = stack.pop() {
225
            if done.contains(&h) {
226
                continue;
227
            }
228
            if !self.store.has(&h) {
229
                return fail(format!("change {} is not in this repository", h.short(12)));
230
            }
231
            if expanded {
232
                done.insert(h);
233
                out.push(h);
234
                continue;
235
            }
236
            stack.push((h, true));
237
            for d in self.store.get_change_meta(&h)?.deps {
238
                if !done.contains(&d) {
239
                    stack.push((d, false));
240
                }
241
            }
242
        }
243
        Ok(out)
244
    }
245
246
    /// Bundle changes (in the given dependency order) with their signatures,
247
    /// seals, identities, blobs, chunks.
248
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
249
        self.bundle_for_filtered(changes, None)
250
    }
251
252
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
253
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
254
        let mut out = Vec::new();
255
        for r in refs {
256
            let (ty, body) = match self.store.get(r) {
257
                Ok(x) => x,
258
                Err(StoreError::NotFound(_)) => continue,
259
                Err(e) => return Err(e.into()),
260
            };
261
            if ty == ObjectType::Blob {
262
                for c in Blob::decode(&body)?.chunks {
263
                    if let Ok((cty, cb)) = self.store.get(&c) {
264
                        out.push((cty, cb));
265
                    }
266
                }
267
            }
268
            out.push((ty, body));
269
        }
270
        Ok(out)
271
    }
272
273
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
274
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
275
    pub fn bundle_for_filtered(
276
        &self,
277
        changes: &[ChangeHash],
278
        max_blob: Option<u64>,
279
    ) -> Result<Bundle> {
280
        self.bundle_of(changes, max_blob, false)
281
    }
282
283
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
284
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
285
    /// with their text blobs and chunks among the objects, so neither side
286
    /// decodes or encodes their text.
287
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
288
        self.bundle_of(changes, max_blob, true)
289
    }
290
291
    fn bundle_of(
292
        &self,
293
        changes: &[ChangeHash],
294
        max_blob: Option<u64>,
295
        raw: bool,
296
    ) -> Result<Bundle> {
297
        let mut bundle = Bundle::default();
298
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
299
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
300
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
301
            if !r.is_zero() && self.store.has(r) {
302
                objects.insert(*r);
303
            }
304
        };
305
        for h in changes {
306
            // Raw: the stored bytes, and a skeleton for the rest.
307
            let (c, encoded) = if raw {
308
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
309
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
310
                for t in texts {
311
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
312
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
313
                        objects.insert(r);
314
                        objects.extend(blob.chunks);
315
                    }
316
                }
317
                (skel, Some(bytes))
318
            } else {
319
                (self.store.get_change(h)?, None)
320
            };
321
            let sigs = self.store.signatures(h)?;
322
            add_object(&c.author, &mut objects);
323
            for s in &sigs {
324
                add_object(&s.key, &mut objects);
325
            }
326
            for e in &c.edits {
327
                if let Edit::Replace { old, new, .. } = e {
328
                    for b in [old, new].into_iter().flatten() {
329
                        if self.store.has(b) {
330
                            if let Ok(blob) =
331
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
332
                            {
333
                                if max_blob.is_some_and(|m| blob.length > m) {
334
                                    continue;
335
                                }
336
                                objects.insert(*b);
337
                                objects.extend(blob.chunks.iter().copied());
338
                            }
339
                        }
340
                    }
341
                }
342
            }
343
            for s in self.store.seals_for(h)? {
344
                seals.insert(s);
345
            }
346
            match encoded {
347
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
348
                None => {
349
                    bundle.changes.push((c, sigs));
350
                    bundle.hashes.push(*h);
351
                }
352
            }
353
        }
354
        for r in seals {
355
            let attest = self.store.get_attest(&r)?;
356
            let sigs = self.store.signatures(&r)?;
357
            for s in &sigs {
358
                add_object(&s.key, &mut objects);
359
            }
360
            bundle.attests.push(SignedAttest { attest, sigs });
361
        }
362
        for r in objects {
363
            let (ty, body) = self.store.get(&r)?;
364
            bundle.objects.push((ty, body));
365
        }
366
        Ok(bundle)
367
    }
368
369
    /// Store a bundle's contents. With `strict`, every change must
370
    /// authenticate (signature or seal by its author or a delegate).
371
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
372
        self.import_bundle_inner(bundle, strict, false)
373
    }
374
375
    /// Like `import_bundle`, accepting changes whose dependencies are absent
376
    /// (they join the shallow boundary).
377
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
378
        self.import_bundle_inner(bundle, strict, true)
379
    }
380
381
    fn import_bundle_inner(
382
        &self,
383
        bundle: &Bundle,
384
        strict: bool,
385
        shallow: bool,
386
    ) -> Result<Vec<ChangeHash>> {
387
        let batch = self.store.begin_batch()?;
388
        let result = self.import_bundle_batched(bundle, strict, shallow);
389
        batch.finish()?;
390
        result
391
    }
392
393
    fn import_bundle_batched(
394
        &self,
395
        bundle: &Bundle,
396
        strict: bool,
397
        shallow: bool,
398
    ) -> Result<Vec<ChangeHash>> {
399
        for (ty, _) in &bundle.objects {
400
            if !matches!(
401
                ty,
402
                ObjectType::Chunk
403
                    | ObjectType::Blob
404
                    | ObjectType::Identity
405
                    | ObjectType::State
406
                    | ObjectType::Checkpoint
407
            ) {
408
                return fail(format!("bundle may not carry {} objects", ty.name()));
409
            }
410
        }
411
        // All at once: in a large batch they are compressed on every core.
412
        let objects: Vec<(ObjectType, &[u8])> = bundle
413
            .objects
414
            .iter()
415
            .map(|(ty, body)| (*ty, body.as_slice()))
416
            .collect();
417
        self.store.put_many(&objects)?;
418
        for sa in &bundle.attests {
419
            let r = self.store.put_attest(&sa.attest)?;
420
            for sig in &sa.sigs {
421
                self.store.put_signature(&r, sig)?;
422
            }
423
            if let AttestBody::Seal { hashes } = &sa.attest.body {
424
                for h in hashes {
425
                    self.store.index_seal(h, &r)?;
426
                }
427
            }
428
        }
429
        // Each change's hash: from the bundle when its maker knew it, else
430
        // worked out once (for a change adding a whole tree, hashing is
431
        // chunking all its text).
432
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
433
            bundle.hashes.clone()
434
        } else {
435
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
436
        };
437
        let raw_hashes: Vec<ChangeHash> = bundle
438
            .raw_changes
439
            .iter()
440
            .map(|(b, _)| hash_object(ObjectType::Change, b))
441
            .collect();
442
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
443
        let boundary = self.boundary();
444
        let mut imported = Vec::new();
445
        // Changes as stored: checked, then stored as they are, their text
446
        // blobs having come with the objects.
447
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
448
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
449
            for d in &skel.deps {
450
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
451
                {
452
                    return fail(format!(
453
                        "change {} depends on {}, which is neither stored nor in the bundle",
454
                        h.short(12),
455
                        d.short(12)
456
                    ));
457
                }
458
            }
459
            for t in texts {
460
                if let crate::objects::TextRef::Blob(r, _, _) = t {
461
                    if !self.store.has(&r) {
462
                        return fail(format!(
463
                            "change {} came without its text blob {}",
464
                            h.short(12),
465
                            r.short(12)
466
                        ));
467
                    }
468
                }
469
            }
470
            self.store.put(ObjectType::Change, bytes)?;
471
            for sig in sigs {
472
                self.store.put_signature(&h, sig)?;
473
            }
474
            imported.push(h);
475
        }
476
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
477
            for d in &c.deps {
478
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
479
                {
480
                    return fail(format!(
481
                        "change {} depends on {}, which is neither stored nor in the bundle",
482
                        h.short(12),
483
                        d.short(12)
484
                    ));
485
                }
486
            }
487
            let stored = self.store.put_change(c)?;
488
            if stored != h {
489
                return fail(format!(
490
                    "change {} is not the change the bundle names",
491
                    h.short(12)
492
                ));
493
            }
494
            for sig in sigs {
495
                self.store.put_signature(&h, sig)?;
496
            }
497
            imported.push(h);
498
        }
499
        if strict {
500
            for h in &imported {
501
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
502
                    return fail(format!(
503
                        "change {} is not authenticated by its author",
504
                        h.short(12)
505
                    ));
506
                }
507
            }
508
        }
509
        Ok(imported)
510
    }
511
512
    /// Verify a reference attestation against an update it claims to describe.
513
    /// `allow_equal` lets a client re-read the attestation it already has; a
514
    /// server receiving a push requires a strictly greater serial.
515
    /// A reference attestation signed by a delegate of an identity the
516
    /// rule lists is authorized as that identity (spec §14.5): the identity
517
    /// named the delegate with the `refs` scope, still in force at `at_ms`
518
    /// (the attestation's wall time), and the policy names the identity.
519
    /// Revoked keys authorize nothing either way.
520
    pub(crate) fn delegate_authorized(
521
        &self,
522
        p: &crate::policy::Policy,
523
        signer: &KeyId,
524
        reference: &str,
525
        at_ms: u64,
526
    ) -> bool {
527
        if p.is_revoked(signer) {
528
            return false;
529
        }
530
        let Some(rule) = p.rule_for(reference) else {
531
            return false;
532
        };
533
        rule.keys.iter().any(|k| {
534
            !p.is_revoked(k)
535
                && p.identity(k)
536
                    .cloned()
537
                    .or_else(|| self.store.get_identity(k).ok())
538
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
539
        })
540
    }
541
542
    fn check_ref_attest(
543
        &self,
544
        sa: &SignedAttest,
545
        name: &str,
546
        old_state: &ObjectRef,
547
        new_state: &ObjectRef,
548
        last_serial: Option<u64>,
549
        allow_equal: bool,
550
    ) -> std::result::Result<u64, String> {
551
        let AttestBody::Ref {
552
            name: n,
553
            old_state: o,
554
            new_state: nw,
555
            serial,
556
        } = &sa.attest.body
557
        else {
558
            return Err("attestation is not a ref attestation".into());
559
        };
560
        if n != name || o != old_state || nw != new_state {
561
            return Err("attestation does not describe this update".into());
562
        }
563
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
564
            return Err("attestation is for a different repository".into());
565
        }
566
        if let Some(last) = last_serial {
567
            if *serial < last || (*serial == last && !allow_equal) {
568
                return Err(format!(
569
                    "attestation serial {serial} is not greater than the last seen {last}"
570
                ));
571
            }
572
        }
573
        let r = sa.attest.hash();
574
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
575
        let id = self
576
            .store
577
            .get_identity(&sig.key)
578
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
579
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
580
        Ok(*serial)
581
    }
582
583
    /// Accept a push (spec §16.4). Without a trust policy every repository
584
    /// is unverified, so unsigned changes and unattested updates are accepted;
585
    /// attestations that are present must still be valid. With a policy,
586
    /// every change and update is checked against it. A newer policy in the
587
    /// push is applied first when it is signed by the current roots.
588
    pub fn receive_push(
589
        &self,
590
        bundle: Bundle,
591
        updates: Vec<RefUpdate>,
592
        policy: Option<SignedPolicy>,
593
        tags: Vec<crate::protocol::TagRef>,
594
    ) -> Result<Vec<RefResult>> {
595
        Ok(self
596
            .receive_push_report(bundle, updates, policy, tags)?
597
            .results)
598
    }
599
600
    /// `receive_push` with what a host wants to log: each accepted
601
    /// reference's old and new state and heads, and the changes this push
602
    /// stored (hub spec §6.12).
603
    pub fn receive_push_report(
604
        &self,
605
        bundle: Bundle,
606
        updates: Vec<RefUpdate>,
607
        policy: Option<SignedPolicy>,
608
        tags: Vec<crate::protocol::TagRef>,
609
    ) -> Result<PushReport> {
610
        let mut report = PushReport::default();
611
        let results = &mut report.results;
612
        if let Some(sp) = policy {
613
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
614
                Ok(()) => {
615
                    results.push(RefResult {
616
                        name: "policy".into(),
617
                        ok: true,
618
                        reason: format!("serial {}", sp.policy.serial),
619
                    });
620
                }
621
                Err(e) => {
622
                    results.push(RefResult {
623
                        name: "policy".into(),
624
                        ok: false,
625
                        reason: e,
626
                    });
627
                    for u in updates {
628
                        results.push(RefResult {
629
                            name: u.name,
630
                            ok: false,
631
                            reason: "policy update was rejected".into(),
632
                        });
633
                    }
634
                    return Ok(report);
635
                }
636
            }
637
        }
638
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
639
        match self.import_bundle(&bundle, policy.is_some()) {
640
            Ok(imported) => report.imported = imported,
641
            Err(e) => {
642
                for u in updates {
643
                    results.push(RefResult {
644
                        name: u.name,
645
                        ok: false,
646
                        reason: e.to_string(),
647
                    });
648
                }
649
                return Ok(report);
650
            }
651
        }
652
        let (op_ref, op) = self.head_op()?;
653
        let mut view = op.view.clone();
654
        let mut names = Vec::new();
655
        for u in updates {
656
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
657
            let (ok, reason) = match outcome {
658
                Ok(()) => (true, String::new()),
659
                Err(e) => (false, e),
660
            };
661
            if ok {
662
                names.push(u.name.clone());
663
                let heads = self
664
                    .store
665
                    .get_state(&u.new_state)
666
                    .map(|s| s.heads)
667
                    .unwrap_or_default();
668
                report.updated.push(RefUpdated {
669
                    name: u.name.clone(),
670
                    old_state: u.old_state,
671
                    new_state: u.new_state,
672
                    heads,
673
                });
674
            }
675
            results.push(RefResult {
676
                name: u.name,
677
                ok,
678
                reason,
679
            });
680
        }
681
        for t in &tags {
682
            let name = format!("tags/{}", t.name);
683
            let new = !view.tags.contains_key(&t.name);
684
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
685
                Ok(()) => {
686
                    // A tag new here is an update too, so a hub can start
687
                    // its pipeline's tag jobs (oxygenflow#24); one it
688
                    // already had, sent again, is not.
689
                    if new {
690
                        report.updated.push(RefUpdated {
691
                            name: name.clone(),
692
                            old_state: ObjectRef::ZERO,
693
                            new_state: t.state,
694
                            heads: t.heads.clone(),
695
                        });
696
                    }
697
                    names.push(name.clone());
698
                    results.push(RefResult {
699
                        name,
700
                        ok: true,
701
                        reason: String::new(),
702
                    });
703
                }
704
                Err(e) => results.push(RefResult {
705
                    name,
706
                    ok: false,
707
                    reason: e,
708
                }),
709
            }
710
        }
711
        if !names.is_empty() {
712
            self.record_op(
713
                &[op_ref],
714
                &format!("push received: {}", names.join(" ")),
715
                view,
716
            )?;
717
        }
718
        Ok(report)
719
    }
720
721
    /// Check an update's attestation against the latest one for its
722
    /// reference and store it as the new latest. Failures say what was
723
    /// being done, for which reference, so a refused push can be diagnosed
724
    /// from its reason alone.
725
    fn record_update_attest(
726
        &self,
727
        u: &RefUpdate,
728
        sa: &SignedAttest,
729
    ) -> std::result::Result<(), String> {
730
        let name = &u.name;
731
        let last = self
732
            .latest_ref_attest(name)
733
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
734
            .and_then(|(_, a)| match a.attest.body {
735
                AttestBody::Ref { serial, .. } => Some(serial),
736
                _ => None,
737
            });
738
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
739
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
740
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
741
        for sig in &sa.sigs {
742
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
743
        }
744
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
745
    }
746
747
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
748
    /// at `old_state`, is never the bookmark a non-bare repository has
749
    /// checked out (a bare one's default is its host's to protect, see
750
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
751
    /// an attestation by a key that may update it.
752
    /// The deletion's attestation stays the bookmark's latest, so an older
753
    /// one cannot be replayed to bring it back.
754
    fn apply_deletion(
755
        &self,
756
        view: &mut View,
757
        u: &RefUpdate,
758
        policy: Option<&crate::policy::Policy>,
759
    ) -> std::result::Result<(), String> {
760
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
761
            return Err(format!("no bookmark {:?} to delete", u.name));
762
        };
763
        if current != u.old_state {
764
            return Err("stale: the remote bookmark has moved; pull first".into());
765
        }
766
        if !self.is_bare() && u.name == self.config.bookmark {
767
            return Err(format!(
768
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
769
                u.name
770
            ));
771
        }
772
        if let Some(p) = policy {
773
            let Some(sa) = &u.attestation else {
774
                return Err(format!(
775
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
776
                    u.name
777
                ));
778
            };
779
            let signer = sa
780
                .sigs
781
                .first()
782
                .map(|s| s.key)
783
                .ok_or("attestation carries no signature")?;
784
            if !p.authorizes(&signer, &u.name)
785
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
786
            {
787
                return Err(format!(
788
                    "key {} may not delete {:?} under this repository's policy",
789
                    signer.short(12),
790
                    u.name
791
                ));
792
            }
793
        }
794
        if let Some(sa) = &u.attestation {
795
            self.record_update_attest(u, sa)?;
796
        }
797
        view.bookmarks.remove(&u.name);
798
        Ok(())
799
    }
800
801
    fn apply_update(
802
        &self,
803
        view: &mut View,
804
        u: &RefUpdate,
805
        policy: Option<&crate::policy::Policy>,
806
    ) -> std::result::Result<(), String> {
807
        if u.name == "policy" {
808
            return Err(
809
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
810
            );
811
        }
812
        let empty = self
813
            .store
814
            .put_state(&StateObject::new(vec![]))
815
            .map_err(|e| e.to_string())?;
816
        if u.new_state.is_zero() {
817
            return self.apply_deletion(view, u, policy);
818
        }
819
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
820
        if current != u.old_state {
821
            return Err("stale: the remote bookmark has moved; pull first".into());
822
        }
823
        let new_state = self
824
            .store
825
            .get_state(&u.new_state)
826
            .map_err(|_| "new state object is missing".to_string())?;
827
        for h in &new_state.heads {
828
            if !self.store.has(h) {
829
                return Err(format!("head {} is missing", h.short(12)));
830
            }
831
        }
832
        if !u.force {
833
            let old_heads = self
834
                .store
835
                .get_state(&current)
836
                .map_err(|e| e.to_string())?
837
                .heads;
838
            let closure = self
839
                .closure_in_store(&new_state.heads)
840
                .map_err(|e| e.to_string())?;
841
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
842
                return Err(format!(
843
                    "not a fast-forward: current head {} would be dropped (use --force)",
844
                    h.short(12)
845
                ));
846
            }
847
        }
848
        if let Some(p) = policy {
849
            let Some(sa) = &u.attestation else {
850
                return Err(format!(
851
                    "{:?} requires a signed reference attestation under this repository's policy",
852
                    u.name
853
                ));
854
            };
855
            let signer = sa
856
                .sigs
857
                .first()
858
                .map(|s| s.key)
859
                .ok_or("attestation carries no signature")?;
860
            if !p.authorizes(&signer, &u.name)
861
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
862
            {
863
                return Err(format!(
864
                    "key {} may not update {:?} under this repository's policy",
865
                    signer.short(12),
866
                    u.name
867
                ));
868
            }
869
            let old_heads = self
870
                .store
871
                .get_state(&current)
872
                .map_err(|e| e.to_string())?
873
                .heads;
874
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
875
        }
876
        if let Some(sa) = &u.attestation {
877
            self.record_update_attest(u, sa)?;
878
        }
879
        view.bookmarks.insert(u.name.clone(), u.new_state);
880
        Ok(())
881
    }
882
883
    // ------------------------------------------------------------ client side
884
885
    fn remote_url(&self, name: &str) -> Result<String> {
886
        self.config.remotes.get(name).cloned().ok_or_else(|| {
887
            RepoError::Msg(format!(
888
                "no remote named {name:?}; add one with `oxy remote add`"
889
            ))
890
        })
891
    }
892
893
    /// Refuse a remote that is another repository. An **unbound** remote
894
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
895
    /// for pushes, which bind it to this repository's id (spec §16.1).
896
    fn check_remote_id(
897
        &self,
898
        remote: &dyn crate::protocol::Remote,
899
        remote_name: &str,
900
        allow_unbound: bool,
901
    ) -> Result<()> {
902
        let theirs = remote.repo_id()?;
903
        if theirs == self.id()? {
904
            return Ok(());
905
        }
906
        if theirs == crate::protocol::UNBOUND_ID {
907
            if allow_unbound {
908
                return Ok(());
909
            }
910
            return fail(format!(
911
                "remote {remote_name:?} is empty and unbound: push to it first"
912
            ));
913
        }
914
        fail(format!(
915
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
916
        ))
917
    }
918
919
    /// Credentials and trust for a remote: `remote.<name>.token` and
920
    /// `remote.<name>.ca`, else the defaults for its URL
921
    /// ([`Repo::fill_credentials`]).
922
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
923
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
924
        let mut options = RemoteOptions {
925
            repo_id: self.id().ok(),
926
            token: self.config.remote_tokens.get(name).cloned(),
927
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
928
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
929
        };
930
        self.fill_credentials(&url, &mut options);
931
        options
932
    }
933
934
    /// The user's credential store (`credentials.toml` beside the user
935
    /// configuration file).
936
    pub fn credentials(&self) -> crate::credentials::Credentials {
937
        crate::credentials::Credentials::at(
938
            self.user_config
939
                .parent()
940
                .map(Path::to_path_buf)
941
                .unwrap_or_else(default_home),
942
        )
943
    }
944
945
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
946
    /// then the user's credential store for its hub, then a remote on the
947
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
948
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
949
        if options.token.is_some() && options.ca.is_some() {
950
            return;
951
        }
952
        let stored = self.credentials().options_for(url);
953
        options.token = options.token.take().or(stored.token);
954
        options.ca = options.ca.take().or(stored.ca);
955
        if options.token.is_some() && options.ca.is_some() {
956
            return;
957
        }
958
        let Some(hub) = crate::credentials::hub_of(url) else {
959
            return;
960
        };
961
        let mut at = self.root.parent();
962
        while let Some(dir) = at {
963
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
964
                break;
965
            };
966
            for (key, remote_url) in &cfg {
967
                let Some(name) = key
968
                    .strip_prefix("remote.")
969
                    .and_then(|k| k.strip_suffix(".url"))
970
                else {
971
                    continue;
972
                };
973
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
974
                    continue;
975
                }
976
                if options.token.is_none() {
977
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
978
                }
979
                if options.ca.is_none() {
980
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
981
                }
982
            }
983
            if options.token.is_some() && options.ca.is_some() {
984
                return;
985
            }
986
            at = dir.parent();
987
        }
988
    }
989
990
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
991
    /// no changes and no reference updates, which the receiver stores.
992
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
993
        let remote = self.open_named_remote(remote_name)?;
994
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
995
        let mut bundle = Bundle::default();
996
        for r in seals {
997
            let attest = self.store.get_attest(r)?;
998
            let sigs = self.store.signatures(r)?;
999
            bundle
1000
                .attests
1001
                .push(crate::protocol::SignedAttest { attest, sigs });
1002
        }
1003
        let results = remote.push(bundle, vec![], None, vec![])?;
1004
        if let Some(r) = results.iter().find(|r| !r.ok) {
1005
            return fail(format!("{}: {}", r.name, r.reason));
1006
        }
1007
        Ok(())
1008
    }
1009
1010
    /// The remote whose URL starts with `base` (a hub), if configured.
1011
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
1012
        let base = base.trim_end_matches('/');
1013
        self.config
1014
            .remotes
1015
            .iter()
1016
            .find(|(_, url)| url.trim_end_matches('/') == base)
1017
            .map(|(name, _)| name.clone())
1018
    }
1019
1020
    /// Open a remote by name or, failing that, by URL with the default
1021
    /// credentials (see [`Repo::credentials_for`]).
1022
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
1023
        if let Some(name) = self.remote_for_url(url) {
1024
            return Ok((name.clone(), self.open_named_remote(&name)?));
1025
        }
1026
        let options = RemoteOptions {
1027
            repo_id: self.id().ok(),
1028
            ..self.credentials_for(url)
1029
        };
1030
        Ok((url.to_string(), open_remote(url, &options)?))
1031
    }
1032
1033
    /// Credentials for a URL: those of the configured remote with that
1034
    /// URL, else the environment's.
1035
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
1036
        match self.remote_for_url(url) {
1037
            Some(name) => self.remote_options(&name),
1038
            None => RemoteOptions {
1039
                repo_id: self.id().ok(),
1040
                ..self.credentials_for(url)
1041
            },
1042
        }
1043
    }
1044
1045
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1046
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1047
    }
1048
1049
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1050
        self.oxy
1051
            .join("remotes")
1052
            .join(remote)
1053
            .join(format!("{bookmark}.serial"))
1054
    }
1055
1056
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
1057
        fs::read_to_string(self.serial_path(remote, bookmark))
1058
            .ok()
1059
            .and_then(|s| s.trim().parse().ok())
1060
    }
1061
1062
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1063
        let p = self.serial_path(remote, bookmark);
1064
        fs::create_dir_all(p.parent().unwrap())?;
1065
        write_atomic(&p, serial.to_string().as_bytes())
1066
    }
1067
1068
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1069
        self.oxy.join("remotes").join(remote).join("policy.serial")
1070
    }
1071
1072
    /// The highest policy serial `remote` has ever presented.
1073
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1074
        fs::read_to_string(self.policy_serial_path(remote))
1075
            .ok()
1076
            .and_then(|s| s.trim().parse().ok())
1077
    }
1078
1079
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
1080
        let p = self.policy_serial_path(remote);
1081
        fs::create_dir_all(p.parent().unwrap())?;
1082
        write_atomic(&p, serial.to_string().as_bytes())
1083
    }
1084
1085
    fn lazy_dir(&self) -> PathBuf {
1086
        self.oxy.join("lazy")
1087
    }
1088
1089
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
1090
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
1091
        fs::create_dir_all(self.lazy_dir())?;
1092
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
1093
    }
1094
1095
    /// Which remote promised an absent blob, if any.
1096
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
1097
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
1098
            .ok()
1099
            .map(|s| s.trim().to_string())
1100
    }
1101
1102
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
1103
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
1104
        let Some(remote_name) = self.lazy_remote(blob) else {
1105
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1106
        };
1107
        let remote = self.open_named_remote(&remote_name)?;
1108
        let objects = remote.objects(&[*blob])?;
1109
        for (ty, body) in objects {
1110
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
1111
                self.store.put(ty, &body)?;
1112
            }
1113
        }
1114
        if !self.store.has(blob) {
1115
            return fail(format!(
1116
                "{remote_name} did not send blob {}",
1117
                blob.short(12)
1118
            ));
1119
        }
1120
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
1121
        Ok(())
1122
    }
1123
1124
    /// After importing from `remote`, record every blob the changes reference
1125
    /// that the store lacks as lazily available from that remote.
1126
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
1127
        let mut n = 0;
1128
        for h in changes {
1129
            let c = self.store.get_change(h)?;
1130
            for e in &c.edits {
1131
                if let Edit::Replace { old, new, .. } = e {
1132
                    for b in [old, new].into_iter().flatten() {
1133
                        if !self.store.has(b) {
1134
                            self.register_lazy(b, remote)?;
1135
                            n += 1;
1136
                        }
1137
                    }
1138
                }
1139
            }
1140
        }
1141
        Ok(n)
1142
    }
1143
1144
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1145
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1146
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1147
        for st in view
1148
            .bookmarks
1149
            .values()
1150
            .chain(view.remotes.values().flat_map(|b| b.values()))
1151
        {
1152
            if let Ok(s) = self.store.get_state(st) {
1153
                have.extend(s.heads);
1154
            }
1155
        }
1156
        have.extend(view.workspaces.values().copied());
1157
        Ok(have.into_iter().collect())
1158
    }
1159
1160
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1161
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1162
        let remote = self.open_named_remote(remote_name)?;
1163
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1164
        let resp = remote.refs()?;
1165
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1166
        // and signed by roots we trust, or on first contact. A remote that
1167
        // once presented a policy may never present none or an older one:
1168
        // that is a downgrade. A remote that never presented one is
1169
        // unverified, and this fetch is checked only as far as possible.
1170
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1171
        let seen = self.remote_policy_serial(remote_name);
1172
        let mut unverified = false;
1173
        match &resp.policy {
1174
            Some(sp) => {
1175
                if seen.is_some_and(|s| sp.policy.serial < s) {
1176
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
1177
                }
1178
                match &local_policy {
1179
                    Some(l) if sp.policy.serial < l.serial => {}
1180
                    Some(l) if sp.policy.serial == l.serial => {
1181
                        if sp.policy.hash() != l.hash() {
1182
                            return fail(format!(
1183
                                "{remote_name} presents a different policy with the same serial {}",
1184
                                l.serial
1185
                            ));
1186
                        }
1187
                    }
1188
                    _ => {
1189
                        self.adopt_policy_chain(
1190
                            &resp.history,
1191
                            sp,
1192
                            &format!("oxy fetch {remote_name}"),
1193
                        )
1194
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1195
                    }
1196
                }
1197
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1198
            }
1199
            None => {
1200
                if seen.is_some() {
1201
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1202
                }
1203
                unverified = true;
1204
            }
1205
        }
1206
        let policy = if unverified {
1207
            None
1208
        } else {
1209
            self.current_policy()?.map(|(_, sp)| sp.policy)
1210
        };
1211
        let (op_ref, op) = self.head_op()?;
1212
        let mut view = op.view.clone();
1213
        let have = self.known_heads(&view)?;
1214
        let mut report = Vec::new();
1215
        let max_blob = self.config.max_blob;
1216
        for r in resp.refs {
1217
            let needed = {
1218
                let _t = crate::timing::phase("fetch: negotiate");
1219
                remote.negotiate(&have, &r.heads)?
1220
            };
1221
            let bundle = {
1222
                let _t = crate::timing::phase("fetch: bundle");
1223
                remote.fetch(&needed, max_blob)?
1224
            };
1225
            // Changes are not individually re-verified here: the bookmark's
1226
            // attestation (checked below) binds its whole state, and the
1227
            // receiver of the push verified the added changes at that time.
1228
            let imported = {
1229
                let _t = crate::timing::phase("fetch: import");
1230
                self.import_bundle(&bundle, false)?
1231
            };
1232
            if max_blob.is_some() {
1233
                self.register_missing_blobs(&imported, remote_name)?;
1234
            }
1235
            for h in &r.heads {
1236
                if !self.store.has(h) {
1237
                    return fail(format!("remote did not send head {}", h.short(12)));
1238
                }
1239
            }
1240
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1241
            if state != r.state {
1242
                return fail(format!(
1243
                    "remote state {} does not match its heads",
1244
                    r.state.short(12)
1245
                ));
1246
            }
1247
            if let Some(p) = &policy {
1248
                let Some(sa) = &r.attestation else {
1249
                    return fail(format!(
1250
                        "{remote_name}/{} has no attestation, which its policy requires",
1251
                        r.name
1252
                    ));
1253
                };
1254
                let signer = sa
1255
                    .sigs
1256
                    .first()
1257
                    .map(|s| s.key)
1258
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1259
                if !p.authorizes(&signer, &r.name)
1260
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1261
                {
1262
                    return fail(format!(
1263
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1264
                        r.name,
1265
                        signer.short(12)
1266
                    ));
1267
                }
1268
            }
1269
            if let Some(sa) = &r.attestation {
1270
                let AttestBody::Ref {
1271
                    old_state,
1272
                    new_state,
1273
                    ..
1274
                } = &sa.attest.body
1275
                else {
1276
                    return fail("remote sent a non-ref attestation for a bookmark");
1277
                };
1278
                let (old_state, new_state) = (*old_state, *new_state);
1279
                let serial = self
1280
                    .check_ref_attest(
1281
                        sa,
1282
                        &r.name,
1283
                        &old_state,
1284
                        &new_state,
1285
                        self.last_seen_serial(remote_name, &r.name),
1286
                        true,
1287
                    )
1288
                    .map_err(|e| {
1289
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
1290
                    })?;
1291
                if new_state != r.state {
1292
                    return fail(format!(
1293
                        "attestation for {}/{} does not cover its current state",
1294
                        remote_name, r.name
1295
                    ));
1296
                }
1297
                let ar = self.store.put_attest(&sa.attest)?;
1298
                for sig in &sa.sigs {
1299
                    self.store.put_signature(&ar, sig)?;
1300
                }
1301
                self.record_serial(remote_name, &r.name, serial)?;
1302
            }
1303
            view.remotes
1304
                .entry(remote_name.to_string())
1305
                .or_default()
1306
                .insert(r.name.clone(), state);
1307
            report.push((r.name, r.heads, imported.len()));
1308
        }
1309
        let mut new_tags = 0;
1310
        for t in &resp.tags {
1311
            if view.tags.contains_key(&t.name) {
1312
                continue;
1313
            }
1314
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
1315
            let missing: Vec<ChangeHash> = t
1316
                .heads
1317
                .iter()
1318
                .filter(|h| !self.store.has(h))
1319
                .copied()
1320
                .collect();
1321
            if !missing.is_empty() {
1322
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1323
                let bundle = remote.fetch(&needed, max_blob)?;
1324
                self.import_bundle(&bundle, false)?;
1325
            }
1326
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1327
            self.adopt_tag(&mut view, t, policy.as_ref())
1328
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
1329
            new_tags += 1;
1330
        }
1331
        if view != op.view {
1332
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1333
        }
1334
        let _ = self.run_hook(
1335
            "post-fetch",
1336
            &format!(
1337
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1338
                json_str(remote_name),
1339
                json_array(report.iter().map(|(n, heads, _)| format!(
1340
                    "{{\"name\":{},\"heads\":{}}}",
1341
                    json_str(n),
1342
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1343
                )))
1344
            ),
1345
        );
1346
        Ok(FetchReport {
1347
            refs: report,
1348
            unverified,
1349
            new_tags,
1350
        })
1351
    }
1352
1353
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1354
    /// the changes within `depth` steps of its heads, and the boundary below.
1355
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1356
        let remote = self.open_named_remote(remote_name)?;
1357
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1358
        let resp = remote.refs()?;
1359
        let bookmark = self.config.bookmark.clone();
1360
        if let Some(sp) = &resp.policy {
1361
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1362
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1363
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1364
        }
1365
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1366
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1367
        };
1368
        if r.heads.is_empty() {
1369
            return Ok(0);
1370
        }
1371
        // Base: the remote's checkpoint of exactly these heads.
1372
        let cp_bundle = remote.checkpoint(&r.heads)?;
1373
        let mut cp_ref = None;
1374
        for (ty, body) in &cp_bundle.objects {
1375
            let put = self.store.put(*ty, body)?;
1376
            if *ty == ObjectType::Checkpoint {
1377
                cp_ref = Some(put);
1378
            }
1379
        }
1380
        let Some(cp_ref) = cp_ref else {
1381
            return fail(format!("{remote_name} sent no checkpoint"));
1382
        };
1383
        self.install_checkpoint(&bookmark, &cp_ref)?;
1384
        // History window.
1385
        let wanted = remote.shallow(&r.heads, depth)?;
1386
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1387
        let imported = self.import_bundle_shallow(&bundle, false)?;
1388
        if self.config.max_blob.is_some() {
1389
            self.register_missing_blobs(&imported, remote_name)?;
1390
        }
1391
        self.refresh_boundary(&imported)?;
1392
        if let Some(sa) = &r.attestation {
1393
            let ar = self.store.put_attest(&sa.attest)?;
1394
            for sig in &sa.sigs {
1395
                self.store.put_signature(&ar, sig)?;
1396
            }
1397
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1398
                self.record_serial(remote_name, &r.name, serial)?;
1399
            }
1400
        }
1401
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1402
        let (op_ref, op) = self.head_op()?;
1403
        let mut view = op.view.clone();
1404
        view.remotes
1405
            .entry(remote_name.to_string())
1406
            .or_default()
1407
            .insert(r.name.clone(), state);
1408
        self.record_op(
1409
            &[op_ref],
1410
            &format!("oxy fetch {remote_name} --depth {depth}"),
1411
            view,
1412
        )?;
1413
        Ok(imported.len())
1414
    }
1415
1416
    /// Fetch, then take the union of the local bookmark's state with the
1417
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1418
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1419
        let _wc = self.lock_working_copy()?;
1420
        self.fetch(remote_name)?;
1421
        let (op_ref, op) = self.head_op()?;
1422
        let current = self.config.bookmark.clone();
1423
        let mut local_current = self.heads_of(&op.view, &current)?;
1424
        local_current.sort();
1425
        let mut view = op.view.clone();
1426
        let mut current_heads = local_current.clone();
1427
        let mut changed = false;
1428
        let mut others = Vec::new();
1429
        let tracked = op
1430
            .view
1431
            .remotes
1432
            .get(remote_name)
1433
            .cloned()
1434
            .unwrap_or_default();
1435
        for (name, remote_state) in tracked {
1436
            // Every local bookmark tracks the remote's of the same name;
1437
            // the current one may be new here.
1438
            let local_state = op.view.bookmarks.get(&name).copied();
1439
            if local_state.is_none() && name != current {
1440
                continue;
1441
            }
1442
            if local_state == Some(remote_state) {
1443
                continue;
1444
            }
1445
            let local = self.heads_of(&op.view, &name)?;
1446
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1447
            if remote_heads.iter().all(|h| local.contains(h)) {
1448
                continue;
1449
            }
1450
            let mut all = local.clone();
1451
            all.extend(remote_heads);
1452
            let st = self.load_state_history(&all)?;
1453
            let mut heads = st.maximal(&all);
1454
            heads.sort();
1455
            let mut sorted_local = local;
1456
            sorted_local.sort();
1457
            if heads == sorted_local {
1458
                continue;
1459
            }
1460
            view.bookmarks.insert(
1461
                name.clone(),
1462
                self.store.put_state(&StateObject::new(heads.clone()))?,
1463
            );
1464
            if name == current {
1465
                changed = true;
1466
                current_heads = heads;
1467
            } else {
1468
                others.push(name);
1469
            }
1470
        }
1471
        if !changed && others.is_empty() {
1472
            return Ok(PullReport {
1473
                heads: local_current,
1474
                changed: false,
1475
                checked_out: false,
1476
                others,
1477
            });
1478
        }
1479
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1480
        let mut checked_out = false;
1481
        if changed {
1482
            // Follow along if the working copy was clean and on the old heads.
1483
            let snap = self.snapshot("oxy pull")?;
1484
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1485
            let mut base = snap.base.maximal(&snap.wc.deps);
1486
            base.sort();
1487
            if clean && base == local_current {
1488
                self.checkout(&current_heads, false, "oxy pull (checkout)")?;
1489
                checked_out = true;
1490
            }
1491
        }
1492
        Ok(PullReport {
1493
            heads: current_heads,
1494
            changed,
1495
            checked_out,
1496
            others,
1497
        })
1498
    }
1499
1500
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1501
    /// changes and attesting the reference when a key is available.
1502
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1503
    /// state, attested when we have an identity. The local bookmark, if
1504
    /// any, is kept; only the remote-tracking entry goes.
1505
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
1506
        let remote = self.open_named_remote(remote_name)?;
1507
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1508
        let resp = remote.refs()?;
1509
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
1510
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1511
        };
1512
        if resp.policy.is_some() && self.secret_key()?.is_none() {
1513
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
1514
        }
1515
        let attestation = match self.secret_key()? {
1516
            Some(_) => Some(self.sign_attest(&Attest {
1517
                repo: self.id()?,
1518
                hlc: Hlc::now(),
1519
                body: AttestBody::Ref {
1520
                    name: bookmark.to_string(),
1521
                    old_state: r.state,
1522
                    new_state: ObjectRef::ZERO,
1523
                    serial: r.last_serial.unwrap_or(0) + 1,
1524
                },
1525
            })?),
1526
            None => None,
1527
        };
1528
        let results = remote.push(
1529
            Bundle::default(),
1530
            vec![RefUpdate {
1531
                name: bookmark.to_string(),
1532
                old_state: r.state,
1533
                new_state: ObjectRef::ZERO,
1534
                force: true,
1535
                attestation,
1536
            }],
1537
            None,
1538
            vec![],
1539
        )?;
1540
        if results.iter().any(|x| x.ok && x.name == bookmark) {
1541
            let (op_ref, op) = self.head_op()?;
1542
            let mut view = op.view.clone();
1543
            if let Some(m) = view.remotes.get_mut(remote_name) {
1544
                m.remove(bookmark);
1545
            }
1546
            self.record_op(
1547
                &[op_ref],
1548
                &format!("oxy push {remote_name} --delete {bookmark}"),
1549
                view,
1550
            )?;
1551
        }
1552
        Ok(results)
1553
    }
1554
1555
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1556
        let bookmark = self.config.bookmark.clone();
1557
        self.push_bookmark(remote_name, &bookmark, force)
1558
    }
1559
1560
    /// `push` for a named bookmark (`oxy push -b NAME`).
1561
    pub fn push_bookmark(
1562
        &self,
1563
        remote_name: &str,
1564
        bookmark: &str,
1565
        force: bool,
1566
    ) -> Result<Vec<RefResult>> {
1567
        let (op_ref, op) = self.head_op()?;
1568
        if !op.view.bookmarks.contains_key(bookmark) {
1569
            return fail(format!("no bookmark {bookmark}"));
1570
        }
1571
        let bookmark = bookmark.to_string();
1572
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1573
        // pre-push hook: may veto before the remote is contacted.
1574
        self.run_hook(
1575
            "pre-push",
1576
            &format!(
1577
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1578
                json_str(remote_name),
1579
                json_str(&bookmark),
1580
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1581
            ),
1582
        )?;
1583
        let remote = self.open_named_remote(remote_name)?;
1584
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1585
        let resp = remote.refs()?;
1586
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1587
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1588
        let policy_to_send = match (&local_policy, &resp.policy) {
1589
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1590
            (Some(l), None) => Some(l.clone()),
1591
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
1592
                return fail(format!(
1593
                    "{remote_name} has a newer policy (serial {}); fetch first",
1594
                    r.policy.serial
1595
                ));
1596
            }
1597
            _ => None,
1598
        };
1599
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1600
        if remote_has_policy && self.secret_key()?.is_none() {
1601
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1602
        }
1603
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1604
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1605
            .tag_refs()?
1606
            .into_iter()
1607
            .filter(|t| !remote_tags.contains(&t.name))
1608
            .collect();
1609
        let refs = resp.refs;
1610
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1611
        let (remote_state, remote_heads, last_serial) =
1612
            match refs.iter().find(|r| r.name == bookmark) {
1613
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1614
                None => (empty, vec![], None),
1615
            };
1616
        let new_state = self
1617
            .store
1618
            .put_state(&StateObject::new(local_heads.clone()))?;
1619
        // A push that carries a policy re-attests the bookmark even when its
1620
        // state is unchanged, so the current attestation is always by a key
1621
        // the current policy authorizes (a revoked key's attestation would
1622
        // otherwise be refused by every later fetch).
1623
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
1624
            return Ok(vec![RefResult {
1625
                name: bookmark,
1626
                ok: true,
1627
                reason: "already up to date".into(),
1628
            }]);
1629
        }
1630
        for h in &remote_heads {
1631
            if !self.store.has(h) {
1632
                return fail(format!(
1633
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
1634
                    h.short(12)
1635
                ));
1636
            }
1637
        }
1638
        if !force {
1639
            let closure = self.closure_in_store(&local_heads)?;
1640
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1641
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1642
            }
1643
        }
1644
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1645
        let mut bundle = self.bundle_for(&to_send)?;
1646
        let key = self.secret_key()?.map(|(k, _)| k);
1647
        if let Some(key) = key {
1648
            // Seal this author's changes that carry no valid authenticator,
1649
            // and adopt anonymous ones (zero author, spec §14.4).
1650
            let mut unsigned = Vec::new();
1651
            for h in &to_send {
1652
                let c = self.store.get_change(h)?;
1653
                if (c.author == key || c.author.is_zero())
1654
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1655
                {
1656
                    unsigned.push(*h);
1657
                }
1658
            }
1659
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
1660
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1661
                bundle.attests.push(sa);
1662
            }
1663
            bundle = self.bundle_for(&to_send)?;
1664
        }
1665
        bundle.objects.push((
1666
            ObjectType::State,
1667
            StateObject::new(local_heads.clone()).encode(),
1668
        ));
1669
        let attestation = match key {
1670
            Some(_) => Some(self.sign_attest(&Attest {
1671
                repo: self.id()?,
1672
                hlc: Hlc::now(),
1673
                body: AttestBody::Ref {
1674
                    name: bookmark.clone(),
1675
                    old_state: remote_state,
1676
                    new_state,
1677
                    serial: next_serial(last_serial),
1678
                },
1679
            })?),
1680
            None => None,
1681
        };
1682
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1683
            AttestBody::Ref { serial, .. } => Some(serial),
1684
            _ => None,
1685
        });
1686
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1687
        // Tag states must be present on the remote: bundle their changes too.
1688
        for t in &tags_to_send {
1689
            let extra = self.negotiate(&remote_heads, &t.heads)?;
1690
            let extra: Vec<ChangeHash> =
1691
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
1692
            if !extra.is_empty() {
1693
                let more = self.bundle_for(&extra)?;
1694
                bundle.changes.extend(more.changes);
1695
                bundle.hashes.extend(more.hashes);
1696
                bundle.attests.extend(more.attests);
1697
                bundle.objects.extend(more.objects);
1698
            }
1699
            bundle.objects.push((
1700
                ObjectType::State,
1701
                StateObject::new(t.heads.clone()).encode(),
1702
            ));
1703
        }
1704
        if let Some(l) = &policy_to_send {
1705
            let remote_serial = resp_policy_serial;
1706
            bundle.policies = self
1707
                .policy_history()?
1708
                .into_iter()
1709
                .filter(|sp| {
1710
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1711
                        && sp.policy.serial < l.policy.serial
1712
                })
1713
                .collect();
1714
        }
1715
        let results = remote.push(
1716
            bundle,
1717
            vec![RefUpdate {
1718
                name: bookmark.clone(),
1719
                old_state: remote_state,
1720
                new_state,
1721
                force,
1722
                attestation,
1723
            }],
1724
            policy_to_send,
1725
            tags_to_send,
1726
        )?;
1727
        if let (Some(serial), true) = (
1728
            sent_serial,
1729
            results.iter().any(|r| r.ok && r.name == "policy"),
1730
        ) {
1731
            self.record_policy_serial(remote_name, serial)?;
1732
        }
1733
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1734
            let mut view = op.view.clone();
1735
            view.remotes
1736
                .entry(remote_name.to_string())
1737
                .or_default()
1738
                .insert(bookmark.clone(), new_state);
1739
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1740
            if let Some(s) = serial {
1741
                self.record_serial(remote_name, &bookmark, s)?;
1742
            }
1743
        }
1744
        Ok(results)
1745
    }
1746
1747
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1748
    /// bookmark set to the remote's, working copy checked out.
1749
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1750
        Self::clone_with(url, dest, None, &[])
1751
    }
1752
1753
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1754
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1755
    /// unless a size is given, so out-of-scope binaries are never fetched).
1756
    pub fn clone_with(
1757
        url: &str,
1758
        dest: &Path,
1759
        max_blob: Option<u64>,
1760
        sparse: &[String],
1761
    ) -> Result<Repo> {
1762
        Self::clone_full(url, dest, max_blob, sparse, None)
1763
    }
1764
1765
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1766
    /// changes within `depth` steps of them; the rest is the boundary.
1767
    pub fn clone_shallow(
1768
        url: &str,
1769
        dest: &Path,
1770
        depth: u32,
1771
        max_blob: Option<u64>,
1772
        sparse: &[String],
1773
    ) -> Result<Repo> {
1774
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1775
    }
1776
1777
    fn clone_full(
1778
        url: &str,
1779
        dest: &Path,
1780
        max_blob: Option<u64>,
1781
        sparse: &[String],
1782
        depth: Option<u32>,
1783
    ) -> Result<Repo> {
1784
        let options = crate::credentials::Credentials::user().options_for(url);
1785
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1786
    }
1787
1788
    /// Clone a subrepo with the credentials the parent would use for its
1789
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1790
    /// subrepo: it finds the same ones again through its parent.
1791
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
1792
        let options = self.credentials_for(url);
1793
        Self::clone_using(url, dest, None, &[], None, &options)
1794
    }
1795
1796
    /// The name of a remote of this repository on the same hub (scheme,
1797
    /// host and port) as `url`.
1798
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
1799
        let origin = |u: &str| -> Option<String> {
1800
            let (scheme, rest) = u.split_once("://")?;
1801
            if !matches!(scheme, "http" | "https") {
1802
                return None;
1803
            }
1804
            let host = rest.split('/').next()?;
1805
            Some(format!(
1806
                "{}://{}",
1807
                scheme.to_ascii_lowercase(),
1808
                host.to_ascii_lowercase()
1809
            ))
1810
        };
1811
        let want = origin(url)?;
1812
        self.config
1813
            .remotes
1814
            .iter()
1815
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
1816
            .map(|(name, _)| name.clone())
1817
    }
1818
1819
    /// The token and CA to reach `url` with: those of a remote of this
1820
    /// repository on the same hub (scheme, host and port), else the
1821
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
1822
    /// and enclosing checkouts', as a clone would use them.
1823
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
1824
        match self.remote_on_same_hub(url) {
1825
            Some(name) => RemoteOptions {
1826
                repo_id: None,
1827
                cache_dir: None,
1828
                ..self.remote_options(&name)
1829
            },
1830
            None => {
1831
                let mut options = RemoteOptions::default();
1832
                self.fill_credentials(url, &mut options);
1833
                options
1834
            }
1835
        }
1836
    }
1837
1838
    fn clone_using(
1839
        url: &str,
1840
        dest: &Path,
1841
        max_blob: Option<u64>,
1842
        sparse: &[String],
1843
        depth: Option<u32>,
1844
        options: &RemoteOptions,
1845
    ) -> Result<Repo> {
1846
        let remote = open_remote(url, options)?;
1847
        let id = remote.repo_id()?;
1848
        if id == crate::protocol::UNBOUND_ID {
1849
            return fail(format!(
1850
                "{url} is empty and unbound: push a repository to it first"
1851
            ));
1852
        }
1853
        let mut repo = Repo::init_with_id(dest, id)?;
1854
        repo.config
1855
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
1856
        if let Some(m) = max_blob {
1857
            repo.config.set("filter.max-blob", &m.to_string())?;
1858
        } else if !sparse.is_empty() {
1859
            repo.config.set("filter.max-blob", "0")?;
1860
        }
1861
        if !sparse.is_empty() {
1862
            repo.config.set("filter.paths", &sparse.join(","))?;
1863
        }
1864
        repo.save_config()?;
1865
        if let Some(depth) = depth {
1866
            repo.fetch_shallow("origin", depth)?;
1867
        } else {
1868
            repo.fetch("origin")?;
1869
        }
1870
        let (op_ref, op) = repo.head_op()?;
1871
        // The remote's default bookmark, else ours (main), else its only one.
1872
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
1873
        // Asked of the remote as now configured, so a store-backed one
1874
        // answers from the mirror the fetch just filled.
1875
        let advertised = repo
1876
            .open_named_remote("origin")
1877
            .ok()
1878
            .and_then(|r| r.refs().ok())
1879
            .and_then(|r| r.default_bookmark);
1880
        let bookmark = advertised
1881
            .filter(|b| theirs.contains_key(b))
1882
            .or_else(|| {
1883
                theirs
1884
                    .contains_key(&repo.config.bookmark)
1885
                    .then(|| repo.config.bookmark.clone())
1886
            })
1887
            .or_else(|| {
1888
                (theirs.len() == 1)
1889
                    .then(|| theirs.keys().next().cloned())
1890
                    .flatten()
1891
            })
1892
            .unwrap_or_else(|| repo.config.bookmark.clone());
1893
        let initial = repo.config.bookmark.clone();
1894
        if bookmark != repo.config.bookmark {
1895
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
1896
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
1897
            repo.config.bookmark = bookmark.clone();
1898
        }
1899
        if let Some(state) = theirs.get(&bookmark).copied() {
1900
            let heads = repo.store.get_state(&state)?.heads;
1901
            let mut view = op.view.clone();
1902
            // The empty bookmark `init` made goes when another is checked out.
1903
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
1904
                view.bookmarks.remove(&initial);
1905
            }
1906
            view.bookmarks.insert(bookmark, state);
1907
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1908
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
1909
        }
1910
        Ok(repo)
1911
    }
1912
}
1913
1914
/// The serial of a reference's next attestation: one more than the last the
1915
/// remote reports, or, for a bookmark the remote does not have, the clock in
1916
/// milliseconds, so a bookmark created again after a deletion goes past the
1917
/// deletion's serial the remote keeps.
1918
fn next_serial(last: Option<u64>) -> u64 {
1919
    match last {
1920
        Some(l) => l + 1,
1921
        None => Hlc::now().wall_ms.max(1),
1922
    }
1923
}