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