OXYGENHUB
◆ v0.7.0 oxygen / crates / oxy-core / src / repo / sync.rs
118.4 KiB · Rust · last changed Pushing a new bookmark sends only what the remote lacks (closes #142) 10 days ago source blame history raw
1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::tags::TagCheck;
4
use super::*;
5
6
/// What a push did, for hosts (hub spec §6.12).
7
#[derive(Clone, Debug, Default)]
8
pub struct PushReport {
9
    pub results: Vec<RefResult>,
10
    /// Accepted reference updates, in request order.
11
    pub updated: Vec<RefUpdated>,
12
    /// Changes this push stored that were not already present.
13
    pub imported: Vec<ChangeHash>,
14
}
15
16
#[derive(Clone, Debug)]
17
pub struct RefUpdated {
18
    pub name: String,
19
    pub old_state: ObjectRef,
20
    pub new_state: ObjectRef,
21
    pub heads: Vec<ChangeHash>,
22
}
23
24
/// What a fetch brought in.
25
#[derive(Debug, Clone, PartialEq, Eq, Default)]
26
pub struct FetchReport {
27
    /// Bookmark name, its heads, and how many changes were new.
28
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
29
    /// Tags adopted from the remote.
30
    pub new_tags: usize,
31
    /// Tags the remote withdrew, and so withdrawn here (oxygenhub#301).
32
    pub withdrawn_tags: Vec<String>,
33
    /// The remote has never presented a policy, so nothing was verified
34
    /// against one (spec §14.5: warn loudly).
35
    pub unverified: bool,
36
    /// What checking the host's transparency log found short of a fork
37
    /// (spec §14.8): attestations not logged yet, a log that could not be
38
    /// read. A fork fails the fetch instead.
39
    pub log_notes: Vec<String>,
40
    /// Bookmarks left as they were because their attestation could not be
41
    /// verified (its signer unknown here, or its signature bad), each with
42
    /// why (oxygenhub#266). The current bookmark is never skipped: its
43
    /// fetch fails instead.
44
    pub skipped: Vec<(String, String)>,
45
}
46
47
#[derive(Debug, Clone, PartialEq, Eq)]
48
pub struct PullReport {
49
    /// The current bookmark's heads after the pull.
50
    pub heads: Vec<ChangeHash>,
51
    /// Whether the current bookmark changed.
52
    pub changed: bool,
53
    pub checked_out: bool,
54
    /// Other bookmarks the pull moved: each local bookmark tracks the
55
    /// remote's of the same name.
56
    pub others: Vec<String>,
57
    /// What the fetch left as it was ([`FetchReport::skipped`]).
58
    pub skipped: Vec<(String, String)>,
59
}
60
61
/// The result a push of objects alone reports (a batch of a long history):
62
/// not a reference.
63
pub const OBJECTS_RESULT: &str = "objects";
64
65
impl Repo {
66
    // ------------------------------------------------------------ serving (spec §16)
67
68
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
69
        self.oxy.join("attest").join(name_file(bookmark))
70
    }
71
72
    /// The latest reference attestation stored for a bookmark.
73
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
74
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
75
            Ok(h) => {
76
                let r = ObjectRef::from_hex(h.trim())
77
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
78
                Ok(Some((
79
                    r,
80
                    SignedAttest {
81
                        attest: self.store.get_attest(&r)?,
82
                        sigs: self.store.signatures(&r)?,
83
                    },
84
                )))
85
            }
86
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
87
            Err(e) => Err(e.into()),
88
        }
89
    }
90
91
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
92
        fs::create_dir_all(self.oxy.join("attest"))?;
93
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
94
    }
95
96
    pub fn remote_refs(&self) -> Result<RefsResponse> {
97
        let view = self.view()?;
98
        let mut out = Vec::new();
99
        for (name, state) in &view.bookmarks {
100
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
101
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
102
                AttestBody::Ref { serial, .. } => Some(serial),
103
                _ => None,
104
            });
105
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
106
            let accepted = match &attestation {
107
                Some(a) => self.acceptance_of(&a.attest.hash())?,
108
                None => None,
109
            };
110
            out.push(RemoteRef {
111
                name: name.clone(),
112
                state: *state,
113
                heads: self.store.get_state(state)?.heads,
114
                attestation,
115
                last_serial,
116
                accepted,
117
                logged: None,
118
                integration: vec![],
119
            });
120
        }
121
        let policy = self.current_policy()?.map(|(_, sp)| sp);
122
        let history = self
123
            .policy_history()?
124
            .into_iter()
125
            .filter(|sp| {
126
                policy
127
                    .as_ref()
128
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
129
            })
130
            .collect();
131
        Ok(RefsResponse {
132
            refs: out,
133
            policy,
134
            tags: self.tag_refs()?,
135
            history,
136
            default_bookmark: Some(self.config.bookmark.clone()),
137
            log: None,
138
            witnesses: vec![],
139
            withdrawn: self.withdrawn_refs()?,
140
        })
141
    }
142
143
    /// Every change reachable from `heads` that is in the store.
144
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
145
        let mut seen = BTreeSet::new();
146
        let mut stack: Vec<ChangeHash> = heads.to_vec();
147
        while let Some(h) = stack.pop() {
148
            if seen.contains(&h) || !self.store.has(&h) {
149
                continue;
150
            }
151
            seen.insert(h);
152
            stack.extend(self.store.get_change_meta(&h)?.deps);
153
        }
154
        Ok(seen)
155
    }
156
157
    /// The changes within `depth` dependency steps of `heads` (spec §17),
158
    /// nearest first; depth 1 is the heads themselves.
159
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
160
        let mut out = Vec::new();
161
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
162
        let mut layer: Vec<ChangeHash> = heads.to_vec();
163
        for _ in 0..depth.max(1) {
164
            let mut next = Vec::new();
165
            for h in layer {
166
                if !seen.insert(h) || !self.store.has(&h) {
167
                    continue;
168
                }
169
                let c = self.store.get_change(&h)?;
170
                next.extend(c.deps.iter().copied());
171
                out.push(h);
172
            }
173
            if next.is_empty() {
174
                break;
175
            }
176
            layer = next;
177
        }
178
        out.reverse();
179
        Ok(out)
180
    }
181
182
    fn shallow_path(&self) -> PathBuf {
183
        self.oxy.join("shallow")
184
    }
185
186
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
187
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
188
        fs::read_to_string(self.shallow_path())
189
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
190
            .unwrap_or_default()
191
    }
192
193
    pub fn is_shallow(&self) -> bool {
194
        !self.boundary().is_empty()
195
    }
196
197
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
198
        if boundary.is_empty() {
199
            let _ = fs::remove_file(self.shallow_path());
200
            return Ok(());
201
        }
202
        let text: String = boundary
203
            .iter()
204
            .map(|h| format!("{}\n", h.to_hex()))
205
            .collect();
206
        write_atomic(&self.shallow_path(), text.as_bytes())
207
    }
208
209
    /// Recompute the boundary from what is stored: every dependency of a
210
    /// stored change that is not itself stored.
211
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
212
        let mut boundary = self.boundary();
213
        boundary.retain(|h| !self.store.has(h));
214
        for h in imported {
215
            for d in self.store.get_change_meta(h)?.deps {
216
                if !self.store.has(&d) {
217
                    boundary.insert(d);
218
                }
219
            }
220
        }
221
        self.write_boundary(&boundary)
222
    }
223
224
    /// Fetch `depth` more levels of history below the shallow boundary.
225
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
226
        let boundary = self.boundary();
227
        if boundary.is_empty() {
228
            return Ok(0);
229
        }
230
        let remote = self.open_named_remote(remote_name)?;
231
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
232
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
233
        let imported = self.import_bundle_shallow(&bundle, false)?;
234
        if self.config.max_blob.is_some() {
235
            self.register_missing_blobs(&imported, remote_name)?;
236
        }
237
        self.refresh_boundary(&imported)?;
238
        Ok(imported.len())
239
    }
240
241
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
242
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
243
        let have = self.closure_in_store(have)?;
244
        // In a shallow repository the walk stops at the boundary, whose
245
        // changes the remote is assumed to hold.
246
        let boundary = self.boundary();
247
        let mut out = Vec::new();
248
        let mut done: BTreeSet<ChangeHash> = have.clone();
249
        done.extend(boundary.iter().copied());
250
        // Iterative post-order DFS.
251
        let shallow = self.is_shallow();
252
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
253
        while let Some((h, expanded)) = stack.pop() {
254
            if done.contains(&h) {
255
                continue;
256
            }
257
            if !self.store.has(&h) {
258
                // A shallow repository holds only part of its history; a
259
                // change it lacks is below what it cloned (in a depth-0
260
                // clone, any change of the checkpoint), which the remote
261
                // is assumed to hold, as it is for the boundary (#137).
262
                if shallow {
263
                    done.insert(h);
264
                    continue;
265
                }
266
                return fail(format!("change {} is not in this repository", h.short(12)));
267
            }
268
            if expanded {
269
                done.insert(h);
270
                out.push(h);
271
                continue;
272
            }
273
            stack.push((h, true));
274
            for d in self.store.get_change_meta(&h)?.deps {
275
                if !done.contains(&d) {
276
                    stack.push((d, false));
277
                }
278
            }
279
        }
280
        Ok(out)
281
    }
282
283
    /// Bundle changes (in the given dependency order) with their signatures,
284
    /// seals, identities, blobs, chunks.
285
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
286
        self.bundle_of(changes, None, false, false)
287
    }
288
289
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
290
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
291
        let mut out = Vec::new();
292
        for r in refs {
293
            let (ty, body) = match self.store.get(r) {
294
                Ok(x) => x,
295
                Err(StoreError::NotFound(_)) => continue,
296
                Err(e) => return Err(e.into()),
297
            };
298
            if ty == ObjectType::Blob {
299
                for c in Blob::decode(&body)?.chunks {
300
                    if let Ok((cty, cb)) = self.store.get(&c) {
301
                        out.push((cty, cb));
302
                    }
303
                }
304
            }
305
            out.push((ty, body));
306
        }
307
        Ok(out)
308
    }
309
310
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
311
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
312
    ///
313
    /// This is what a server answers a fetch with, so it also carries what
314
    /// verifies the attestations it serves beside it (see
315
    /// [`Repo::served_attest_signers`]), also when `changes` is empty.
316
    pub fn bundle_for_filtered(
317
        &self,
318
        changes: &[ChangeHash],
319
        max_blob: Option<u64>,
320
    ) -> Result<Bundle> {
321
        self.bundle_of(changes, max_blob, false, true)
322
    }
323
324
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
325
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
326
    /// with their text blobs and chunks among the objects, so neither side
327
    /// decodes or encodes their text.
328
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
329
        self.bundle_of(changes, max_blob, true, true)
330
    }
331
332
    /// The keys that signed the attestations this repository serves with
333
    /// its references: each bookmark's latest and each tag's. A fetch
334
    /// bundle carries their identities and certificates (spec §16.2), so a
335
    /// client can check an attestation whose signer signed none of the
336
    /// changes it receives, a delegate or a short-lived key that only
337
    /// moved a bookmark (oxygenhub#266). One pointer and one signature
338
    /// list per reference, computed once per operation head and kept
339
    /// (every bookmark move and tag is an operation): a client sends one
340
    /// fetch per bookmark, and on a bucket store each signature list is a
341
    /// LIST request, so recomputing per fetch cost metalgear2 (145
342
    /// bookmarks) 14 s a fetch.
343
    pub fn served_attest_signers(&self) -> Result<BTreeSet<KeyId>> {
344
        type Signers = std::collections::HashMap<(PathBuf, ObjectRef), BTreeSet<KeyId>>;
345
        static SERVED: std::sync::Mutex<Option<Signers>> = std::sync::Mutex::new(None);
346
        let key = (self.oxy.clone(), self.head_op()?.0);
347
        if let Some(keys) = SERVED
348
            .lock()
349
            .unwrap_or_else(|p| p.into_inner())
350
            .as_ref()
351
            .and_then(|m| m.get(&key))
352
        {
353
            return Ok(keys.clone());
354
        }
355
        let keys = self.attest_signers_now()?;
356
        let mut served = SERVED.lock().unwrap_or_else(|p| p.into_inner());
357
        let map = served.get_or_insert_with(Default::default);
358
        // One entry per repository: an older operation head is never asked
359
        // for again once a newer one is current.
360
        map.retain(|(oxy, _), _| *oxy != key.0);
361
        if map.len() >= 1024 {
362
            map.clear();
363
        }
364
        map.insert(key, keys.clone());
365
        Ok(keys)
366
    }
367
368
    fn attest_signers_now(&self) -> Result<BTreeSet<KeyId>> {
369
        let view = self.view()?;
370
        let pointers = view
371
            .bookmarks
372
            .keys()
373
            .map(|b| self.ref_attest_path(b))
374
            .chain(view.tags.keys().map(|t| self.tag_attest_path(t)));
375
        let mut keys = BTreeSet::new();
376
        for p in pointers {
377
            let Ok(text) = fs::read_to_string(&p) else {
378
                continue;
379
            };
380
            let Some(r) = ObjectRef::from_hex(text.trim()) else {
381
                continue;
382
            };
383
            keys.extend(self.store.signatures(&r)?.into_iter().map(|s| s.key));
384
        }
385
        Ok(keys)
386
    }
