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