OXYGENHUB
# 85ef828b6bf0 oxygen / crates / oxy-core / src / repo / sync.rs
61.9 KiB · Rust · last changed Delete bookmarks on a remote: oxy push REMOTE --delete NAME 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(&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(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(&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
        let mut bundle = Bundle::default();
275
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
276
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
277
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
278
            if !r.is_zero() && self.store.has(r) {
279
                objects.insert(*r);
280
            }
281
        };
282
        for h in changes {
283
            let c = self.store.get_change(h)?;
284
            let sigs = self.store.signatures(h)?;
285
            add_object(&c.author, &mut objects);
286
            for s in &sigs {
287
                add_object(&s.key, &mut objects);
288
            }
289
            for e in &c.edits {
290
                if let Edit::Replace { old, new, .. } = e {
291
                    for b in [old, new].into_iter().flatten() {
292
                        if self.store.has(b) {
293
                            if let Ok(blob) =
294
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
295
                            {
296
                                if max_blob.is_some_and(|m| blob.length > m) {
297
                                    continue;
298
                                }
299
                                objects.insert(*b);
300
                                objects.extend(blob.chunks.iter().copied());
301
                            }
302
                        }
303
                    }
304
                }
305
            }
306
            for s in self.store.seals_for(h)? {
307
                seals.insert(s);
308
            }
309
            bundle.changes.push((c, sigs));
310
        }
311
        for r in seals {
312
            let attest = self.store.get_attest(&r)?;
313
            let sigs = self.store.signatures(&r)?;
314
            for s in &sigs {
315
                add_object(&s.key, &mut objects);
316
            }
317
            bundle.attests.push(SignedAttest { attest, sigs });
318
        }
319
        for r in objects {
320
            let (ty, body) = self.store.get(&r)?;
321
            bundle.objects.push((ty, body));
322
        }
323
        Ok(bundle)
324
    }
325
326
    /// Store a bundle's contents. With `strict`, every change must
327
    /// authenticate (signature or seal by its author or a delegate).
328
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
329
        self.import_bundle_inner(bundle, strict, false)
330
    }
331
332
    /// Like `import_bundle`, accepting changes whose dependencies are absent
333
    /// (they join the shallow boundary).
334
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
335
        self.import_bundle_inner(bundle, strict, true)
336
    }
337
338
    fn import_bundle_inner(
339
        &self,
340
        bundle: &Bundle,
341
        strict: bool,
342
        shallow: bool,
343
    ) -> Result<Vec<ChangeHash>> {
344
        let batch = self.store.begin_batch()?;
345
        let result = self.import_bundle_batched(bundle, strict, shallow);
346
        batch.finish()?;
347
        result
348
    }
349
350
    fn import_bundle_batched(
351
        &self,
352
        bundle: &Bundle,
353
        strict: bool,
354
        shallow: bool,
355
    ) -> Result<Vec<ChangeHash>> {
356
        for (ty, body) in &bundle.objects {
357
            match ty {
358
                ObjectType::Chunk
359
                | ObjectType::Blob
360
                | ObjectType::Identity
361
                | ObjectType::State
362
                | ObjectType::Checkpoint => {
363
                    self.store.put(*ty, body)?;
364
                }
365
                other => return fail(format!("bundle may not carry {} objects", other.name())),
366
            }
367
        }
368
        for sa in &bundle.attests {
369
            let r = self.store.put_attest(&sa.attest)?;
370
            for sig in &sa.sigs {
371
                self.store.put_signature(&r, sig)?;
372
            }
373
            if let AttestBody::Seal { hashes } = &sa.attest.body {
374
                for h in hashes {
375
                    self.store.index_seal(h, &r)?;
376
                }
377
            }
378
        }
379
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
380
        let boundary = self.boundary();
381
        let mut imported = Vec::new();
382
        for (c, sigs) in &bundle.changes {
383
            let h = c.hash();
384
            for d in &c.deps {
385
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
386
                {
387
                    return fail(format!(
388
                        "change {} depends on {}, which is neither stored nor in the bundle",
389
                        h.short(12),
390
                        d.short(12)
391
                    ));
392
                }
393
            }
394
            self.store.put_change(c)?;
395
            for sig in sigs {
396
                self.store.put_signature(&h, sig)?;
397
            }
398
            imported.push(h);
399
        }
400
        if strict {
401
            for h in &imported {
402
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
403
                    return fail(format!(
404
                        "change {} is not authenticated by its author",
405
                        h.short(12)
406
                    ));
407
                }
408
            }
409
        }
410
        Ok(imported)
411
    }
412
413
    /// Verify a reference attestation against an update it claims to describe.
414
    /// `allow_equal` lets a client re-read the attestation it already has; a
415
    /// server receiving a push requires a strictly greater serial.
416
    /// A reference attestation signed by a delegate of an identity the
417
    /// rule lists is authorized as that identity (spec §14.5): the identity
418
    /// named the delegate, and the policy names the identity. Revoked keys
419
    /// authorize nothing either way.
420
    pub(crate) fn delegate_authorized(
421
        &self,
422
        p: &crate::policy::Policy,
423
        signer: &KeyId,
424
        reference: &str,
425
    ) -> bool {
426
        if p.is_revoked(signer) {
427
            return false;
428
        }
429
        let Some(rule) = p.rule_for(reference) else {
430
            return false;
431
        };
432
        rule.keys.iter().any(|k| {
433
            !p.is_revoked(k)
434
                && p.identity(k)
435
                    .cloned()
436
                    .or_else(|| self.store.get_identity(k).ok())
437
                    .is_some_and(|id| id.delegates.contains(signer))
438
        })
439
    }