387
388
    /// `serving`: a fetch's answer, which carries the identities and
389
    /// certificates of [`Repo::served_attest_signers`] too.
390
    fn bundle_of(
391
        &self,
392
        changes: &[ChangeHash],
393
        max_blob: Option<u64>,
394
        raw: bool,
395
        serving: bool,
396
    ) -> Result<Bundle> {
397
        let mut bundle = Bundle::default();
398
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
399
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
400
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
401
            if !r.is_zero() && self.store.has(r) {
402
                objects.insert(*r);
403
            }
404
        };
405
        for h in changes {
406
            // Raw: the stored bytes, and a skeleton for the rest.
407
            let (c, encoded) = if raw {
408
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
409
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
410
                for t in texts {
411
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
412
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
413
                        objects.insert(r);
414
                        objects.extend(blob.chunks);
415
                    }
416
                }
417
                (skel, Some(bytes))
418
            } else {
419
                (self.store.get_change(h)?, None)
420
            };
421
            let sigs = self.store.signatures(h)?;
422
            add_object(&c.author, &mut objects);
423
            for s in &sigs {
424
                add_object(&s.key, &mut objects);
425
            }
426
            // A replacement's new content only: its old content is the new
427
            // content of a change it depends on, which the receiver holds or
428
            // which this bundle carries (oxygen#136: removing ~1,100 binary
429
            // files sent them all again).
430
            for e in &c.edits {
431
                if let Edit::Replace { new: Some(b), .. } = e {
432
                    if self.store.has(b) {
433
                        if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
434
                        {
435
                            if max_blob.is_some_and(|m| blob.length > m) {
436
                                continue;
437
                            }
438
                            objects.insert(*b);
439
                            objects.extend(blob.chunks.iter().copied());
440
                        }
441
                    }
442
                }
443
            }
444
            for s in self.store.seals_for(h)? {
445
                seals.insert(s);
446
            }
447
            match encoded {
448
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
449
                None => {
450
                    bundle.changes.push((c, sigs));
451
                    bundle.hashes.push(*h);
452
                }
453
            }
454
        }
455
        for r in seals {
456
            let attest = self.store.get_attest(&r)?;
457
            let sigs = self.store.signatures(&r)?;
458
            for s in &sigs {
459
                add_object(&s.key, &mut objects);
460
            }
461
            bundle.attests.push(SignedAttest { attest, sigs });
462
        }
463
        let signers: Vec<KeyId> = if serving {
464
            let signers = self.served_attest_signers()?;
465
            for k in &signers {
466
                add_object(k, &mut objects);
467
            }
468
            signers.into_iter().collect()
469
        } else {
470
            Vec::new()
471
        };
472
        for r in objects {
473
            let (ty, body) = self.store.get(&r)?;
474
            bundle.objects.push((ty, body));
475
        }
476
        self.attach_certificates_for(&mut bundle, &signers)?;
477
        Ok(bundle)
478
    }
479
480
    /// Add the certificates of short-lived keys that signed what `bundle`
481
    /// carries, and their issuers' identities, so a receiver can tell who
482
    /// they stand for (spec §14.7). `also` names more signers (a reference
483
    /// attestation sent beside the bundle).
484
    pub(crate) fn attach_certificates_for(
485
        &self,
486
        bundle: &mut Bundle,
487
        also: &[KeyId],
488
    ) -> Result<()> {
489
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
490
        keys.extend(
491
            bundle
492
                .changes
493
                .iter()
494
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
495
        );
496
        keys.extend(
497
            bundle
498
                .raw_changes
499
                .iter()
500
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
501
        );
502
        keys.extend(
503
            bundle
504
                .attests
505
                .iter()
506
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
507
        );
508
        for k in keys {
509
            let Some(r) = self.store.certificate_of(&k)? else {
510
                continue;
511
            };
512
            let cert = self.store.get_certificate(&r)?;
513
            if bundle
514
                .certificates
515
                .iter()
516
                .any(|c| c.cert.hash() == cert.cert.hash())
517
            {
518
                continue;
519
            }
520
            // An agent's certificate brings its grant's signer too, so the
521
            // receiver can check the grant (oxygen#134).
522
            let grantor = cert.cert.grant.as_ref().map(|g| g.grant.grantor);
523
            for id in [Some(k), Some(cert.cert.issuer), grantor].iter().flatten() {
524
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
525
                    if !bundle
526
                        .objects
527
                        .iter()
528
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
529
                    {
530
                        bundle.objects.push((ObjectType::Identity, body));
531
                    }
532
                }
533
            }
534
            bundle.certificates.push(cert);
535
        }
536
        Ok(())
537
    }
538
539
    /// Keep the certificates a bundle brings once each verifies with the
540
    /// identity of the issuer it names; one that does not refuses the bundle.
541
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
542
        for c in certs {
543
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
544
                RepoError::Msg(format!(
545
                    "a certificate names issuer {}, whose identity did not come with it",
546
                    c.cert.issuer.short(12)
547
                ))
548
            })?;
549
            c.verify(&issuer)
550
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
551
            self.store.put_identity(&c.cert.key)?;
552
            self.store.put_certificate(c)?;
553
        }
554
        Ok(())
555
    }
556
557
    /// A signer authorized for `reference` by what an issuer certified it
558
    /// as (spec §14.7): a short-lived key with a kept certificate that
559
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
560
    /// signer did not choose) and names a subject the policy grants.
561
    pub(crate) fn certified_authorized(
562
        &self,
563
        p: &crate::policy::Policy,
564
        signer: &KeyId,
565
        reference: &str,
566
        scope: Scope,
567
        at_ms: u64,
568
    ) -> bool {
569
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
570
            return false;
571
        };
572
        let Ok(c) = self.store.get_certificate(&r) else {
573
            return false;
574
        };
575
        let Some(issuer) = p
576
            .identity(&c.cert.issuer)
577
            .cloned()
578
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
579
        else {
580
            return false;
581
        };
582
        c.verify(&issuer).is_ok()
583
            && c.cert.key_id() == *signer
584
            && c.cert.covers(scope, at_ms)
585
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
586
    }
587
588
    /// Store a bundle's contents. With `strict`, every change must
589
    /// authenticate (signature or seal by its author or a delegate).
590
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
591
        self.import_bundle_inner(bundle, strict, false)
592
    }
593
594
    /// Like `import_bundle`, accepting changes whose dependencies are absent
595
    /// (they join the shallow boundary).
596
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
597
        self.import_bundle_inner(bundle, strict, true)
598
    }
599
600
    fn import_bundle_inner(
601
        &self,
602
        bundle: &Bundle,
603
        strict: bool,
604
        shallow: bool,
605
    ) -> Result<Vec<ChangeHash>> {
606
        let batch = self.store.begin_batch()?;
607
        let result = self.import_bundle_batched(bundle, strict, shallow);
608
        batch.finish()?;
609
        result
610
    }
611
612
    fn import_bundle_batched(
613
        &self,
614
        bundle: &Bundle,
615
        strict: bool,
616
        shallow: bool,
617
    ) -> Result<Vec<ChangeHash>> {
618
        for (ty, _) in &bundle.objects {
619
            if !matches!(
620
                ty,
621
                ObjectType::Chunk
622
                    | ObjectType::Blob
623
                    | ObjectType::Identity
624
                    | ObjectType::State
625
                    | ObjectType::Checkpoint
626
            ) {
627
                return fail(format!("bundle may not carry {} objects", ty.name()));
628
            }
629
        }
630
        // All at once: in a large batch they are compressed on every core.
631
        let objects: Vec<(ObjectType, &[u8])> = bundle
632
            .objects
633
            .iter()
634
            .map(|(ty, body)| (*ty, body.as_slice()))
635
            .collect();
636
        self.store.put_many(&objects)?;
637
        self.adopt_certificates(&bundle.certificates)?;
638
        for sa in &bundle.attests {
639
            let r = self.store.put_attest(&sa.attest)?;
640
            for sig in &sa.sigs {
641
                self.store.put_signature(&r, sig)?;
642
            }
643
            if let AttestBody::Seal { hashes } = &sa.attest.body {
644
                for h in hashes {
645
                    self.store.index_seal(h, &r)?;
646
                }
647
            }
648
        }
649
        // Each change's hash: from the bundle when its maker knew it, else
650
        // worked out once (for a change adding a whole tree, hashing is
651
        // chunking all its text).
652
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
653
            bundle.hashes.clone()
654
        } else {
655
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
656
        };
657
        let raw_hashes: Vec<ChangeHash> = bundle
658
            .raw_changes
659
            .iter()
660
            .map(|(b, _)| hash_object(ObjectType::Change, b))
661
            .collect();
662
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
663
        let boundary = self.boundary();
664
        let mut imported = Vec::new();
665
        // Changes as stored: checked, then stored as they are, their text
666
        // blobs having come with the objects.
667
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
668
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
669
            for d in &skel.deps {
670
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
671
                {
672
                    return fail(format!(
673
                        "change {} depends on {}, which is neither stored nor in the bundle",
674
                        h.short(12),
675
                        d.short(12)
676
                    ));
677
                }
678
            }
679
            for t in texts {
680
                if let crate::objects::TextRef::Blob(r, _, _) = t {
681
                    if !self.store.has(&r) {
682
                        return fail(format!(
683
                            "change {} came without its text blob {}",
684
                            h.short(12),
685
                            r.short(12)
686
                        ));
687
                    }
688
                }
689
            }
690
            self.store.put(ObjectType::Change, bytes)?;
691
            for sig in sigs {
692
                self.store.put_signature(&h, sig)?;
693
            }
694
            imported.push(h);
695
        }
696
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
697
            for d in &c.deps {
698
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
699
                {
700
                    return fail(format!(
701
                        "change {} depends on {}, which is neither stored nor in the bundle",
702
                        h.short(12),
703
                        d.short(12)
704
                    ));
705
                }
706
            }
707
            let stored = self.store.put_change(c)?;
708
            if stored != h {
709
                return fail(format!(
710
                    "change {} is not the change the bundle names",
711
                    h.short(12)
712
                ));
713
            }
714
            for sig in sigs {
715
                self.store.put_signature(&h, sig)?;
716
            }
717
            imported.push(h);
718
        }
719
        if strict {
720
            for h in &imported {
721
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
722
                    return fail(format!(
723
                        "change {} is not authenticated by its author",
724
                        h.short(12)
725
                    ));
726
                }
727
            }
728
        }
729
        Ok(imported)
730
    }
731
732
    /// Verify a reference attestation against an update it claims to describe.
733
    /// `allow_equal` lets a client re-read the attestation it already has; a
734
    /// server receiving a push requires a strictly greater serial.
735
    /// A reference attestation signed by a delegate of an identity the
736
    /// rule lists is authorized as that identity (spec §14.5): the identity
737
    /// named the delegate with the `refs` scope, still in force at `at_ms`
738
    /// (the attestation's wall time), and the policy names the identity.
739
    /// Revoked keys authorize nothing either way.
740
    pub(crate) fn delegate_authorized(
741
        &self,
742
        p: &crate::policy::Policy,
743
        signer: &KeyId,
744
        reference: &str,
745
        at_ms: u64,
746
    ) -> bool {
747
        if p.is_revoked(signer) {
748
            return false;
749
        }
750
        let Some(rule) = p.rule_for(reference) else {
751
            return false;
752
        };
753
        rule.keys.iter().any(|k| {
754
            !p.is_revoked(k)
755
                && p.identity(k)
756
                    .cloned()
757
                    .or_else(|| self.store.get_identity(k).ok())
758
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
759
        })
760
    }
761
762
    /// A lasting attestation (a tag) signed by a key the policy has since
763
    /// rotated away from (spec §14.2) is authorized as the key that
764
    /// succeeded it: a key the rule lists reaches the signer through
765
    /// `previous` links, and the attestation is dated (`at_ms`) before the
766
    /// signer's successor was made, so a superseded key makes nothing new.
767
    /// Revoked keys authorize nothing.
768
    pub(crate) fn predecessor_authorized(
769
        &self,
770
        p: &crate::policy::Policy,
771
        signer: &KeyId,
772
        reference: &str,
773
        at_ms: u64,
774
    ) -> bool {
775
        if p.is_revoked(signer) {
776
            return false;
777
        }
778
        let Some(rule) = p.rule_for(reference) else {
779
            return false;
780
        };
781
        let identity = |k: &KeyId| {
782
            p.identity(k)
783
                .cloned()
784
                .or_else(|| self.store.get_identity(k).ok())
785
        };
786
        rule.keys.iter().any(|k| {
787
            if p.is_revoked(k) {
788
                return false;
789
            }
790
            let mut cur = identity(k);
791
            for _ in 0..32 {
792
                let Some(id) = cur else {
793
                    return false;
794
                };
795
                match id.previous {
796
                    Some(prev) if prev == *signer => return at_ms < id.created,
797
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
798
                    _ => return false,
799
                }
800
            }
801
            false
802
        })
803
    }
