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