440
441
    fn check_ref_attest(
442
        &self,
443
        sa: &SignedAttest,
444
        name: &str,
445
        old_state: &ObjectRef,
446
        new_state: &ObjectRef,
447
        last_serial: Option<u64>,
448
        allow_equal: bool,
449
    ) -> std::result::Result<u64, String> {
450
        let AttestBody::Ref {
451
            name: n,
452
            old_state: o,
453
            new_state: nw,
454
            serial,
455
        } = &sa.attest.body
456
        else {
457
            return Err("attestation is not a ref attestation".into());
458
        };
459
        if n != name || o != old_state || nw != new_state {
460
            return Err("attestation does not describe this update".into());
461
        }
462
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
463
            return Err("attestation is for a different repository".into());
464
        }
465
        if let Some(last) = last_serial {
466
            if *serial < last || (*serial == last && !allow_equal) {
467
                return Err(format!(
468
                    "attestation serial {serial} is not greater than the last seen {last}"
469
                ));
470
            }
471
        }
472
        let r = sa.attest.hash();
473
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
474
        let id = self
475
            .store
476
            .get_identity(&sig.key)
477
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
478
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
479
        Ok(*serial)
480
    }
481
482
    /// Accept a push (spec §16.4). Without a trust policy every repository
483
    /// is unverified, so unsigned changes and unattested updates are accepted;
484
    /// attestations that are present must still be valid. With a policy,
485
    /// every change and update is checked against it. A newer policy in the
486
    /// push is applied first when it is signed by the current roots.
487
    pub fn receive_push(
488
        &self,
489
        bundle: Bundle,
490
        updates: Vec<RefUpdate>,
491
        policy: Option<SignedPolicy>,
492
        tags: Vec<crate::protocol::TagRef>,
493
    ) -> Result<Vec<RefResult>> {
494
        Ok(self
495
            .receive_push_report(bundle, updates, policy, tags)?
496
            .results)
497
    }
498
499
    /// `receive_push` with what a host wants to log: each accepted
500
    /// reference's old and new state and heads, and the changes this push
501
    /// stored (hub spec §6.12).
502
    pub fn receive_push_report(
503
        &self,
504
        bundle: Bundle,
505
        updates: Vec<RefUpdate>,
506
        policy: Option<SignedPolicy>,
507
        tags: Vec<crate::protocol::TagRef>,
508
    ) -> Result<PushReport> {
509
        let mut report = PushReport::default();
510
        let results = &mut report.results;
511
        if let Some(sp) = policy {
512
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
513
                Ok(()) => {
514
                    results.push(RefResult {
515
                        name: "policy".into(),
516
                        ok: true,
517
                        reason: format!("serial {}", sp.policy.serial),
518
                    });
519
                }
520
                Err(e) => {
521
                    results.push(RefResult {
522
                        name: "policy".into(),
523
                        ok: false,
524
                        reason: e,
525
                    });
526
                    for u in updates {
527
                        results.push(RefResult {
528
                            name: u.name,
529
                            ok: false,
530
                            reason: "policy update was rejected".into(),
531
                        });
532
                    }
533
                    return Ok(report);
534
                }
535
            }
536
        }
537
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
538
        match self.import_bundle(&bundle, policy.is_some()) {
539
            Ok(imported) => report.imported = imported,
540
            Err(e) => {
541
                for u in updates {
542
                    results.push(RefResult {
543
                        name: u.name,
544
                        ok: false,
545
                        reason: e.to_string(),
546
                    });
547
                }
548
                return Ok(report);
549
            }
550
        }
551
        let (op_ref, op) = self.head_op()?;
552
        let mut view = op.view.clone();
553
        let mut names = Vec::new();
554
        for u in updates {
555
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
556
            let (ok, reason) = match outcome {
557
                Ok(()) => (true, String::new()),
558
                Err(e) => (false, e),
559
            };
560
            if ok {
561
                names.push(u.name.clone());
562
                let heads = self
563
                    .store
564
                    .get_state(&u.new_state)
565
                    .map(|s| s.heads)
566
                    .unwrap_or_default();
567
                report.updated.push(RefUpdated {
568
                    name: u.name.clone(),
569
                    old_state: u.old_state,
570
                    new_state: u.new_state,
571
                    heads,
572
                });
573
            }
574
            results.push(RefResult {
575
                name: u.name,
576
                ok,
577
                reason,
578
            });
579
        }
580
        for t in &tags {
581
            let name = format!("tags/{}", t.name);
582
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
583
                Ok(()) => {
584
                    names.push(name.clone());
585
                    results.push(RefResult {
586
                        name,
587
                        ok: true,
588
                        reason: String::new(),
589
                    });
590
                }
591
                Err(e) => results.push(RefResult {
592
                    name,
593
                    ok: false,
594
                    reason: e,
595
                }),
596
            }
597
        }
598
        if !names.is_empty() {
599
            self.record_op(
600
                &[op_ref],
601
                &format!("push received: {}", names.join(" ")),
602
                view,
603
            )?;
604
        }
605
        Ok(report)
606
    }
607
608
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
609
    /// at `old_state`, is never the repository's own bookmark (its default),
610
    /// and under a policy needs an attestation by a key that may update it.
611
    /// The deletion's attestation stays the bookmark's latest, so an older
612
    /// one cannot be replayed to bring it back.
613
    fn apply_deletion(
614
        &self,
615
        view: &mut View,
616
        u: &RefUpdate,
617
        policy: Option<&crate::policy::Policy>,
618
    ) -> std::result::Result<(), String> {
619
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
620
            return Err(format!("no bookmark {:?} to delete", u.name));
621
        };