804
805
    fn check_ref_attest(
806
        &self,
807
        sa: &SignedAttest,
808
        name: &str,
809
        old_state: &ObjectRef,
810
        new_state: &ObjectRef,
811
        last_serial: Option<u64>,
812
        allow_equal: bool,
813
    ) -> std::result::Result<u64, String> {
814
        let serial =
815
            self.check_ref_attest_body(sa, name, old_state, new_state, last_serial, allow_equal)?;
816
        self.verify_attest_signature(sa)?;
817
        Ok(serial)
818
    }
819
820
    /// What [`Repo::check_ref_attest`] checks short of the signature: the
821
    /// attestation describes this update of this repository with a serial
822
    /// past the last seen.
823
    fn check_ref_attest_body(
824
        &self,
825
        sa: &SignedAttest,
826
        name: &str,
827
        old_state: &ObjectRef,
828
        new_state: &ObjectRef,
829
        last_serial: Option<u64>,
830
        allow_equal: bool,
831
    ) -> std::result::Result<u64, String> {
832
        let AttestBody::Ref {
833
            name: n,
834
            old_state: o,
835
            new_state: nw,
836
            serial,
837
        } = &sa.attest.body
838
        else {
839
            return Err("attestation is not a ref attestation".into());
840
        };
841
        if n != name || o != old_state || nw != new_state {
842
            return Err("attestation does not describe this update".into());
843
        }
844
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
845
            return Err("attestation is for a different repository".into());
846
        }
847
        if let Some(last) = last_serial {
848
            if *serial < last || (*serial == last && !allow_equal) {
849
                return Err(format!(
850
                    "attestation serial {serial} is not greater than the last seen {last}"
851
                ));
852
            }
853
        }
854
        Ok(*serial)
855
    }
856
857
    /// An attestation's first signature verifies with its signer's
858
    /// identity, which must be stored here.
859
    fn verify_attest_signature(&self, sa: &SignedAttest) -> std::result::Result<(), String> {
860
        let r = sa.attest.hash();
861
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
862
        let id = self
863
            .store
864
            .get_identity(&sig.key)
865
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
866
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())
867
    }
868
869
    /// Accept a push (spec §16.4). Without a trust policy every repository
870
    /// is unverified, so unsigned changes and unattested updates are accepted;
871
    /// attestations that are present must still be valid. With a policy,
872
    /// every change and update is checked against it. A newer policy in the
873
    /// push is applied first when it is signed by the current roots.
874
    pub fn receive_push(
875
        &self,
876
        bundle: Bundle,
877
        updates: Vec<RefUpdate>,
878
        policy: Option<SignedPolicy>,
879
        tags: Vec<crate::protocol::TagRef>,
880
    ) -> Result<Vec<RefResult>> {
881
        Ok(self
882
            .receive_push_report(bundle, updates, policy, tags)?
883
            .results)
884
    }
885
886
    /// `receive_push` with what a host wants to log: each accepted
887
    /// reference's old and new state and heads, and the changes this push
888
    /// stored (hub spec §6.12).
889
    pub fn receive_push_report(
890
        &self,
891
        bundle: Bundle,
892
        updates: Vec<RefUpdate>,
893
        policy: Option<SignedPolicy>,
894
        tags: Vec<crate::protocol::TagRef>,
895
    ) -> Result<PushReport> {
896
        // Updates are checked against the head as it is now, not as this
897
        // handle first read it (oxygenhub#249): another push may have
898
        // landed since.
899
        self.refresh()?;
900
        let mut report = PushReport::default();
901
        let results = &mut report.results;
902
        if let Some(sp) = policy {
903
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
904
                Ok(()) => {
905
                    results.push(RefResult {
906
                        name: "policy".into(),
907
                        ok: true,
908
                        reason: format!("serial {}", sp.policy.serial),
909
                    });
910
                }
911
                Err(e) => {
912
                    results.push(RefResult {
913
                        name: "policy".into(),
914
                        ok: false,
915
                        reason: e,
916
                    });
917
                    for u in updates {
918
                        results.push(RefResult {
919
                            name: u.name,
920
                            ok: false,
921
                            reason: "policy update was rejected".into(),
922
                        });
923
                    }
924
                    return Ok(report);
925
                }
926
            }
927
        }
928
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
929
        // A push of objects alone (one batch of a long history, oxygen#95)
930
        // names no reference: its outcome is reported as `objects`.
931
        let objects_only = updates.is_empty() && tags.is_empty();
932
        match self.import_bundle(&bundle, policy.is_some()) {
933
            Ok(imported) => {
934
                if objects_only {
935
                    results.push(RefResult {
936
                        name: OBJECTS_RESULT.into(),
937
                        ok: true,
938
                        reason: format!("{} changes stored", imported.len()),
939
                    });
940
                }
941
                report.imported = imported;
942
            }
943
            Err(e) => {
944
                if objects_only {
945
                    results.push(RefResult {
946
                        name: OBJECTS_RESULT.into(),
947
                        ok: false,
948
                        reason: e.to_string(),
949
                    });
950
                }
951
                for u in updates {
952
                    results.push(RefResult {
953
                        name: u.name,
954
                        ok: false,
955
                        reason: e.to_string(),
956
                    });
957
                }
958
                return Ok(report);
959
            }
960
        }
961
        let (op_ref, op) = self.head_op()?;
962
        let mut view = op.view.clone();
963
        let mut names = Vec::new();
964
        for u in updates {
965
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
966
            let (ok, reason) = match outcome {
967
                Ok(()) => (true, String::new()),
968
                Err(e) => (false, e),
969
            };
970
            if ok {
971
                names.push(u.name.clone());
972
                let heads = self
973
                    .store
974
                    .get_state(&u.new_state)
975
                    .map(|s| s.heads)
976
                    .unwrap_or_default();
977
                report.updated.push(RefUpdated {
978
                    name: u.name.clone(),
979
                    old_state: u.old_state,
980
                    new_state: u.new_state,
981
                    heads,
982
                });
983
            }
984
            results.push(RefResult {
985
                name: u.name,
986
                ok,
987
                reason,
988
            });
989
        }
990
        for t in &tags {
991
            let name = format!("tags/{}", t.name);
992
            if t.is_withdrawal() {
993
                match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut TagCheck::Received)
994
                {
995
                    Ok(removed) => {
996
                        // A withdrawal is an update to nothing, as a
997
                        // bookmark's deletion is.
998
                        if removed {
999
                            report.updated.push(RefUpdated {
1000
                                name: name.clone(),
1001
                                old_state: t.state,
1002
                                new_state: ObjectRef::ZERO,
1003
                                heads: vec![],
1004
                            });
1005
                        }
1006
                        names.push(name.clone());
1007
                        results.push(RefResult {
1008
                            name,
1009
                            ok: true,
1010
                            reason: if removed {
1011
                                "withdrawn"
1012
                            } else {
1013
                                "already withdrawn"
1014
                            }
1015
                            .into(),
1016
                        });
1017
                    }
1018
                    Err(e) => results.push(RefResult {
1019
                        name,
1020
                        ok: false,
1021
                        reason: e.reason,
1022
                    }),
1023
                }
1024
                continue;
1025
            }
1026
            let new = !view.tags.contains_key(&t.name);
1027
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut TagCheck::Received) {
1028
                Ok(()) => {
1029
                    // A tag new here is an update too, so a hub can start
1030
                    // its pipeline's tag jobs (oxygenflow#24); one it
1031
                    // already had, sent again, is not.
1032
                    if new {
1033
                        report.updated.push(RefUpdated {
1034
                            name: name.clone(),
1035
                            old_state: ObjectRef::ZERO,
1036
                            new_state: t.state,
1037
                            heads: t.heads.clone(),
1038
                        });
1039
                    }
1040
                    names.push(name.clone());
1041
                    results.push(RefResult {
1042
                        name,
1043
                        ok: true,
1044
                        reason: String::new(),
1045
                    });
1046
                }
1047
                Err(e) => results.push(RefResult {
1048
                    name,
1049
                    ok: false,
1050
                    reason: e.reason,
1051
                }),
1052
            }
1053
        }
1054
        if !names.is_empty() {
1055
            self.record_op(
1056
                &[op_ref],
1057
                &format!("push received: {}", names.join(" ")),
1058
                view,
1059
            )?;
1060
        }
1061
        Ok(report)
1062
    }
1063
1064
    /// Check an update's attestation against the latest one for its
1065
    /// reference and store it as the new latest. Failures say what was
1066
    /// being done, for which reference, so a refused push can be diagnosed
1067
    /// from its reason alone.
1068
    fn record_update_attest(
1069
        &self,
1070
        u: &RefUpdate,
1071
        sa: &SignedAttest,
1072
    ) -> std::result::Result<(), String> {
1073
        let name = &u.name;
1074
        let last = self
1075
            .latest_ref_attest(name)
1076
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
1077
            .and_then(|(_, a)| match a.attest.body {
1078
                AttestBody::Ref { serial, .. } => Some(serial),
1079
                _ => None,
1080
            });
1081
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
1082
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
1083
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
1084
        for sig in &sa.sigs {
1085
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
1086
        }
1087
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
1088
        // Signed by a short-lived key: a host records when it accepted it.
1089
        let certified = sa
1090
            .sigs
1091
            .first()
1092
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
1093
        if certified {
1094
            self.record_acceptance(&r).map_err(|e| store(&e))?;
1095
        }
1096
        Ok(())
1097
    }
1098
1099
    /// Record that this host accepted attestation `r` now, signed with its
1100
    /// acceptor key (spec §14.7); nothing without one.
1101
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
1102
        let Some(acceptor) = &self.acceptor else {
1103
            return Ok(());
1104
        };
1105
        let (id, sk) = (&acceptor.0, &acceptor.1);
1106
        let attest = Attest {
1107
            repo: self.id()?,
1108
            hlc: Hlc::now(),
1109
            body: AttestBody::Accepted { attest: *r },
1110
        };
1111
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
1112
        self.store.put_identity(id)?;
1113
        let a = self.store.put_attest(&attest)?;
1114
        self.store.put_signature(&a, &sig)?;
1115
        self.store.index_add_pub("accepted", r, &a)?;
1116
        Ok(())
1117
    }
1118
1119
    /// The host's acceptance of attestation `r`, if one was recorded.
1120
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
1121
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
1122
            return Ok(None);
1123
        };
1124
        Ok(Some(SignedAttest {
1125
            attest: self.store.get_attest(&a)?,
1126
            sigs: self.store.signatures(&a)?,
1127
        }))
1128
    }
1129
1130
    /// When a certified signer's attestation `sa` is checked on a fetch: the
1131
    /// host's acceptance time, if `accepted` is signed by the issuer of the
1132
    /// signer's certificate and accepts `sa`; else the attestation's own
1133
    /// time, which the signer chose.
1134
    pub(crate) fn certified_time(
1135
        &self,
1136
        signer: &KeyId,
1137
        sa: &SignedAttest,
1138
        accepted: Option<&SignedAttest>,
1139
    ) -> u64 {
1140
        self.issuer_acceptance(signer, sa, accepted)
1141
            .unwrap_or(sa.attest.hlc.wall_ms)
1142
    }
1143
1144
    /// The time of `accepted` when it accepts exactly `sa` and is signed by
1145
    /// the issuer of `signer`'s kept certificate (spec §14.7); else none.
1146
    pub(crate) fn issuer_acceptance(
1147
        &self,
1148
        signer: &KeyId,
1149
        sa: &SignedAttest,
1150
        accepted: Option<&SignedAttest>,
1151
    ) -> Option<u64> {
1152
        let acc = accepted?;
1153
        let c = self.store.certificate_of(signer).ok().flatten()?;
1154
        let cert = self.store.get_certificate(&c).ok()?;
1155
        let AttestBody::Accepted { attest } = &acc.attest.body else {
1156
            return None;
1157
        };
1158
        let sig = acc.sigs.iter().find(|s| s.key == cert.cert.issuer)?;
1159
        let issuer = self.store.get_identity(&cert.cert.issuer).ok()?;
1160
        (*attest == sa.attest.hash()
1161
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok())
1162
        .then_some(acc.attest.hlc.wall_ms)
1163
    }
1164
1165
    /// Keep an acceptance this repository was given for attestation `r`
1166
    /// (one [`Repo::issuer_acceptance`] took), so it is served again with
1167
    /// what it accepts.
1168
    pub(crate) fn keep_acceptance(&self, r: &ObjectRef, acc: &SignedAttest) -> Result<()> {
1169
        let a = self.store.put_attest(&acc.attest)?;
1170
        for sig in &acc.sigs {
1171
            self.store.put_signature(&a, sig)?;
1172
        }
1173
        self.store.index_add_pub("accepted", r, &a)?;
1174
        Ok(())
1175
    }
1176
1177
    /// A fetched bookmark's attestation by a signer the policy does not
1178
    /// list itself: a delegate or a short-lived key, whose authority
1179
    /// depends on when it signed (spec §14.5, §14.8). Checked at the
1180
    /// attestation's integrated time when the host's log gives one; else
1181
    /// as before, at the host's acceptance for a certified signer, when it
1182
    /// countersigned one, or at the attestation's own time, and said so
1183
    /// when the host keeps a log. Failing at the integrated time but not
1184
    /// as before is a note while logs are new; a large gap between the
1185
    /// claimed and the integrated time is a note.
