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