622
        if current != u.old_state {
623
            return Err("stale: the remote bookmark has moved; pull first".into());
624
        }
625
        if u.name == self.config.bookmark {
626
            return Err(format!(
627
                "{:?} is this repository's default bookmark and cannot be deleted",
628
                u.name
629
            ));
630
        }
631
        if let Some(p) = policy {
632
            let Some(sa) = &u.attestation else {
633
                return Err(format!(
634
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
635
                    u.name
636
                ));
637
            };
638
            let signer = sa
639
                .sigs
640
                .first()
641
                .map(|s| s.key)
642
                .ok_or("attestation carries no signature")?;
643
            if !p.authorizes(&signer, &u.name) && !self.delegate_authorized(p, &signer, &u.name) {
644
                return Err(format!(
645
                    "key {} may not delete {:?} under this repository's policy",
646
                    signer.short(12),
647
                    u.name
648
                ));
649
            }
650
        }
651
        if let Some(sa) = &u.attestation {
652
            let last = self
653
                .latest_ref_attest(&u.name)
654
                .map_err(|e| e.to_string())?
655
                .and_then(|(_, a)| match a.attest.body {
656
                    AttestBody::Ref { serial, .. } => Some(serial),
657
                    _ => None,
658
                });
659
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
660
            let r = self
661
                .store
662
                .put_attest(&sa.attest)
663
                .map_err(|e| e.to_string())?;
664
            for sig in &sa.sigs {
665
                self.store
666
                    .put_signature(&r, sig)
667
                    .map_err(|e| e.to_string())?;
668
            }
669
            self.set_ref_attest(&u.name, &r)
670
                .map_err(|e| e.to_string())?;
671
        }
672
        view.bookmarks.remove(&u.name);
673
        Ok(())
674
    }
675
676
    fn apply_update(
677
        &self,
678
        view: &mut View,
679
        u: &RefUpdate,
680
        policy: Option<&crate::policy::Policy>,
681
    ) -> std::result::Result<(), String> {
682
        if u.name == "policy" {
683
            return Err(
684
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
685
            );
686
        }
687
        let empty = self
688
            .store
689
            .put_state(&StateObject::new(vec![]))
690
            .map_err(|e| e.to_string())?;
691
        if u.new_state.is_zero() {
692
            return self.apply_deletion(view, u, policy);
693
        }
694
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
695
        if current != u.old_state {
696
            return Err("stale: the remote bookmark has moved; pull first".into());
697
        }
698
        let new_state = self
699
            .store
700
            .get_state(&u.new_state)
701
            .map_err(|_| "new state object is missing".to_string())?;
702
        for h in &new_state.heads {
703
            if !self.store.has(h) {
704
                return Err(format!("head {} is missing", h.short(12)));
705
            }
706
        }
707
        if !u.force {
708
            let old_heads = self
709
                .store
710
                .get_state(&current)
711
                .map_err(|e| e.to_string())?
712
                .heads;
713
            let closure = self
714
                .closure_in_store(&new_state.heads)
715
                .map_err(|e| e.to_string())?;
716
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
717
                return Err(format!(
718
                    "not a fast-forward: current head {} would be dropped (use --force)",
719
                    h.short(12)
720
                ));
721
            }
722
        }
723
        if let Some(p) = policy {
724
            let Some(sa) = &u.attestation else {
725
                return Err(format!(
726
                    "{:?} requires a signed reference attestation under this repository's policy",
727
                    u.name
728
                ));
729
            };
730
            let signer = sa
731
                .sigs
732
                .first()
733
                .map(|s| s.key)
734
                .ok_or("attestation carries no signature")?;
735
            if !p.authorizes(&signer, &u.name) && !self.delegate_authorized(p, &signer, &u.name) {
736
                return Err(format!(
737
                    "key {} may not update {:?} under this repository's policy",
738
                    signer.short(12),
739
                    u.name
740
                ));
741
            }
742
            let old_heads = self
743
                .store
744
                .get_state(&current)
745
                .map_err(|e| e.to_string())?
746
                .heads;
747
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
748
        }
749
        if let Some(sa) = &u.attestation {
750
            let last = self
751
                .latest_ref_attest(&u.name)
752
                .map_err(|e| e.to_string())?
753
                .and_then(|(_, a)| match a.attest.body {
754
                    AttestBody::Ref { serial, .. } => Some(serial),
755
                    _ => None,
756
                });
757
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
758
            let r = self
759
                .store
760
                .put_attest(&sa.attest)
761
                .map_err(|e| e.to_string())?;
762
            for sig in &sa.sigs {
763
                self.store
764
                    .put_signature(&r, sig)
765
                    .map_err(|e| e.to_string())?;
766
            }
767
            self.set_ref_attest(&u.name, &r)
768
                .map_err(|e| e.to_string())?;
769
        }
770
        view.bookmarks.insert(u.name.clone(), u.new_state);
771
        Ok(())
772
    }
773
774
    // ------------------------------------------------------------ client side
775
776
    fn remote_url(&self, name: &str) -> Result<String> {
777
        self.config.remotes.get(name).cloned().ok_or_else(|| {
778
            RepoError::Msg(format!(
779
                "no remote named {name:?}; add one with `oxy remote add`"
780
            ))
781
        })
782
    }
783
784
    /// Credentials and trust for a remote: `remote.<name>.token` (else
785
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
786
    /// Refuse a remote that is another repository. An **unbound** remote
787
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
788
    /// for pushes, which bind it to this repository's id (spec §16.1).