1186
    #[allow(clippy::too_many_arguments)]
1187
    pub(crate) fn authorize_in_time(
1188
        &self,
1189
        p: &crate::policy::Policy,
1190
        remote_name: &str,
1191
        r: &crate::protocol::RemoteRef,
1192
        sa: &SignedAttest,
1193
        signer: &KeyId,
1194
        log: &super::transparency::LogCheck,
1195
        notes: &mut Vec<String>,
1196
    ) -> Result<()> {
1197
        use super::transparency::{gap_note, judge, Timed};
1198
        let own = sa.attest.hlc.wall_ms;
1199
        let at = self.certified_time(signer, sa, r.accepted.as_ref());
1200
        let time = log.time_of(&r.name);
1201
        let check = |t_delegate: u64, t_cert: u64| {
1202
            self.delegate_authorized(p, signer, &r.name, t_delegate)
1203
                || self.certified_authorized(p, signer, &r.name, Scope::REFS, t_cert)
1204
        };
1205
        let before = if at != own {
1206
            "the host's acceptance"
1207
        } else {
1208
            "the time it claims"
1209
        };
1210
        let what = format!("{remote_name}/{}", r.name);
1211
        match judge(time.as_ref().ok().map(|i| i.ms()), |t| check(t, t), || check(own, at)) {
1212
            Timed::Refused => {
1213
                return fail(format!(
1214
                    "{what}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1215
                    signer.short(12)
1216
                ))
1217
            }
1218
            Timed::Integrated => {}
1219
            Timed::Disagrees => notes.push(format!(
1220
                "{what}: {}'s authority had lapsed when witness {} first saw its attestation, though not at {before}; accepted while transparency logs are new",
1221
                signer.short(12),
1222
                time.as_ref().map(|i| i.witness.as_str()).unwrap_or("?")
1223
            )),
1224
            Timed::Fallback if log.kept => notes.push(format!(
1225
                "{what}: {} checked at {before}, not at a witnessed time: {}",
1226
                signer.short(12),
1227
                time.as_ref().err().map(String::as_str).unwrap_or("none")
1228
            )),
1229
            Timed::Fallback => {}
1230
        }
1231
        if let Some(n) = time.ok().and_then(|i| gap_note(own, i)) {
1232
            notes.push(format!("{what}'s attestation {n}"));
1233
        }
1234
        Ok(())
1235
    }
1236
1237
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1238
    /// at `old_state`, is never the bookmark a non-bare repository has
1239
    /// checked out (a bare one's default is its host's to protect, see
1240
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1241
    /// an attestation by a key that may update it.
1242
    /// The deletion's attestation stays the bookmark's latest, so an older
1243
    /// one cannot be replayed to bring it back.
1244
    fn apply_deletion(
1245
        &self,
1246
        view: &mut View,
1247
        u: &RefUpdate,
1248
        policy: Option<&crate::policy::Policy>,
1249
    ) -> std::result::Result<(), String> {
1250
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
1251
            return Err(format!("no bookmark {:?} to delete", u.name));
1252
        };
1253
        if current != u.old_state {
1254
            return Err("stale: the remote bookmark has moved; pull first".into());
1255
        }
1256
        if !self.is_bare() && u.name == self.config.bookmark {
1257
            return Err(format!(
1258
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
1259
                u.name
1260
            ));
1261
        }
1262
        if let Some(p) = policy {
1263
            let Some(sa) = &u.attestation else {
1264
                return Err(format!(
1265
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
1266
                    u.name
1267
                ));
1268
            };
1269
            let signer = sa
1270
                .sigs
1271
                .first()
1272
                .map(|s| s.key)
1273
                .ok_or("attestation carries no signature")?;
1274
            // Received now: the receiver's own clock is the trusted time.
1275
            let now = Hlc::now().wall_ms;
1276
            if !p.authorizes(&signer, &u.name)
1277
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
1278
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1279
            {
1280
                return Err(format!(
1281
                    "key {} may not delete {:?} under this repository's policy",
1282
                    signer.short(12),
1283
                    u.name
1284
                ));
1285
            }
1286
        }
1287
        if let Some(sa) = &u.attestation {
1288
            self.record_update_attest(u, sa)?;
1289
        }
1290
        view.bookmarks.remove(&u.name);
1291
        Ok(())
1292
    }
1293
1294
    fn apply_update(
1295
        &self,
1296
        view: &mut View,
1297
        u: &RefUpdate,
1298
        policy: Option<&crate::policy::Policy>,
1299
    ) -> std::result::Result<(), String> {
1300
        if u.name == "policy" {
1301
            return Err(
1302
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
1303
            );
1304
        }
1305
        let empty = self
1306
            .store
1307
            .put_state(&StateObject::new(vec![]))
1308
            .map_err(|e| e.to_string())?;
1309
        if u.new_state.is_zero() {
1310
            return self.apply_deletion(view, u, policy);
1311
        }
1312
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1313
        if current != u.old_state {
1314
            return Err("stale: the remote bookmark has moved; pull first".into());
1315
        }
1316
        let new_state = self
1317
            .store
1318
            .get_state(&u.new_state)
1319
            .map_err(|_| "new state object is missing".to_string())?;
1320
        for h in &new_state.heads {
1321
            if !self.store.has(h) {
1322
                return Err(format!("head {} is missing", h.short(12)));
1323
            }
1324
        }
1325
        if !u.force {
1326
            let old_heads = self
1327
                .store
1328
                .get_state(&current)
1329
                .map_err(|e| e.to_string())?
1330
                .heads;
1331
            let closure = self
1332
                .closure_in_store(&new_state.heads)
1333
                .map_err(|e| e.to_string())?;
1334
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
1335
                return Err(format!(
1336
                    "not a fast-forward: current head {} would be dropped (use --force)",
1337
                    h.short(12)
1338
                ));
1339
            }
1340
        }
1341
        if let Some(p) = policy {
1342
            let Some(sa) = &u.attestation else {
1343
                return Err(format!(
1344
                    "{:?} requires a signed reference attestation under this repository's policy",
1345
                    u.name
1346
                ));
1347
            };
1348
            let signer = sa
1349
                .sigs
1350
                .first()
1351
                .map(|s| s.key)
1352
                .ok_or("attestation carries no signature")?;
1353
            // Received now: the receiver's own clock is the trusted time.
1354
            let now = Hlc::now().wall_ms;
1355
            if !p.authorizes(&signer, &u.name)
1356
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
1357
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1358
            {
1359
                return Err(format!(
1360
                    "key {} may not update {:?} under this repository's policy",
1361
                    signer.short(12),
1362
                    u.name
1363
                ));
1364
            }
1365
            let old_heads = self
1366
                .store
1367
                .get_state(&current)
1368
                .map_err(|e| e.to_string())?
1369
                .heads;
1370
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1371
        }
1372
        if let Some(sa) = &u.attestation {
1373
            self.record_update_attest(u, sa)?;
1374
        }
1375
        view.bookmarks.insert(u.name.clone(), u.new_state);
1376
        Ok(())
1377
    }
1378
1379
    // ------------------------------------------------------------ client side
1380
1381
    fn remote_url(&self, name: &str) -> Result<String> {
1382
        self.config.remotes.get(name).cloned().ok_or_else(|| {
1383
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
1384
            RepoError::Msg(match names.as_slice() {
1385
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
1386
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1387
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
1388
                    names.join(", "),
1389
                    names[0],
1390
                    names[0]
1391
                ),
1392
                _ => format!(
1393
                    "no remote named {name:?}; this repository has {}",
1394
                    names.join(", ")
1395
                ),
1396
            })
1397
        })
1398
    }
1399
1400
    /// Refuse a remote that is another repository. An **unbound** remote
1401
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1402
    /// for pushes, which bind it to this repository's id (spec §16.1).
1403
    fn check_remote_id(
1404
        &self,
1405
        remote: &dyn crate::protocol::Remote,
1406
        remote_name: &str,
1407
        allow_unbound: bool,
1408
    ) -> Result<()> {
1409
        let theirs = remote.repo_id()?;
1410
        if theirs == self.id()? {
1411
            return Ok(());
1412
        }
1413
        if theirs == crate::protocol::UNBOUND_ID {
1414
            if allow_unbound {
1415
                return Ok(());
1416
            }
1417
            return fail(format!(
1418
                "remote {remote_name:?} is empty and unbound: push to it first"
1419
            ));
1420
        }
1421
        fail(format!(
1422
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1423
        ))
1424
    }
1425
1426
    /// Credentials and trust for a remote: `remote.<name>.token` and
1427
    /// `remote.<name>.ca`, else the defaults for its URL
1428
    /// ([`Repo::fill_credentials`]).
1429
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
1430
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
1431
        let mut options = RemoteOptions {
1432
            repo_id: self.id().ok(),
1433
            token: self.config.remote_tokens.get(name).cloned(),
1434
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
1435
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
1436
            ..RemoteOptions::default()
1437
        };
1438
        self.fill_credentials(&url, &mut options);
1439
        options
1440
    }
1441
1442
    /// The user's credential store (`credentials.toml` beside the user
1443
    /// configuration file).
1444
    pub fn credentials(&self) -> crate::credentials::Credentials {
1445
        crate::credentials::Credentials::at(
1446
            self.user_config
1447
                .parent()
1448
                .map(Path::to_path_buf)
1449
                .unwrap_or_else(default_home),
1450
        )
1451
    }
1452
1453
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1454
    /// then the user's credential store for its hub, then a remote on the
1455
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1456
    /// When the token is not this remote's own or the environment's, the
1457
    /// other tokens enclosing checkouts hold for the hub are kept to try
1458
    /// if it is refused: a stale stored login must not hide a parent's
1459
    /// good token (oxygen#112).
1460
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
1461
        if options.token.is_some() && options.ca.is_some() {
1462
            return;
1463
        }
1464
        let explicit =
1465
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
1466
        let stored = self.credentials().options_for(url);
1467
        options.token = options.token.take().or(stored.token);
1468
        options.ca = options.ca.take().or(stored.ca);
1469
        let enclosing = self.enclosing_credentials(url);
1470
        if options.token.is_none() {
1471
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
1472
        }
1473
        if options.ca.is_none() {
1474
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
1475
        }
1476
        if !explicit {
1477
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
1478
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
1479
                    options.fallback_tokens.push(t);
1480
                }
1481
            }
1482
        }
1483
    }
1484
1485
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1486
    /// checkouts, nearest first.
1487
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
1488
        let mut out = Vec::new();
1489
        let Some(hub) = crate::credentials::hub_of(url) else {
1490
            return out;
1491
        };
1492
        let mut at = self.root.parent();
1493
        while let Some(dir) = at {
1494
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
1495
                break;
1496
            };
1497
            for (key, remote_url) in &cfg {
1498
                let Some(name) = key
1499
                    .strip_prefix("remote.")
1500
                    .and_then(|k| k.strip_suffix(".url"))
1501
                else {
1502
                    continue;
1503
                };
1504
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
1505
                    continue;
1506
                }
1507
                out.push((
1508
                    cfg.get(&format!("remote.{name}.token")).cloned(),
1509
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
1510
                ));
1511
            }
1512
            at = dir.parent();
1513
        }
1514
        out
1515
    }
1516
1517
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1518
    /// no changes and no reference updates, which the receiver stores.
1519
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
1520
        let remote = self.open_named_remote(remote_name)?;
1521
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1522
        let mut bundle = Bundle::default();
1523
        for r in seals {
1524
            let attest = self.store.get_attest(r)?;
1525
            let sigs = self.store.signatures(r)?;
1526
            bundle
1527
                .attests
1528
                .push(crate::protocol::SignedAttest { attest, sigs });
1529
        }
1530
        let results = remote.push(bundle, vec![], None, vec![])?;
1531
        if let Some(r) = results.iter().find(|r| !r.ok) {
1532
            return fail(format!("{}: {}", r.name, r.reason));
1533
        }
1534
        Ok(())
1535
    }
1536
1537
    /// The remote whose URL starts with `base` (a hub), if configured.
1538
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
1539
        let base = base.trim_end_matches('/');
1540
        self.config
1541
            .remotes
1542
            .iter()
1543
            .find(|(_, url)| url.trim_end_matches('/') == base)
1544
            .map(|(name, _)| name.clone())
1545
    }
1546
1547
    /// Open a remote by name or, failing that, by URL with the default
1548
    /// credentials (see [`Repo::credentials_for`]).
1549
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
1550
        if let Some(name) = self.remote_for_url(url) {
1551
            return Ok((name.clone(), self.open_named_remote(&name)?));
1552
        }
1553
        let options = RemoteOptions {
1554
            repo_id: self.id().ok(),
1555
            ..self.credentials_for(url)
1556
        };
1557
        Ok((url.to_string(), open_remote(url, &options)?))
1558
    }
1559
1560
    /// Credentials for a URL: those of the configured remote with that
1561
    /// URL, else the environment's.
1562
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
1563
        match self.remote_for_url(url) {
1564
            Some(name) => self.remote_options(&name),
1565
            None => RemoteOptions {
1566
                repo_id: self.id().ok(),
1567
                ..self.credentials_for(url)
1568
            },
1569
        }
1570
    }
