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