789
    fn check_remote_id(
790
        &self,
791
        remote: &dyn crate::protocol::Remote,
792
        remote_name: &str,
793
        allow_unbound: bool,
794
    ) -> Result<()> {
795
        let theirs = remote.repo_id()?;
796
        if theirs == self.id()? {
797
            return Ok(());
798
        }
799
        if theirs == crate::protocol::UNBOUND_ID {
800
            if allow_unbound {
801
                return Ok(());
802
            }
803
            return fail(format!(
804
                "remote {remote_name:?} is empty and unbound: push to it first"
805
            ));
806
        }
807
        fail(format!(
808
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
809
        ))
810
    }
811
812
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
813
        RemoteOptions {
814
            repo_id: self.id().ok(),
815
            token: self
816
                .config
817
                .remote_tokens
818
                .get(name)
819
                .cloned()
820
                .or_else(|| std::env::var("OXY_TOKEN").ok()),
821
            ca: self
822
                .config
823
                .remote_cas
824
                .get(name)
825
                .map(PathBuf::from)
826
                .or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
827
        }
828
    }
829
830
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
831
    /// no changes and no reference updates, which the receiver stores.
832
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
833
        let remote = self.open_named_remote(remote_name)?;
834
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
835
        let mut bundle = Bundle::default();
836
        for r in seals {
837
            let attest = self.store.get_attest(r)?;
838
            let sigs = self.store.signatures(r)?;
839
            bundle
840
                .attests
841
                .push(crate::protocol::SignedAttest { attest, sigs });
842
        }
843
        let results = remote.push(bundle, vec![], None, vec![])?;
844
        if let Some(r) = results.iter().find(|r| !r.ok) {
845
            return fail(format!("{}: {}", r.name, r.reason));
846
        }
847
        Ok(())
848
    }
849
850
    /// The remote whose URL starts with `base` (a hub), if configured.
851
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
852
        let base = base.trim_end_matches('/');
853
        self.config
854
            .remotes
855
            .iter()
856
            .find(|(_, url)| url.trim_end_matches('/') == base)
857
            .map(|(name, _)| name.clone())
858
    }
859
860
    /// Open a remote by name or, failing that, by URL with the default
861
    /// credentials (`OXY_TOKEN`, `OXY_CA`).
862
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
863
        if let Some(name) = self.remote_for_url(url) {
864
            return Ok((name.clone(), self.open_named_remote(&name)?));
865
        }
866
        let options = RemoteOptions {
867
            token: std::env::var("OXY_TOKEN").ok(),
868
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
869
            repo_id: self.id().ok(),
870
        };
871
        Ok((url.to_string(), open_remote(url, &options)?))
872
    }
873
874
    /// Credentials for a URL: those of the configured remote with that
875
    /// URL, else the environment's.
876
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
877
        match self.remote_for_url(url) {
878
            Some(name) => self.remote_options(&name),
879
            None => RemoteOptions {
880
                token: std::env::var("OXY_TOKEN").ok(),
881
                ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
882
                repo_id: self.id().ok(),
883
            },
884
        }
885
    }
886
887
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
888
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
889
    }
890
891
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
892
        self.oxy
893
            .join("remotes")
894
            .join(remote)
895
            .join(format!("{bookmark}.serial"))
896
    }
897
898
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
899
        fs::read_to_string(self.serial_path(remote, bookmark))
900
            .ok()
901
            .and_then(|s| s.trim().parse().ok())
902
    }
903
904
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
905
        let p = self.serial_path(remote, bookmark);
906
        fs::create_dir_all(p.parent().unwrap())?;
907
        write_atomic(&p, serial.to_string().as_bytes())
908
    }
909
910
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
911
        self.oxy.join("remotes").join(remote).join("policy.serial")
912
    }
913
914
    /// The highest policy serial `remote` has ever presented.
915
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
916
        fs::read_to_string(self.policy_serial_path(remote))
917
            .ok()
918
            .and_then(|s| s.trim().parse().ok())
919
    }
920
921
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
922
        let p = self.policy_serial_path(remote);
923
        fs::create_dir_all(p.parent().unwrap())?;
924
        write_atomic(&p, serial.to_string().as_bytes())
925
    }
926
927
    fn lazy_dir(&self) -> PathBuf {
928
        self.oxy.join("lazy")
929
    }
930
931
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
932
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
933
        fs::create_dir_all(self.lazy_dir())?;
934
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
935
    }
936
937
    /// Which remote promised an absent blob, if any.
938
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
939
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
940
            .ok()
941
            .map(|s| s.trim().to_string())
942
    }
943
944
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
945
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
946
        let Some(remote_name) = self.lazy_remote(blob) else {
947
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
948
        };
949
        let remote = self.open_named_remote(&remote_name)?;
950
        let objects = remote.objects(&[*blob])?;
951
        for (ty, body) in objects {
952
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
953
                self.store.put(ty, &body)?;
954
            }
955
        }
956
        if !self.store.has(blob) {
957
            return fail(format!(
958
                "{remote_name} did not send blob {}",
959
                blob.short(12)
960
            ));
961
        }
962
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
963
        Ok(())
964
    }
965
966
    /// After importing from `remote`, record every blob the changes reference
967
    /// that the store lacks as lazily available from that remote.
968
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
969
        let mut n = 0;
970
        for h in changes {
971
            let c = self.store.get_change(h)?;
972
            for e in &c.edits {
973
                if let Edit::Replace { old, new, .. } = e {
974
                    for b in [old, new].into_iter().flatten() {
975
                        if !self.store.has(b) {
976
                            self.register_lazy(b, remote)?;
977
                            n += 1;
978
                        }
979
                    }
980
                }
981
            }
982
        }
983
        Ok(n)