1571
1572
    pub(crate) fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1573
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1574
    }
1575
1576
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1577
        self.oxy
1578
            .join("remotes")
1579
            .join(remote)
1580
            .join(format!("{bookmark}.serial"))
1581
    }
1582
1583
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
1584
        fs::read_to_string(self.serial_path(remote, bookmark))
1585
            .ok()
1586
            .and_then(|s| s.trim().parse().ok())
1587
    }
1588
1589
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1590
        let p = self.serial_path(remote, bookmark);
1591
        fs::create_dir_all(p.parent().unwrap())?;
1592
        write_atomic(&p, serial.to_string().as_bytes())
1593
    }
1594
1595
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1596
        self.oxy.join("remotes").join(remote).join("policy.serial")
1597
    }
1598
1599
    /// The highest policy serial `remote` has ever presented.
1600
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1601
        fs::read_to_string(self.policy_serial_path(remote))
1602
            .ok()
1603
            .and_then(|s| s.trim().parse().ok())
1604
    }
1605
1606
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
1607
        let p = self.policy_serial_path(remote);
1608
        fs::create_dir_all(p.parent().unwrap())?;
1609
        write_atomic(&p, serial.to_string().as_bytes())
1610
    }
1611
1612
    fn lazy_dir(&self) -> PathBuf {
1613
        self.oxy.join("lazy")
1614
    }
1615
1616
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
1617
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
1618
        fs::create_dir_all(self.lazy_dir())?;
1619
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
1620
    }
1621
1622
    /// Which remote promised an absent blob, if any.
1623
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
1624
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
1625
            .ok()
1626
            .map(|s| s.trim().to_string())
1627
    }
1628
1629
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
1630
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
1631
        let Some(remote_name) = self.lazy_remote(blob) else {
1632
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1633
        };
1634
        let remote = self.open_named_remote(&remote_name)?;
1635
        let objects = remote.objects(&[*blob])?;
1636
        for (ty, body) in objects {
1637
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
1638
                self.store.put(ty, &body)?;
1639
            }
1640
        }
1641
        if !self.store.has(blob) {
1642
            return fail(format!(
1643
                "{remote_name} did not send blob {}",
1644
                blob.short(12)
1645
            ));
1646
        }
1647
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
1648
        Ok(())
1649
    }
1650
1651
    /// After importing from `remote`, record every blob the changes reference
1652
    /// that the store lacks as lazily available from that remote.
1653
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
1654
        let mut n = 0;
1655
        for h in changes {
1656
            let c = self.store.get_change(h)?;
1657
            for e in &c.edits {
1658
                if let Edit::Replace { old, new, .. } = e {
1659
                    for b in [old, new].into_iter().flatten() {
1660
                        if !self.store.has(b) {
1661
                            self.register_lazy(b, remote)?;
1662
                            n += 1;
1663
                        }
1664
                    }
1665
                }
1666
            }
1667
        }
1668
        Ok(n)
1669
    }
1670
1671
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1672
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1673
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1674
        for st in view
1675
            .bookmarks
1676
            .values()
1677
            .chain(view.remotes.values().flat_map(|b| b.values()))
1678
        {
1679
            if let Ok(s) = self.store.get_state(st) {
1680
                have.extend(s.heads);
1681
            }
1682
        }
1683
        have.extend(view.workspaces.values().copied());
1684
        Ok(have.into_iter().collect())
1685
    }
1686
1687
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1688
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1689
        let remote = self.open_named_remote(remote_name)?;
1690
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1691
        let resp = remote.refs()?;
1692
        // The host's transparency log (spec §14.8): a fork fails here.
1693
        let log = self.check_log(
1694
            &self.remote_url(remote_name)?,
1695
            self.config.remote_cas.get(remote_name).map(Path::new),
1696
            &resp,
1697
        )?;
1698
        let mut log_notes = log.notes.clone();
1699
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1700
        // and signed by roots we trust, or on first contact. A remote that
1701
        // once presented a policy may never present none or an older one:
1702
        // that is a downgrade. A remote that never presented one is
1703
        // unverified, and this fetch is checked only as far as possible.
1704
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1705
        let seen = self.remote_policy_serial(remote_name);
1706
        let mut unverified = false;
1707
        match &resp.policy {
1708
            Some(sp) => {
1709
                if seen.is_some_and(|s| sp.policy.serial < s) {
1710
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
1711
                }
1712
                match &local_policy {
1713
                    Some(l) if sp.policy.serial < l.serial => {}
1714
                    Some(l) if sp.policy.serial == l.serial => {
1715
                        if sp.policy.hash() != l.hash() {
1716
                            return fail(format!(
1717
                                "{remote_name} presents a different policy with the same serial {}",
1718
                                l.serial
1719
                            ));
1720
                        }
1721
                    }
1722
                    _ => {
1723
                        self.adopt_policy_chain(
1724
                            &resp.history,
1725
                            sp,
1726
                            &format!("oxy fetch {remote_name}"),
1727
                        )
1728
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1729
                    }
1730
                }
1731
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1732
            }
1733
            None => {
1734
                if seen.is_some() {
1735
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1736
                }
1737
                unverified = true;
1738
            }
1739
        }
1740
        let policy = if unverified {
1741
            None
1742
        } else {
1743
            self.current_policy()?.map(|(_, sp)| sp.policy)
1744
        };
1745
        let (op_ref, op) = self.head_op()?;
1746
        let mut view = op.view.clone();
1747
        let have = self.known_heads(&view)?;
1748
        let mut report = Vec::new();
1749
        let mut skipped = Vec::new();
1750
        let max_blob = self.config.max_blob;
1751
        for r in resp.refs {
1752
            let needed = {
1753
                let _t = crate::timing::phase("fetch: negotiate");
1754
                remote.negotiate(&have, &r.heads)?
1755
            };
1756
            let bundle = {
1757
                let _t = crate::timing::phase("fetch: bundle");
1758
                remote.fetch(&needed, max_blob)?
1759
            };
1760
            // Changes are not individually re-verified here: the bookmark's
1761
            // attestation (checked below) binds its whole state, and the
1762
            // receiver of the push verified the added changes at that time.
1763
            // A shallow repository takes changes whose dependencies it never
1764
            // held (below what it cloned), as its clone did (#137).
1765
            let shallow = self.is_shallow();
1766
            let imported = {
1767
                let _t = crate::timing::phase("fetch: import");
1768
                if shallow {
1769
                    self.import_bundle_shallow(&bundle, false)?
1770
                } else {
1771
                    self.import_bundle(&bundle, false)?
1772
                }
1773
            };
1774
            if shallow {
1775
                self.refresh_boundary(&imported)?;
1776
            }
1777
            if max_blob.is_some() {
1778
                self.register_missing_blobs(&imported, remote_name)?;
1779
            }
1780
            let boundary = if shallow {
1781
                self.boundary()
1782
            } else {
1783
                BTreeSet::new()
1784
            };
1785
            for h in &r.heads {
1786
                if !self.store.has(h) && !boundary.contains(h) {
1787
                    return fail(format!("remote did not send head {}", h.short(12)));
1788
                }
1789
            }
1790
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1791
            if state != r.state {
1792
                return fail(format!(
1793
                    "remote state {} does not match its heads",
1794
                    r.state.short(12)
1795
                ));
1796
            }
1797
            if let Some(p) = &policy {
1798
                let Some(sa) = &r.attestation else {
1799
                    return fail(format!(
1800
                        "{remote_name}/{} has no attestation, which its policy requires",
1801
                        r.name
1802
                    ));
1803
                };
1804
                let signer = sa
1805
                    .sigs
1806
                    .first()
1807
                    .map(|s| s.key)
1808
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1809
                if !p.authorizes(&signer, &r.name) {
1810
                    self.authorize_in_time(p, remote_name, &r, sa, &signer, &log, &mut log_notes)?;
1811
                }
1812
            }
1813
            if let Some(sa) = &r.attestation {
1814
                let AttestBody::Ref {
1815
                    old_state,
1816
                    new_state,
1817
                    ..
1818
                } = &sa.attest.body
1819
                else {
1820
                    return fail("remote sent a non-ref attestation for a bookmark");
1821
                };
1822
                let (old_state, new_state) = (*old_state, *new_state);
1823
                let serial = self
1824
                    .check_ref_attest_body(
1825
                        sa,
1826
                        &r.name,
1827
                        &old_state,
1828
                        &new_state,
1829
                        self.last_seen_serial(remote_name, &r.name),
1830
                        true,
1831
                    )
1832
                    .map_err(|e| {
1833
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
1834
                    })?;
1835
                if new_state != r.state {
1836
                    return fail(format!(
1837
                        "attestation for {}/{} does not cover its current state",
1838
                        remote_name, r.name
1839
                    ));
1840
                }
1841
                // A signature this client cannot verify (its signer unknown
1842
                // here, as from a host that did not send the identity, or
1843
                // bad) fails that bookmark alone: it stays as it was and
1844
                // the rest are fetched (oxygenhub#266). The current
1845
                // bookmark, which a pull would take, still fails the fetch.
1846
                // A policy's requirements were checked above and still fail.
1847
                if let Err(e) = self.verify_attest_signature(sa) {
1848
                    let why = format!("attestation for {remote_name}/{}: {e}", r.name);
1849
                    if r.name == self.config.bookmark {
1850
                        return fail(why);
1851
                    }
1852
                    skipped.push((r.name, why));
1853
                    continue;
1854
                }
1855
                let ar = self.store.put_attest(&sa.attest)?;
1856
                for sig in &sa.sigs {
1857
                    self.store.put_signature(&ar, sig)?;
1858
                }
1859
                self.record_serial(remote_name, &r.name, serial)?;
1860
            }
1861
            view.remotes
1862
                .entry(remote_name.to_string())
1863
                .or_default()
1864
                .insert(r.name.clone(), state);
1865
            report.push((r.name, r.heads, imported.len()));
1866
        }
1867
        let mut new_tags = 0;
1868
        for t in &resp.tags {
1869
            if view.tags.contains_key(&t.name) {
1870
                continue;
1871
            }
1872
            // Withdrawn here: the name is not used again.
1873
            if self.tag_withdrawal(&t.name)?.is_some() {
1874
                continue;
1875
            }
1876
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
1877
            let missing: Vec<ChangeHash> = t
1878
                .heads
1879
                .iter()
1880
                .filter(|h| !self.store.has(h))
1881
                .copied()
1882
                .collect();
1883
            if !missing.is_empty() {
1884
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1885
                let bundle = remote.fetch(&needed, max_blob)?;
1886
                self.import_bundle(&bundle, false)?;
1887
            }
1888
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1889
            let mut check = TagCheck::Fetched {
1890
                remote: remote_name,
1891
                log: &log,
1892
                notes: &mut log_notes,
1893
            };
1894
            match self.adopt_tag(&mut view, t, policy.as_ref(), &mut check) {
1895
                Ok(()) => new_tags += 1,
1896
                // Nothing says when a short-lived key signed it: the tag is
1897
                // left out, said so, and the rest is fetched (oxygen#129).
1898
                Err(e) if e.untimed => {
1899
                    skipped.push((format!("tags/{}", t.name), e.reason));
1900
                }
1901
                Err(e) => return fail(format!("{remote_name} {}: {}", t.name, e.reason)),
1902
            }
1903
        }
1904
        // The remote withdrew a tag this repository has: so does this one,
1905
        // once the withdrawal is checked as a push's would be; one that is
1906
        // not is left as it is, said so (oxygenhub#301).
1907
        let mut withdrawn_tags = Vec::new();
1908
        for t in &resp.withdrawn {
1909
            if !view.tags.contains_key(&t.name) {
1910
                continue;
1911
            }
1912
            let mut check = TagCheck::Fetched {
1913
                remote: remote_name,
1914
                log: &log,
1915
                notes: &mut log_notes,
1916
            };
1917
            match self.adopt_withdrawal(&mut view, t, policy.as_ref(), &mut check) {
1918
                Ok(true) => withdrawn_tags.push(t.name.clone()),
1919
                Ok(false) => {}
1920
                Err(e) => skipped.push((
1921
                    format!("tags/{}", t.name),
1922
                    format!("withdrawn on {remote_name}, kept here: {}", e.reason),
1923
                )),
1924
            }
1925
        }
1926
        if view != op.view {
1927
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1928
        }
1929
        let _ = self.run_hook(
1930
            "post-fetch",
1931
            &format!(
1932
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1933
                json_str(remote_name),
1934
                json_array(report.iter().map(|(n, heads, _)| format!(
1935
                    "{{\"name\":{},\"heads\":{}}}",
1936
                    json_str(n),
1937
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1938
                )))
1939
            ),
1940
        );
1941
        Ok(FetchReport {
1942
            refs: report,
1943
            unverified,
1944
            new_tags,
1945
            withdrawn_tags,
1946
            log_notes,
1947
            skipped,
1948
        })
1949
    }
1950
1951
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1952
    /// the changes within `depth` steps of its heads, and the boundary below.
1953
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1954
        let remote = self.open_named_remote(remote_name)?;
1955
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1956
        let resp = remote.refs()?;
1957
        let bookmark = self.config.bookmark.clone();
1958
        if let Some(sp) = &resp.policy {
1959
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1960
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1961
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1962
        }
