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