984
    }
985
986
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
987
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
988
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
989
        for st in view
990
            .bookmarks
991
            .values()
992
            .chain(view.remotes.values().flat_map(|b| b.values()))
993
        {
994
            if let Ok(s) = self.store.get_state(st) {
995
                have.extend(s.heads);
996
            }
997
        }
998
        have.extend(view.workspaces.values().copied());
999
        Ok(have.into_iter().collect())
1000
    }
1001
1002
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1003
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1004
        let remote = self.open_named_remote(remote_name)?;
1005
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1006
        let resp = remote.refs()?;
1007
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1008
        // and signed by roots we trust, or on first contact. A remote that
1009
        // once presented a policy may never present none or an older one:
1010
        // that is a downgrade. A remote that never presented one is
1011
        // unverified, and this fetch is checked only as far as possible.
1012
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1013
        let seen = self.remote_policy_serial(remote_name);
1014
        let mut unverified = false;
1015
        match &resp.policy {
1016
            Some(sp) => {
1017
                if seen.is_some_and(|s| sp.policy.serial < s) {
1018
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
1019
                }
1020
                match &local_policy {
1021
                    Some(l) if sp.policy.serial < l.serial => {}
1022
                    Some(l) if sp.policy.serial == l.serial => {
1023
                        if sp.policy.hash() != l.hash() {
1024
                            return fail(format!(
1025
                                "{remote_name} presents a different policy with the same serial {}",
1026
                                l.serial
1027
                            ));
1028
                        }
1029
                    }
1030
                    _ => {
1031
                        self.adopt_policy_chain(
1032
                            &resp.history,
1033
                            sp,
1034
                            &format!("oxy fetch {remote_name}"),
1035
                        )
1036
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1037
                    }
1038
                }
1039
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1040
            }
1041
            None => {
1042
                if seen.is_some() {
1043
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1044
                }
1045
                unverified = true;
1046
            }
1047
        }
1048
        let policy = if unverified {
1049
            None
1050
        } else {
1051
            self.current_policy()?.map(|(_, sp)| sp.policy)
1052
        };
1053
        let (op_ref, op) = self.head_op()?;
1054
        let mut view = op.view.clone();
1055
        let have = self.known_heads(&view)?;
1056
        let mut report = Vec::new();
1057
        let max_blob = self.config.max_blob;
1058
        for r in resp.refs {
1059
            let needed = remote.negotiate(&have, &r.heads)?;
1060
            let bundle = remote.fetch(&needed, max_blob)?;
1061
            // Changes are not individually re-verified here: the bookmark's
1062
            // attestation (checked below) binds its whole state, and the
1063
            // receiver of the push verified the added changes at that time.
1064
            let imported = self.import_bundle(&bundle, false)?;
1065
            if max_blob.is_some() {
1066
                self.register_missing_blobs(&imported, remote_name)?;
1067
            }
1068
            for h in &r.heads {
1069
                if !self.store.has(h) {
1070
                    return fail(format!("remote did not send head {}", h.short(12)));
1071
                }
1072
            }
1073
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1074
            if state != r.state {
1075
                return fail(format!(
1076
                    "remote state {} does not match its heads",
1077
                    r.state.short(12)
1078
                ));
1079
            }
1080
            if let Some(p) = &policy {
1081
                let Some(sa) = &r.attestation else {
1082
                    return fail(format!(
1083
                        "{remote_name}/{} has no attestation, which its policy requires",
1084
                        r.name
1085
                    ));
1086
                };
1087
                let signer = sa
1088
                    .sigs
1089
                    .first()
1090
                    .map(|s| s.key)
1091
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1092
                if !p.authorizes(&signer, &r.name) && !self.delegate_authorized(p, &signer, &r.name) {
1093
                    return fail(format!(
1094
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1095
                        r.name,
1096
                        signer.short(12)
1097
                    ));
1098
                }
1099
            }
1100
            if let Some(sa) = &r.attestation {
1101
                let AttestBody::Ref {
1102
                    old_state,
1103
                    new_state,
1104
                    ..
1105
                } = &sa.attest.body
1106
                else {
1107
                    return fail("remote sent a non-ref attestation for a bookmark");
1108
                };
1109
                let (old_state, new_state) = (*old_state, *new_state);
1110
                let serial = self
1111
                    .check_ref_attest(
1112
                        sa,
1113
                        &r.name,
1114
                        &old_state,
1115
                        &new_state,
1116
                        self.last_seen_serial(remote_name, &r.name),
1117
                        true,
1118
                    )
1119
                    .map_err(|e| {
1120
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
1121
                    })?;
1122
                if new_state != r.state {
1123
                    return fail(format!(
1124
                        "attestation for {}/{} does not cover its current state",
1125
                        remote_name, r.name
1126
                    ));
1127
                }
1128
                let ar = self.store.put_attest(&sa.attest)?;
1129
                for sig in &sa.sigs {
1130
                    self.store.put_signature(&ar, sig)?;
1131
                }
1132
                self.record_serial(remote_name, &r.name, serial)?;
1133
            }
1134
            view.remotes
1135
                .entry(remote_name.to_string())
1136
                .or_default()
1137
                .insert(r.name.clone(), state);
1138
            report.push((r.name, r.heads, imported.len()));
1139
        }
1140
        let mut new_tags = 0;