1963
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1964
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1965
        };
1966
        if r.heads.is_empty() {
1967
            return Ok(0);
1968
        }
1969
        // Base: the remote's checkpoint of exactly these heads.
1970
        let cp_bundle = {
1971
            let _t = crate::timing::phase("shallow: checkpoint request");
1972
            remote.checkpoint(&r.heads)?
1973
        };
1974
        // In one batch: a big state's checkpoint is tens of thousands of
1975
        // graph blobs and chunks, which stored one by one were each written
1976
        // loose and flushed (a VS Code clone ran at 27 objects a second).
1977
        let objects: Vec<(ObjectType, &[u8])> = cp_bundle
1978
            .objects
1979
            .iter()
1980
            .map(|(ty, body)| (*ty, body.as_slice()))
1981
            .collect();
1982
        let t_store = crate::timing::phase("shallow: store the checkpoint");
1983
        let batch = self.store.begin_batch()?;
1984
        let stored = self.store.put_many(&objects);
1985
        batch.finish()?;
1986
        drop(t_store);
1987
        let cp_ref = objects
1988
            .iter()
1989
            .zip(stored?)
1990
            .find(|((ty, _), _)| *ty == ObjectType::Checkpoint)
1991
            .map(|(_, r)| r);
1992
        let Some(cp_ref) = cp_ref else {
1993
            return fail(format!("{remote_name} sent no checkpoint"));
1994
        };
1995
        self.install_checkpoint(&bookmark, &cp_ref)?;
1996
        let _t_blobs = crate::timing::phase("shallow: the binary files' blobs");
1997
        // The blobs of the state's opaque files come with no change when the
1998
        // window holds none of the changes that set them (#137): fetch them
1999
        // now, or under `filter.max-blob` leave them to be fetched on read.
2000
        let cp = crate::objects::Checkpoint::decode(
2001
            &self.store.get_typed(&cp_ref, ObjectType::Checkpoint)?,
2002
        )?;
2003
        let base = State::from_checkpoint_history(&self.read_blob(&cp.payload)?)?;
2004
        let mut missing: Vec<ObjectRef> = base
2005
            .opaque_nodes()
2006
            .iter()
2007
            .flat_map(|n| base.live_blobs(n))
2008
            .filter(|b| !self.store.has(b))
2009
            .collect();
2010
        missing.sort();
2011
        missing.dedup();
2012
        if self.config.max_blob.is_some() {
2013
            for b in &missing {
2014
                self.register_lazy(b, remote_name)?;
2015
            }
2016
        } else {
2017
            for part in missing.chunks(512) {
2018
                let objects = remote.objects(part)?;
2019
                let objects: Vec<(ObjectType, &[u8])> = objects
2020
                    .iter()
2021
                    .filter(|(ty, _)| matches!(ty, ObjectType::Blob | ObjectType::Chunk))
2022
                    .map(|(ty, body)| (*ty, body.as_slice()))
2023
                    .collect();
2024
                let batch = self.store.begin_batch()?;
2025
                let stored = self.store.put_many(&objects);
2026
                batch.finish()?;
2027
                stored?;
2028
            }
2029
            if let Some(b) = missing.iter().find(|b| !self.store.has(b)) {
2030
                return fail(format!("{remote_name} did not send blob {}", b.short(12)));
2031
            }
2032
        }
2033
        // History window. Depth 0 takes none (#137): the checkpoint holds
2034
        // every change's metadata, and its heads become the boundary, so a
2035
        // state of many heads (33,835 in the VS Code import) costs nothing
2036
        // to fetch.
2037
        let imported = if depth == 0 {
2038
            let mut boundary = self.boundary();
2039
            boundary.extend(r.heads.iter().filter(|h| !self.store.has(h)).copied());
2040
            self.write_boundary(&boundary)?;
2041
            Vec::new()
2042
        } else {
2043
            let wanted = remote.shallow(&r.heads, depth)?;
2044
            let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2045
            self.import_bundle_shallow(&bundle, false)?
2046
        };
2047
        if self.config.max_blob.is_some() {
2048
            self.register_missing_blobs(&imported, remote_name)?;
2049
        }
2050
        self.refresh_boundary(&imported)?;
2051
        if let Some(sa) = &r.attestation {
2052
            let ar = self.store.put_attest(&sa.attest)?;
2053
            for sig in &sa.sigs {
2054
                self.store.put_signature(&ar, sig)?;
2055
            }
2056
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
2057
                self.record_serial(remote_name, &r.name, serial)?;
2058
            }
2059
        }
2060
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
2061
        let (op_ref, op) = self.head_op()?;
2062
        let mut view = op.view.clone();
2063
        view.remotes
2064
            .entry(remote_name.to_string())
2065
            .or_default()
2066
            .insert(r.name.clone(), state);
2067
        self.record_op(
2068
            &[op_ref],
2069
            &format!("oxy fetch {remote_name} --depth {depth}"),
2070
            view,
2071
        )?;
2072
        Ok(imported.len())
2073
    }
2074
2075
    /// Fetch, then take the union of the local bookmark's state with the
2076
    /// remote's: no merge change, conflicts become reified (spec §9.4).
2077
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
2078
        let _wc = self.lock_working_copy()?;
2079
        let skipped = self.fetch(remote_name)?.skipped;
2080
        let (op_ref, op) = self.head_op()?;
2081
        let current = self.config.bookmark.clone();
2082
        let mut local_current = self.heads_of(&op.view, &current)?;
2083
        local_current.sort();
2084
        let mut view = op.view.clone();
2085
        let mut current_heads = local_current.clone();
2086
        let mut changed = false;
2087
        let mut others = Vec::new();
2088
        let tracked = op
2089
            .view
2090
            .remotes
2091
            .get(remote_name)
2092
            .cloned()
2093
            .unwrap_or_default();
2094
        for (name, remote_state) in tracked {
2095
            // Every local bookmark tracks the remote's of the same name;
2096
            // the current one may be new here.
2097
            let local_state = op.view.bookmarks.get(&name).copied();
2098
            if local_state.is_none() && name != current {
2099
                continue;
2100
            }
2101
            if local_state == Some(remote_state) {
2102
                continue;
2103
            }
2104
            let local = self.heads_of(&op.view, &name)?;
2105
            let remote_heads = self.store.get_state(&remote_state)?.heads;
2106
            if remote_heads.iter().all(|h| local.contains(h)) {
2107
                continue;
2108
            }
2109
            let mut all = local.clone();
2110
            all.extend(remote_heads);
2111
            let st = self.load_state_history(&all)?;
2112
            let mut heads = st.maximal(&all);
2113
            heads.sort();
2114
            let mut sorted_local = local;
2115
            sorted_local.sort();
2116
            if heads == sorted_local {
2117
                continue;
2118
            }
2119
            view.bookmarks.insert(
2120
                name.clone(),
2121
                self.store.put_state(&StateObject::new(heads.clone()))?,
2122
            );
2123
            if name == current {
2124
                changed = true;
2125
                current_heads = heads;
2126
            } else {
2127
                others.push(name);
2128
            }
2129
        }
2130
        if changed || !others.is_empty() {
2131
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
2132
        }
2133
        // The working copy follows its bookmark whenever nothing would be
2134
        // lost, also when this pull brought nothing new but it had been
2135
        // left behind (oxygen#89).
2136
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
2137
        Ok(PullReport {
2138
            heads: if changed {
2139
                current_heads
2140
            } else {
2141
                local_current
2142
            },
2143
            changed,
2144
            checked_out,
2145
            others,
2146
            skipped,
2147
        })
2148
    }
2149
2150
    /// How many changes the working copy's bookmark has that its base
2151
    /// lacks, when the base is part of the bookmark's state (it fell behind,
2152
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
2153
    /// the bookmark or holds changes the bookmark lacks. History is read
2154
    /// only when the base and the bookmark's heads differ (oxygen#89).
2155
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
2156
        let (_, wc) = self.working_copy()?;
2157
        let mut base = wc.deps.clone();
2158
        base.sort();
2159
        let mut heads = self.bookmark_heads()?;
2160
        heads.sort();
2161
        if base == heads || heads.is_empty() {
2162
            return Ok(None);
2163
        }
2164
        let state = self.load_state_history(&heads)?;
2165
        if !base.iter().all(|h| state.contains(h)) {
2166
            return Ok(None);
2167
        }
2168
        let had = if base.is_empty() {
2169
            0
2170
        } else {
2171
            self.load_state_history(&base)?.len()
2172
        };
2173
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
2174
    }
2175
2176
    /// Bring the working copy to `heads`, the state of its bookmark
2177
    /// `bookmark`, when nothing would be lost: its base is part of that
2178
    /// state, so the bookmark only adds to it. Clean, it is checked out;
2179
    /// with uncommitted work, the work comes along when the new changes
2180
    /// leave its paths alone (as `git pull` does), else it stays. Before,
2181
    /// it followed only from exactly the bookmark's old heads, so a working
2182
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
2183
    /// or a pull from another workspace) never caught up, and nothing said
2184
    /// so (oxygen#74, #89). Returns whether it moved.
2185
    pub fn follow_bookmark(
2186
        &self,
2187
        heads: &[ChangeHash],
2188
        bookmark: &str,
2189
        command: &str,
2190
    ) -> Result<bool> {
2191
        let snap = self.snapshot(command)?;
2192
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
2193
        let mut base = snap.base.maximal(&snap.wc.deps);
2194
        base.sort();
2195
        let mut target = heads.to_vec();
2196
        target.sort();
2197
        if base == target {
2198
            return Ok(false);
2199
        }
2200
        let state = self.load_state_history(heads)?;
2201
        if !base.iter().all(|h| state.contains(h)) {
2202
            // The working copy holds changes the bookmark lacks: not ours to move.
2203
            return Ok(false);
2204
        }
2205
        if clean {
2206
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
2207
            Ok(true)
2208
        } else {
2209
            Ok(self
2210
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
2211
                .is_ok())
2212
        }
2213
    }
2214
2215
    /// Withdraw tag `tag` on `remote_name` (`oxy push --delete tags/NAME`,
2216
    /// oxygenhub#301): withdrawn here first when it still is a tag here
2217
    /// (`oxy tag delete`), then the withdrawal alone is sent, with its
2218
    /// signer's identity and certificate.
2219
    pub fn push_tag_withdrawal(&self, remote_name: &str, tag: &str) -> Result<Vec<RefResult>> {
2220
        let remote = self.open_named_remote(remote_name)?;
2221
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2222
        let resp = remote.refs()?;
2223
        let name = format!("tags/{tag}");
2224
        if resp.withdrawn.iter().any(|t| t.name == tag) {
2225
            return Ok(vec![RefResult {
2226
                name,
2227
                ok: true,
2228
                reason: "already withdrawn".into(),
2229
            }]);
2230
        }
2231
        let Some(there) = resp.tags.iter().find(|t| t.name == tag) else {
2232
            return fail(format!("{remote_name} has no tag {tag}"));
2233
        };
2234
        if resp.policy.is_some() && self.secret_key()?.is_none() {
2235
            return fail(format!("{remote_name} enforces a trust policy; withdrawing a tag needs an identity (`oxy identity create`)"));
2236
        }
2237
        if self.tag_withdrawal(tag)?.is_none() {
2238
            match self.view()?.tags.get(tag) {
2239
                Some(st) if *st == there.state => {
2240
                    self.tag_delete(tag, "")?;
2241
                }
2242
                Some(_) => {
2243
                    return fail(format!(
2244
                        "tag {tag} names another state here than on {remote_name}"
2245
                    ))
2246
                }
2247
                None => {
2248
                    return fail(format!(
2249
                        "there is no tag {tag} here to withdraw: `oxy fetch {remote_name}` first"
2250
                    ))
2251
                }
2252
            }
2253
        }
2254
        let Some(w) = self
2255
            .withdrawn_refs()?
2256
            .into_iter()
2257
            .find(|w| w.name == tag && w.state == there.state)
2258
        else {
2259
            return fail(format!(
2260
                "tag {tag} was withdrawn here at another state than {remote_name}'s"
2261
            ));
2262
        };
2263
        let mut bundle = Bundle::default();
2264
        let signers: Vec<KeyId> = w
2265
            .attestation
2266
            .iter()
2267
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2268
            .collect();
2269
        for k in &signers {
2270
            if let Ok(id) = self.identity(k) {
2271
                bundle.objects.push((ObjectType::Identity, id.encode()));
2272
            }
2273
        }
2274
        self.attach_certificates_for(&mut bundle, &signers)?;
2275
        remote.push(bundle, vec![], None, vec![w])
2276
    }
2277
2278
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
2279
    /// changes and attesting the reference when a key is available.
2280
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
2281
    /// state, attested when we have an identity. The local bookmark, if
2282
    /// any, is kept; only the remote-tracking entry goes.
2283
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
2284
        if let Some(tag) = bookmark.strip_prefix("tags/") {
2285
            return self.push_tag_withdrawal(remote_name, tag);
2286
        }
2287
        let remote = self.open_named_remote(remote_name)?;
2288
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2289
        let resp = remote.refs()?;
2290
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
2291
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
2292
        };
2293
        if resp.policy.is_some() && self.secret_key()?.is_none() {
2294
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
2295
        }
