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