1141
        for t in &resp.tags {
1142
            if view.tags.contains_key(&t.name) {
1143
                continue;
1144
            }
1145
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
1146
            let missing: Vec<ChangeHash> = t
1147
                .heads
1148
                .iter()
1149
                .filter(|h| !self.store.has(h))
1150
                .copied()
1151
                .collect();
1152
            if !missing.is_empty() {
1153
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1154
                let bundle = remote.fetch(&needed, max_blob)?;
1155
                self.import_bundle(&bundle, false)?;
1156
            }
1157
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1158
            self.adopt_tag(&mut view, t, policy.as_ref())
1159
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
1160
            new_tags += 1;
1161
        }
1162
        if view != op.view {
1163
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1164
        }
1165
        let _ = self.run_hook(
1166
            "post-fetch",
1167
            &format!(
1168
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1169
                json_str(remote_name),
1170
                json_array(report.iter().map(|(n, heads, _)| format!(
1171
                    "{{\"name\":{},\"heads\":{}}}",
1172
                    json_str(n),
1173
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1174
                )))
1175
            ),
1176
        );
1177
        Ok(FetchReport {
1178
            refs: report,
1179
            unverified,
1180
            new_tags,
1181
        })
1182
    }
1183
1184
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1185
    /// the changes within `depth` steps of its heads, and the boundary below.
1186
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1187
        let remote = self.open_named_remote(remote_name)?;
1188
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1189
        let resp = remote.refs()?;
1190
        let bookmark = self.config.bookmark.clone();
1191
        if let Some(sp) = &resp.policy {
1192
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1193
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1194
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1195
        }
1196
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1197
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1198
        };
1199
        if r.heads.is_empty() {
1200
            return Ok(0);
1201
        }
1202
        // Base: the remote's checkpoint of exactly these heads.
1203
        let cp_bundle = remote.checkpoint(&r.heads)?;
1204
        let mut cp_ref = None;
1205
        for (ty, body) in &cp_bundle.objects {
1206
            let put = self.store.put(*ty, body)?;
1207
            if *ty == ObjectType::Checkpoint {
1208
                cp_ref = Some(put);
1209
            }
1210
        }
1211
        let Some(cp_ref) = cp_ref else {
1212
            return fail(format!("{remote_name} sent no checkpoint"));
1213
        };
1214
        self.install_checkpoint(&bookmark, &cp_ref)?;
1215
        // History window.
1216
        let wanted = remote.shallow(&r.heads, depth)?;
1217
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1218
        let imported = self.import_bundle_shallow(&bundle, false)?;
1219
        if self.config.max_blob.is_some() {
1220
            self.register_missing_blobs(&imported, remote_name)?;
1221
        }
1222
        self.refresh_boundary(&imported)?;
1223
        if let Some(sa) = &r.attestation {
1224
            let ar = self.store.put_attest(&sa.attest)?;
1225
            for sig in &sa.sigs {
1226
                self.store.put_signature(&ar, sig)?;
1227
            }
1228
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1229
                self.record_serial(remote_name, &r.name, serial)?;
1230
            }
1231
        }
1232
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1233
        let (op_ref, op) = self.head_op()?;
1234
        let mut view = op.view.clone();
1235
        view.remotes
1236
            .entry(remote_name.to_string())
1237
            .or_default()
1238
            .insert(r.name.clone(), state);
1239
        self.record_op(
1240
            &[op_ref],
1241
            &format!("oxy fetch {remote_name} --depth {depth}"),
1242
            view,
1243
        )?;
1244
        Ok(imported.len())
1245
    }
1246
1247
    /// Fetch, then take the union of the local bookmark's state with the
1248
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1249
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1250
        self.fetch(remote_name)?;
1251
        let (op_ref, op) = self.head_op()?;
1252
        let bookmark = self.config.bookmark.clone();
1253
        let local = self.heads_of(&op.view, &bookmark)?;
1254
        let Some(remote_state) = op
1255
            .view
1256
            .remotes
1257
            .get(remote_name)
1258
            .and_then(|b| b.get(&bookmark))
1259
            .copied()
1260
        else {
1261
            return Ok(PullReport {
1262
                heads: local,
1263
                changed: false,
1264
                checked_out: false,
1265
            });
1266
        };
1267
        let remote_heads = self.store.get_state(&remote_state)?.heads;
1268
        let mut all = local.clone();
1269
        all.extend(remote_heads);
1270
        let st = self.load_state(&all)?;
1271
        let mut heads = st.maximal(&all);
1272
        heads.sort();
1273
        let mut sorted_local = local.clone();
1274
        sorted_local.sort();
1275
        if heads == sorted_local {
1276
            return Ok(PullReport {
1277
                heads,
1278
                changed: false,
1279
                checked_out: false,
1280
            });
1281
        }
1282
        let mut view = op.view.clone();
1283
        view.bookmarks.insert(
1284
            bookmark.clone(),
1285
            self.store.put_state(&StateObject::new(heads.clone()))?,
1286
        );
1287
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1288
        // Follow along if the working copy was clean and on the old heads.
1289
        let snap = self.snapshot("oxy pull")?;
1290
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1291
        let mut base = snap.base.maximal(&snap.wc.deps);
1292
        base.sort();
1293
        let mut checked_out = false;
1294
        if clean && base == sorted_local {
1295
            self.checkout(&heads, false, "oxy pull (checkout)")?;
1296
            checked_out = true;
1297
        }
1298
        Ok(PullReport {
1299
            heads,
1300
            changed: true,
1301
            checked_out,
1302
        })
1303
    }
1304
1305
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1306
    /// changes and attesting the reference when a key is available.
1307
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1308
    /// state, attested when we have an identity. The local bookmark, if
1309
    /// any, is kept; only the remote-tracking entry goes.
1310
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
1311
        let remote = self.open_named_remote(remote_name)?;
1312
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1313
        let resp = remote.refs()?;
1314
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
1315
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1316
        };