2296
        let attestation = match self.secret_key()? {
2297
            Some(_) => Some(self.sign_attest(&Attest {
2298
                repo: self.id()?,
2299
                hlc: Hlc::now(),
2300
                body: AttestBody::Ref {
2301
                    name: bookmark.to_string(),
2302
                    old_state: r.state,
2303
                    new_state: ObjectRef::ZERO,
2304
                    serial: r.last_serial.unwrap_or(0) + 1,
2305
                },
2306
            })?),
2307
            None => None,
2308
        };
2309
        let results = remote.push(
2310
            Bundle::default(),
2311
            vec![RefUpdate {
2312
                name: bookmark.to_string(),
2313
                old_state: r.state,
2314
                new_state: ObjectRef::ZERO,
2315
                force: true,
2316
                attestation,
2317
            }],
2318
            None,
2319
            vec![],
2320
        )?;
2321
        if results.iter().any(|x| x.ok && x.name == bookmark) {
2322
            let (op_ref, op) = self.head_op()?;
2323
            let mut view = op.view.clone();
2324
            if let Some(m) = view.remotes.get_mut(remote_name) {
2325
                m.remove(bookmark);
2326
            }
2327
            self.record_op(
2328
                &[op_ref],
2329
                &format!("oxy push {remote_name} --delete {bookmark}"),
2330
                view,
2331
            )?;
2332
        }
2333
        Ok(results)
2334
    }
2335
2336
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
2337
    /// repository's config (its URL, token, CA and store settings), its
2338
    /// tracking bookmarks in the view, and a store remote's mirror under
2339
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
2340
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
2341
        if !self.config.remotes.contains_key(name) {
2342
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
2343
        }
2344
        let prefix = format!("remote.{name}.");
2345
        let keys: Vec<String> = self
2346
            .config
2347
            .repo_layer()
2348
            .keys()
2349
            .filter(|k| k.starts_with(&prefix))
2350
            .cloned()
2351
            .collect();
2352
        for k in keys {
2353
            self.config.set(&k, "")?;
2354
        }
2355
        self.config.remotes.remove(name);
2356
        self.save_config()?;
2357
        let (op_ref, op) = self.head_op()?;
2358
        if op.view.remotes.contains_key(name) {
2359
            let mut view = op.view.clone();
2360
            view.remotes.remove(name);
2361
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
2362
        }
2363
        let mirror = self.oxy.join("remotes").join(name);
2364
        if mirror.is_dir() {
2365
            fs::remove_dir_all(&mirror)?;
2366
        }
2367
        Ok(())
2368
    }
2369
2370
    /// Send `bundle`'s blobs and chunks ahead of it, in parts of about
2371
    /// `push.batch-bytes` of objects alone, when the whole would be larger
2372
    /// (oxygen#133): one change can bring more blobs than one request may
2373
    /// carry, and a proxy in front of a hub refuses a request past its limit
2374
    /// (Cloudflare's is 100 MB). What is left, the changes with their
2375
    /// identities and states, is returned to send as before. A receiver
2376
    /// stores objects as they come, and checks a change's blobs are stored.
2377
    fn send_objects_ahead(
2378
        &self,
2379
        remote: &dyn crate::protocol::Remote,
2380
        remote_name: &str,
2381
        mut bundle: Bundle,
2382
        progress: crate::store::Progress,
2383
    ) -> Result<Bundle> {
2384
        let limit = self.config.push_batch_bytes;
2385
        let changes: u64 = bundle
2386
            .changes
2387
            .iter()
2388
            .map(|(c, _)| c.encode().len() as u64)
2389
            .sum();
2390
        let objects: u64 = bundle.objects.iter().map(|(_, b)| b.len() as u64).sum();
2391
        if changes + objects <= limit {
2392
            return Ok(bundle);
2393
        }
2394
        let (mut kept, mut parts, mut part, mut bytes) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
2395
        for (ty, body) in std::mem::take(&mut bundle.objects) {
2396
            if !matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
2397
                kept.push((ty, body));
2398
                continue;
2399
            }
2400
            if !part.is_empty() && bytes + body.len() as u64 > limit {
2401
                parts.push(std::mem::take(&mut part));
2402
                bytes = 0;
2403
            }
2404
            bytes += body.len() as u64;
2405
            part.push((ty, body));
2406
        }
2407
        if !part.is_empty() {
2408
            parts.push(part);
2409
        }
2410
        let n = parts.len();
2411
        for (i, objects) in parts.into_iter().enumerate() {
2412
            progress(&format!(
2413
                "objects {} of {n}: {} blobs and chunks",
2414
                i + 1,
2415
                objects.len()
2416
            ));
2417
            let results = remote.push(
2418
                Bundle {
2419
                    objects,
2420
                    ..Default::default()
2421
                },
2422
                vec![],
2423
                None,
2424
                vec![],
2425
            )?;
2426
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
2427
                Some(r) if r.ok => {}
2428
                Some(r) => {
2429
                    return fail(format!(
2430
                        "{remote_name} refused objects part {} of {n}: {}",
2431
                        i + 1,
2432
                        r.reason
2433
                    ))
2434
                }
2435
                None => {
2436
                    return fail(format!(
2437
                        "{remote_name} does not take a push in parts, and this one is too large for one: update the server's oxy"
2438
                    ))
2439
                }
2440
            }
2441
        }
2442
        bundle.objects = kept;
2443
        Ok(bundle)
2444
    }
2445
2446
    /// `changes`, in dependency order, cut into batches of about
2447
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
2448
    /// There is always one, perhaps empty.
2449
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
2450
        let blob_len = |r: &ObjectRef| -> u64 {
2451
            self.store
2452
                .get_typed(r, ObjectType::Blob)
2453
                .ok()
2454
                .and_then(|b| Blob::decode(&b).ok())
2455
                .map_or(0, |b| b.length)
2456
        };
2457
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
2458
        for h in changes {
2459
            let raw = self.store.get_typed(h, ObjectType::Change)?;
2460
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
2461
            let mut weight = raw.len() as u64;
2462
            for t in &texts {
2463
                if let crate::objects::TextRef::Blob(r, _, _) = t {
2464
                    weight += blob_len(r);
2465
                }
2466
            }
2467
            for e in &c.edits {
2468
                if let Edit::Replace { new: Some(b), .. } = e {
2469
                    weight += blob_len(b);
2470
                }
2471
            }
2472
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
2473
                out.push(std::mem::take(&mut batch));
2474
                bytes = 0;
2475
            }
2476
            batch.push(*h);
2477
            bytes += weight;
2478
        }
2479
        out.push(batch);
2480
        Ok(out)
2481
    }
2482
2483
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
2484
        let bookmark = self.config.bookmark.clone();
2485
        self.push_bookmark(remote_name, &bookmark, force)
2486
    }
2487
2488
    /// `push` for a named bookmark (`oxy push -b NAME`).
2489
    pub fn push_bookmark(
2490
        &self,
2491
        remote_name: &str,
2492
        bookmark: &str,
2493
        force: bool,
2494
    ) -> Result<Vec<RefResult>> {
2495
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
2496
    }
2497
2498
    /// `push_bookmark`, saying how a long push is going: one line per
2499
    /// batch sent (oxygen#95).
2500
    /// What a push may take the remote to hold already: the heads of the
2501
    /// bookmark pushed, and of every other bookmark it lists that are held
2502
    /// here, so a new bookmark made from main sends only what main lacks
2503
    /// (oxygen#142), not its whole history again.
2504
    pub(crate) fn remote_holds(
2505
        &self,
2506
        refs: &[crate::protocol::RemoteRef],
2507
        bookmark_heads: &[ChangeHash],
2508
    ) -> Vec<ChangeHash> {
2509
        let mut have: Vec<ChangeHash> = bookmark_heads.to_vec();
2510
        for h in refs.iter().flat_map(|r| &r.heads) {
2511
            if !have.contains(h) && self.store.has(h) {
2512
                have.push(*h);
2513
            }
2514
        }
2515
        have
2516
    }
2517
2518
    pub fn push_bookmark_with(
2519
        &self,
2520
        remote_name: &str,
2521
        bookmark: &str,
2522
        force: bool,
2523
        progress: crate::store::Progress,
2524
    ) -> Result<Vec<RefResult>> {
2525
        let (op_ref, op) = self.head_op()?;
2526
        if !op.view.bookmarks.contains_key(bookmark) {
2527
            return fail(format!("no bookmark {bookmark}"));
2528
        }
2529
        let bookmark = bookmark.to_string();
2530
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2531
        // pre-push hook: may veto before the remote is contacted.
2532
        self.run_hook(
2533
            "pre-push",
2534
            &format!(
2535
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2536
                json_str(remote_name),
2537
                json_str(&bookmark),
2538
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2539
            ),
2540
        )?;
2541
        let remote = self.open_named_remote(remote_name)?;
2542
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2543
        let resp = remote.refs()?;
2544
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2545
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2546
        let policy_to_send = match (&local_policy, &resp.policy) {
2547
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
2548
            (Some(l), None) => Some(l.clone()),
2549
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
2550
                return fail(format!(
2551
                    "{remote_name} has a newer policy (serial {}); fetch first",
2552
                    r.policy.serial
2553
                ));
2554
            }
2555
            _ => None,
2556
        };
2557
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2558
        if remote_has_policy && self.secret_key()?.is_none() {
2559
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2560
        }
2561
        let remote_tags: BTreeSet<String> = resp
2562
            .tags
2563
            .iter()
2564
            .chain(&resp.withdrawn)
2565
            .map(|t| t.name.clone())
2566
            .collect();
2567
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2568
            .tag_refs()?
2569
            .into_iter()
2570
            .filter(|t| !remote_tags.contains(&t.name))
2571
            .collect();
2572
        // Tags withdrawn here that the remote still has, at the same state
2573
        // (oxygenhub#301).
2574
        let withdrawals_to_send: Vec<crate::protocol::TagRef> = self
2575
            .withdrawn_refs()?
2576
            .into_iter()
2577
            .filter(|w| {
2578
                resp.tags
2579
                    .iter()
2580
                    .any(|t| t.name == w.name && t.state == w.state)
2581
            })
2582
            .collect();
2583
        let refs = resp.refs;
2584
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2585
        let (remote_state, remote_heads, last_serial) =
2586
            match refs.iter().find(|r| r.name == bookmark) {
2587
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
2588
                None => (empty, vec![], None),
2589
            };
2590
        let new_state = self
2591
            .store
2592
            .put_state(&StateObject::new(local_heads.clone()))?;
2593
        // A push that carries a policy re-attests the bookmark even when its
2594
        // state is unchanged, so the current attestation is always by a key
2595
        // the current policy authorizes (a revoked key's attestation would
2596
        // otherwise be refused by every later fetch).
2597
        if new_state == remote_state
2598
            && policy_to_send.is_none()
2599
            && tags_to_send.is_empty()
2600
            && withdrawals_to_send.is_empty()
2601
        {
2602
            return Ok(vec![RefResult {
2603
                name: bookmark,
2604
                ok: true,
2605
                reason: "already up to date".into(),
2606
            }]);
2607
        }
2608
        // A shallow repository knows the changes on its boundary without
2609
        // holding them: a depth-0 clone's are the heads it cloned (#137).
2610
        let boundary = self.boundary();
2611
        for h in &remote_heads {
2612
            if !self.store.has(h) && !boundary.contains(h) {
2613
                return fail(format!(
2614
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
2615
                    h.short(12)
2616
                ));
2617
            }
2618
        }
2619
        if !force {
2620
            let closure = self.closure_in_store(&local_heads)?;
2621
            if let Some(h) = remote_heads
2622
                .iter()
2623
                .find(|h| !closure.contains(h) && !boundary.contains(h))
2624
            {
2625
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2626
            }
2627
        }
2628
        let to_send = self.negotiate(&self.remote_holds(&refs, &remote_heads), &local_heads)?;
2629
        let key = self.secret_key()?.map(|(k, _)| k);
2630
        if let Some(key) = key {
2631
            // Seal this author's changes that carry no valid authenticator,
2632
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2633
            // are stored, so each batch's bundle carries those it needs.
2634
            let mut unsigned = Vec::new();
2635
            for h in &to_send {
2636
                let c = self.store.get_change_meta(h)?;
2637
                if self.seals_for_author(&c.author, &key)
2638
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
2639
                {
2640
                    unsigned.push(*h);
2641
                }
2642
            }
2643
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
2644
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2645
            }
2646
        }
2647
        // A long history goes in batches, in dependency order, so neither
2648
        // side holds it whole and no request passes the remote's limit:
2649
        // all but the last carry objects alone; the last moves the bookmark
2650
        // (oxygen#95).
2651
        let batches = self.push_batches(&to_send)?;
2652
        let (last, earlier) = batches.split_last().expect("at least one batch");
2653
        for (i, batch) in earlier.iter().enumerate() {
2654
            progress(&format!(
2655
                "part {} of {}: {} changes",
2656
                i + 1,
2657
                batches.len(),
2658
                batch.len()
2659
            ));
2660
            let bundle = self.send_objects_ahead(
2661
                remote.as_ref(),
2662
                remote_name,
2663
                self.bundle_for(batch)?,
2664
                &mut *progress,
2665
            )?;
2666
            let results = remote.push(bundle, vec![], None, vec![])?;
2667
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
2668
                Some(r) if r.ok => {}
2669
                Some(r) => {
2670
                    return fail(format!(
2671
                        "{remote_name} refused part {} of the push: {}",
2672
                        i + 1,
2673
                        r.reason
2674
                    ))
2675
                }
2676
                None => {
2677
                    return fail(format!(
2678
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2679
                    ))
2680
                }
2681
            }
2682
        }
2683
        if batches.len() > 1 {
2684
            progress(&format!(
2685
                "part {} of {}: {} changes",
2686
                batches.len(),
2687
                batches.len(),
2688
                last.len()
2689
            ));
2690
        }
2691
        let mut bundle = self.send_objects_ahead(
2692
            remote.as_ref(),
2693
            remote_name,
2694
            self.bundle_for(last)?,
2695
            &mut *progress,
2696
        )?;
2697
        bundle.objects.push((
2698
            ObjectType::State,
2699
            StateObject::new(local_heads.clone()).encode(),
2700
        ));
2701
        let attestation = match key {
2702
            Some(_) => Some(self.sign_attest(&Attest {
2703
                repo: self.id()?,
2704
                hlc: Hlc::now(),
2705
                body: AttestBody::Ref {
2706
                    name: bookmark.clone(),
2707
                    old_state: remote_state,
2708
                    new_state,
2709
                    serial: next_serial(last_serial),
2710
                },
2711
            })?),
2712
            None => None,
2713
        };
2714
        // Whoever signed the move, and whom a delegate acts for, travel with
2715
        // it: a receiver that has never seen a change by this delegate could
2716
        // not otherwise check its signature (oxygenhub#129).
2717
        if attestation.is_some() {
2718
            for k in [self.signing_key(), self.config.author_key]
2719
                .into_iter()
2720
                .flatten()
2721
            {
2722
                if let Ok(id) = self.identity(&k) {
2723
                    let body = id.encode();
2724
                    if !bundle
2725
                        .objects
2726
                        .iter()
2727
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
2728
                    {
2729
                        bundle.objects.push((ObjectType::Identity, body));
2730
                    }
2731
                }
2732
            }
2733
            // A short-lived signing key's certificate goes with it (§14.7).
2734
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2735
            self.attach_certificates_for(&mut bundle, &signers)?;
2736
        }
2737
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2738
            AttestBody::Ref { serial, .. } => Some(serial),
2739
            _ => None,
2740
        });
2741
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2742
        // Tag states must be present on the remote: bundle their changes too.
2743
        for t in &tags_to_send {
2744
            let extra = self.negotiate(&remote_heads, &t.heads)?;
2745
            let extra: Vec<ChangeHash> =
2746
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
2747
            if !extra.is_empty() {
2748
                let more = self.bundle_for(&extra)?;
2749
                bundle.changes.extend(more.changes);
2750
                bundle.hashes.extend(more.hashes);
2751
                bundle.attests.extend(more.attests);
2752
                bundle.objects.extend(more.objects);
2753
            }
2754
            bundle.objects.push((
2755
                ObjectType::State,
2756
                StateObject::new(t.heads.clone()).encode(),
2757
            ));
2758
        }
2759
        // A tag's signer travels with it, as the bookmark's does: a tag made
2760
        // by `oxy tag create` under a short-lived key was signed by a key the
2761
        // receiver has never seen, so its identity and certificate go too.
2762
        let tag_signers: Vec<KeyId> = tags_to_send
2763
            .iter()
2764
            .chain(&withdrawals_to_send)
2765
            .filter_map(|t| t.attestation.as_ref())
2766
            .flat_map(|a| a.sigs.iter().map(|s| s.key))
2767
            .collect();
2768
        for k in &tag_signers {
2769
            if let Ok(id) = self.identity(k) {
2770
                let body = id.encode();
2771
                if !bundle
2772
                    .objects
2773
                    .iter()
2774
                    .any(|(t, b)| *t == ObjectType::Identity && *b == body)
2775
                {
2776
                    bundle.objects.push((ObjectType::Identity, body));
2777
                }
2778
            }
2779
        }
2780
        if !tag_signers.is_empty() {
2781
            self.attach_certificates_for(&mut bundle, &tag_signers)?;
2782
        }
2783
        if let Some(l) = &policy_to_send {
2784
            let remote_serial = resp_policy_serial;
2785
            bundle.policies = self
2786
                .policy_history()?
2787
                .into_iter()
2788
                .filter(|sp| {
2789
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
2790
                        && sp.policy.serial < l.policy.serial
2791
                })
2792
                .collect();
2793
        }
2794
        let results = remote.push(
2795
            bundle,
2796
            vec![RefUpdate {
2797
                name: bookmark.clone(),
2798
                old_state: remote_state,
2799
                new_state,
2800
                force,
2801
                attestation,
2802
            }],
2803
            policy_to_send,
2804
            tags_to_send
2805
                .into_iter()
2806
                .chain(withdrawals_to_send)
2807
                .collect(),
2808
        )?;
2809
        if let (Some(serial), true) = (
2810
            sent_serial,
2811
            results.iter().any(|r| r.ok && r.name == "policy"),
2812
        ) {
2813
            self.record_policy_serial(remote_name, serial)?;
2814
        }
2815
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2816
            let mut view = op.view.clone();
2817
            view.remotes
2818
                .entry(remote_name.to_string())
2819
                .or_default()
2820
                .insert(bookmark.clone(), new_state);
2821
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2822
            if let Some(s) = serial {
2823
                self.record_serial(remote_name, &bookmark, s)?;
2824
            }
2825
        }
2826
        Ok(results)
2827
    }
2828
2829
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2830
    /// bookmark set to the remote's, working copy checked out.
2831
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2832
        Self::clone_with(url, dest, None, &[])
2833
    }
2834
2835
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2836
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2837
    /// unless a size is given, so out-of-scope binaries are never fetched).
2838
    pub fn clone_with(
2839
        url: &str,
2840
        dest: &Path,
2841
        max_blob: Option<u64>,
2842
        sparse: &[String],
2843
    ) -> Result<Repo> {
2844
        Self::clone_full(url, dest, max_blob, sparse, None)
2845
    }
2846
2847
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2848
    /// changes within `depth` steps of them; the rest is the boundary.
2849
    pub fn clone_shallow(
2850
        url: &str,
2851
        dest: &Path,
2852
        depth: u32,
2853
        max_blob: Option<u64>,
2854
        sparse: &[String],
2855
    ) -> Result<Repo> {
2856
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
2857
    }
2858
2859
    fn clone_full(
2860
        url: &str,
2861
        dest: &Path,
2862
        max_blob: Option<u64>,
2863
        sparse: &[String],
2864
        depth: Option<u32>,
2865
    ) -> Result<Repo> {
2866
        Ok(Self::clone_reporting(url, dest, max_blob, sparse, depth)?.0)
2867
    }
2868
2869
    /// Clone as [`Repo::clone_with`] (or [`Repo::clone_shallow`] with a
2870
    /// `depth`), also returning the bookmarks the fetch left out because
2871
    /// their attestation could not be verified ([`FetchReport::skipped`]),
2872
    /// for the caller to warn about. The bookmark checked out is never one
2873
    /// of them: that fails the clone.
2874
    pub fn clone_reporting(
2875
        url: &str,
2876
        dest: &Path,
2877
        max_blob: Option<u64>,
2878
        sparse: &[String],
2879
        depth: Option<u32>,
2880
    ) -> Result<(Repo, Vec<(String, String)>)> {
2881
        let options = crate::credentials::Credentials::user().options_for(url);
2882
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2883
    }
2884
2885
    /// Clone a subrepo with the credentials the parent would use for its
2886
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2887
    /// subrepo: it finds the same ones again through its parent.
2888
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
2889
        let options = self.credentials_for(url);
2890
        Ok(Self::clone_using(url, dest, None, &[], None, &options)?.0)
2891
    }
2892
2893
    /// The name of a remote of this repository on the same hub (scheme,
2894
    /// host and port) as `url`.
2895
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
2896
        let origin = |u: &str| -> Option<String> {
2897
            let (scheme, rest) = u.split_once("://")?;
2898
            if !matches!(scheme, "http" | "https") {
2899
                return None;
2900
            }
2901
            let host = rest.split('/').next()?;
2902
            Some(format!(
2903
                "{}://{}",
2904
                scheme.to_ascii_lowercase(),
2905
                host.to_ascii_lowercase()
2906
            ))
2907
        };
2908
        let want = origin(url)?;
2909
        self.config
2910
            .remotes
2911
            .iter()
2912
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
2913
            .map(|(name, _)| name.clone())
2914
    }
2915
2916
    /// The token and CA to reach `url` with: those of a remote of this
2917
    /// repository on the same hub (scheme, host and port), else the
2918
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2919
    /// and enclosing checkouts', as a clone would use them.
2920
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
2921
        match self.remote_on_same_hub(url) {
2922
            Some(name) => RemoteOptions {
2923
                repo_id: None,
2924
                cache_dir: None,
2925
                ..self.remote_options(&name)
2926
            },
2927
            None => {
2928
                let mut options = RemoteOptions::default();
2929
                self.fill_credentials(url, &mut options);
2930
                options
2931
            }
2932
        }
2933
    }
2934
2935
    fn clone_using(
2936
        url: &str,
2937
        dest: &Path,
2938
        max_blob: Option<u64>,
2939
        sparse: &[String],
2940
        depth: Option<u32>,
2941
        options: &RemoteOptions,
2942
    ) -> Result<(Repo, Vec<(String, String)>)> {
2943
        let remote = open_remote(url, options)?;
2944
        let id = remote.repo_id()?;
2945
        if id == crate::protocol::UNBOUND_ID {
2946
            return fail(format!(
2947
                "{url} is empty and unbound: push a repository to it first"
2948
            ));
2949
        }
2950
        let mut repo = Repo::init_with_id(dest, id)?;
2951
        repo.config
2952
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2953
        if let Some(m) = max_blob {
2954
            repo.config.set("filter.max-blob", &m.to_string())?;
2955
        } else if !sparse.is_empty() {
2956
            repo.config.set("filter.max-blob", "0")?;
2957
        }
2958
        if !sparse.is_empty() {
2959
            repo.config.set("filter.paths", &sparse.join(","))?;
2960
        }
2961
        repo.save_config()?;
2962
        let skipped = if let Some(depth) = depth {
2963
            repo.fetch_shallow("origin", depth)?;
2964
            Vec::new()
2965
        } else {
2966
            repo.fetch("origin")?.skipped
2967
        };
2968
        let (op_ref, op) = repo.head_op()?;
2969
        // The remote's default bookmark, else ours (main), else its only
2970
        // one; a bookmark the fetch skipped counts, so the clone fails
2971
        // rather than check out another (oxygenhub#266).
2972
        let mut theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2973
        for (name, _) in &skipped {
2974
            theirs.insert(name.clone(), ObjectRef::ZERO);
2975
        }
2976
        // Asked of the remote as now configured, so a store-backed one
2977
        // answers from the mirror the fetch just filled.
2978
        let advertised = repo
2979
            .open_named_remote("origin")
2980
            .ok()
2981
            .and_then(|r| r.refs().ok())
2982
            .and_then(|r| r.default_bookmark);
2983
        let bookmark = advertised
2984
            .filter(|b| theirs.contains_key(b))
2985
            .or_else(|| {
2986
                theirs
2987
                    .contains_key(&repo.config.bookmark)
2988
                    .then(|| repo.config.bookmark.clone())
2989
            })
2990
            .or_else(|| {
2991
                (theirs.len() == 1)
2992
                    .then(|| theirs.keys().next().cloned())
2993
                    .flatten()
2994
            })
2995
            .unwrap_or_else(|| repo.config.bookmark.clone());
2996
        if let Some((_, why)) = skipped.iter().find(|(name, _)| *name == bookmark) {
2997
            return fail(format!("cannot check out {bookmark}: {why}"));
2998
        }
2999
        let initial = repo.config.bookmark.clone();
3000
        if bookmark != repo.config.bookmark {
3001
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
3002
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
3003
            repo.config.bookmark = bookmark.clone();
3004
        }
3005
        if let Some(state) = theirs.get(&bookmark).copied() {
3006
            let heads = repo.store.get_state(&state)?.heads;
3007
            let mut view = op.view.clone();
3008
            // The empty bookmark `init` made goes when another is checked out.
3009
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
3010
                view.bookmarks.remove(&initial);
3011
            }
3012
            view.bookmarks.insert(bookmark, state);
3013
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
3014
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
3015
        }
3016
        Ok((repo, skipped))
3017
    }
3018
}
3019
3020
/// The serial of a reference's next attestation: one more than the last the
3021
/// remote reports, or, for a bookmark the remote does not have, the clock in
3022
/// milliseconds, so a bookmark created again after a deletion goes past the
3023
/// deletion's serial the remote keeps.
3024
fn next_serial(last: Option<u64>) -> u64 {
3025
    match last {
3026
        Some(l) => l + 1,
3027
        None => Hlc::now().wall_ms.max(1),
3028
    }
3029
}