1317
        if resp.policy.is_some() && self.secret_key()?.is_none() {
1318
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
1319
        }
1320
        let attestation = match self.secret_key()? {
1321
            Some(_) => Some(self.sign_attest(&Attest {
1322
                repo: self.id()?,
1323
                hlc: Hlc::now(),
1324
                body: AttestBody::Ref {
1325
                    name: bookmark.to_string(),
1326
                    old_state: r.state,
1327
                    new_state: ObjectRef::ZERO,
1328
                    serial: r.last_serial.unwrap_or(0) + 1,
1329
                },
1330
            })?),
1331
            None => None,
1332
        };
1333
        let results = remote.push(
1334
            Bundle::default(),
1335
            vec![RefUpdate {
1336
                name: bookmark.to_string(),
1337
                old_state: r.state,
1338
                new_state: ObjectRef::ZERO,
1339
                force: true,
1340
                attestation,
1341
            }],
1342
            None,
1343
            vec![],
1344
        )?;
1345
        if results.iter().any(|x| x.ok && x.name == bookmark) {
1346
            let (op_ref, op) = self.head_op()?;
1347
            let mut view = op.view.clone();
1348
            if let Some(m) = view.remotes.get_mut(remote_name) {
1349
                m.remove(bookmark);
1350
            }
1351
            self.record_op(
1352
                &[op_ref],
1353
                &format!("oxy push {remote_name} --delete {bookmark}"),
1354
                view,
1355
            )?;
1356
        }
1357
        Ok(results)
1358
    }
1359
1360
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1361
        let bookmark = self.config.bookmark.clone();
1362
        self.push_bookmark(remote_name, &bookmark, force)
1363
    }
1364
1365
    /// `push` for a named bookmark (`oxy push -b NAME`).
1366
    pub fn push_bookmark(
1367
        &self,
1368
        remote_name: &str,
1369
        bookmark: &str,
1370
        force: bool,
1371
    ) -> Result<Vec<RefResult>> {
1372
        let (op_ref, op) = self.head_op()?;
1373
        if !op.view.bookmarks.contains_key(bookmark) {
1374
            return fail(format!("no bookmark {bookmark}"));
1375
        }
1376
        let bookmark = bookmark.to_string();
1377
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1378
        // pre-push hook: may veto before the remote is contacted.
1379
        self.run_hook(
1380
            "pre-push",
1381
            &format!(
1382
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1383
                json_str(remote_name),
1384
                json_str(&bookmark),
1385
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1386
            ),
1387
        )?;
1388
        let remote = self.open_named_remote(remote_name)?;
1389
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1390
        let resp = remote.refs()?;
1391
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1392
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1393
        let policy_to_send = match (&local_policy, &resp.policy) {
1394
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1395
            (Some(l), None) => Some(l.clone()),
1396
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
1397
                return fail(format!(
1398
                    "{remote_name} has a newer policy (serial {}); fetch first",
1399
                    r.policy.serial
1400
                ));
1401
            }
1402
            _ => None,
1403
        };
1404
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1405
        if remote_has_policy && self.secret_key()?.is_none() {
1406
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1407
        }
1408
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1409
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1410
            .tag_refs()?
1411
            .into_iter()
1412
            .filter(|t| !remote_tags.contains(&t.name))
1413
            .collect();
1414
        let refs = resp.refs;
1415
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1416
        let (remote_state, remote_heads, last_serial) =
1417
            match refs.iter().find(|r| r.name == bookmark) {
1418
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1419
                None => (empty, vec![], None),
1420
            };
1421
        let new_state = self
1422
            .store
1423
            .put_state(&StateObject::new(local_heads.clone()))?;
1424
        // A push that carries a policy re-attests the bookmark even when its
1425
        // state is unchanged, so the current attestation is always by a key
1426
        // the current policy authorizes (a revoked key's attestation would
1427
        // otherwise be refused by every later fetch).
1428
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
1429
            return Ok(vec![RefResult {
1430
                name: bookmark,
1431
                ok: true,
1432
                reason: "already up to date".into(),
1433
            }]);
1434
        }
1435
        for h in &remote_heads {
1436
            if !self.store.has(h) {
1437
                return fail(format!(
1438
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
1439
                    h.short(12)
1440
                ));
1441
            }
1442
        }
1443
        if !force {
1444
            let closure = self.closure_in_store(&local_heads)?;
1445
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1446
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1447
            }
1448
        }
1449
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1450
        let mut bundle = self.bundle_for(&to_send)?;
1451
        let key = self.secret_key()?.map(|(k, _)| k);
1452
        if let Some(key) = key {
1453
            // Seal this author's changes that carry no valid authenticator,
1454
            // and adopt anonymous ones (zero author, spec §14.4).
1455
            let mut unsigned = Vec::new();
1456
            for h in &to_send {
1457
                let c = self.store.get_change(h)?;
1458
                if (c.author == key || c.author.is_zero())
1459
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1460
                {
1461
                    unsigned.push(*h);
1462
                }
1463
            }
1464
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
1465
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1466
                bundle.attests.push(sa);
1467
            }
1468
            bundle = self.bundle_for(&to_send)?;
1469
        }
1470
        bundle.objects.push((
1471
            ObjectType::State,
1472
            StateObject::new(local_heads.clone()).encode(),
1473
        ));
1474
        let attestation = match key {
1475
            Some(_) => Some(self.sign_attest(&Attest {
1476
                repo: self.id()?,
1477
                hlc: Hlc::now(),
1478
                body: AttestBody::Ref {
1479
                    name: bookmark.clone(),
1480
                    old_state: remote_state,
1481
                    new_state,
1482
                    serial: next_serial(last_serial),
1483
                },
1484
            })?),
1485
            None => None,
1486
        };
1487
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1488
            AttestBody::Ref { serial, .. } => Some(serial),
1489
            _ => None,
1490
        });
1491
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1492
        // Tag states must be present on the remote: bundle their changes too.
1493
        for t in &tags_to_send {
1494
            let extra = self.negotiate(&remote_heads, &t.heads)?;
1495
            let extra: Vec<ChangeHash> =
1496
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
1497
            if !extra.is_empty() {
1498
                let more = self.bundle_for(&extra)?;
1499
                bundle.changes.extend(more.changes);
1500
                bundle.attests.extend(more.attests);
1501
                bundle.objects.extend(more.objects);
1502
            }
1503
            bundle.objects.push((
1504
                ObjectType::State,
1505
                StateObject::new(t.heads.clone()).encode(),
1506
            ));
1507
        }
1508
        if let Some(l) = &policy_to_send {
1509
            let remote_serial = resp_policy_serial;
1510
            bundle.policies = self
1511
                .policy_history()?
1512
                .into_iter()
1513
                .filter(|sp| {
1514
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1515
                        && sp.policy.serial < l.policy.serial
1516
                })
1517
                .collect();
1518
        }
1519
        let results = remote.push(
1520
            bundle,
1521
            vec![RefUpdate {
1522
                name: bookmark.clone(),
1523
                old_state: remote_state,
1524
                new_state,
1525
                force,
1526
                attestation,
1527
            }],
1528
            policy_to_send,
1529
            tags_to_send,
1530
        )?;
1531
        if let (Some(serial), true) = (
1532
            sent_serial,
1533
            results.iter().any(|r| r.ok && r.name == "policy"),
1534
        ) {
1535
            self.record_policy_serial(remote_name, serial)?;
1536
        }
1537
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1538
            let mut view = op.view.clone();
1539
            view.remotes
1540
                .entry(remote_name.to_string())
1541
                .or_default()
1542
                .insert(bookmark.clone(), new_state);
1543
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1544
            if let Some(s) = serial {
1545
                self.record_serial(remote_name, &bookmark, s)?;
1546
            }
1547
        }
1548
        Ok(results)
1549
    }
1550
1551
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1552
    /// bookmark set to the remote's, working copy checked out.
1553
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1554
        Self::clone_with(url, dest, None, &[])
1555
    }
1556
1557
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1558
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1559
    /// unless a size is given, so out-of-scope binaries are never fetched).
1560
    pub fn clone_with(
1561
        url: &str,
1562
        dest: &Path,
1563
        max_blob: Option<u64>,
1564
        sparse: &[String],
1565
    ) -> Result<Repo> {
1566
        Self::clone_full(url, dest, max_blob, sparse, None)
1567
    }
1568
1569
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1570
    /// changes within `depth` steps of them; the rest is the boundary.
1571
    pub fn clone_shallow(
1572
        url: &str,
1573
        dest: &Path,
1574
        depth: u32,
1575
        max_blob: Option<u64>,
1576
        sparse: &[String],
1577
    ) -> Result<Repo> {
1578
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1579
    }
1580
1581
    fn clone_full(
1582
        url: &str,
1583
        dest: &Path,
1584
        max_blob: Option<u64>,
1585
        sparse: &[String],
1586
        depth: Option<u32>,
1587
    ) -> Result<Repo> {
1588
        let options = RemoteOptions {
1589
            token: std::env::var("OXY_TOKEN").ok(),
1590
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
1591
            repo_id: None,
1592
        };
1593
        let remote = open_remote(url, &options)?;
1594
        let id = remote.repo_id()?;
1595
        if id == crate::protocol::UNBOUND_ID {
1596
            return fail(format!(
1597
                "{url} is empty and unbound: push a repository to it first"
1598
            ));
1599
        }
1600
        let mut repo = Repo::init_with_id(dest, id)?;
1601
        repo.config.set("remote.origin.url", url)?;
1602
        if let Some(m) = max_blob {
1603
            repo.config.set("filter.max-blob", &m.to_string())?;
1604
        } else if !sparse.is_empty() {
1605
            repo.config.set("filter.max-blob", "0")?;
1606
        }
1607
        if !sparse.is_empty() {
1608
            repo.config.set("filter.paths", &sparse.join(","))?;
1609
        }
1610
        repo.save_config()?;
1611
        if let Some(depth) = depth {
1612
            repo.fetch_shallow("origin", depth)?;
1613
        } else {
1614
            repo.fetch("origin")?;
1615
        }
1616
        let (op_ref, op) = repo.head_op()?;
1617
        let bookmark = repo.config.bookmark.clone();
1618
        if let Some(state) = op
1619
            .view
1620
            .remotes
1621
            .get("origin")
1622
            .and_then(|b| b.get(&bookmark))
1623
            .copied()
1624
        {
1625
            let heads = repo.store.get_state(&state)?.heads;
1626
            let mut view = op.view.clone();
1627
            view.bookmarks.insert(bookmark, state);
1628
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1629
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
1630
        }
1631
        Ok(repo)
1632
    }
1633
}
1634
1635
/// The serial of a reference's next attestation: one more than the last the
1636
/// remote reports, or, for a bookmark the remote does not have, the clock in
1637
/// milliseconds, so a bookmark created again after a deletion goes past the
1638
/// deletion's serial the remote keeps.
1639
fn next_serial(last: Option<u64>) -> u64 {
1640
    match last {
1641
        Some(l) => l + 1,
1642
        None => Hlc::now().wall_ms.max(1),
1643
    }
1644
}