OXYGENHUB
# 19555025a2ac oxygen / crates / oxy-core / src / repo / sync.rs
53.9 KiB · Rust · last changed Host API: changes from an edit set, delegate-signed reference updates 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(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
    fn delegate_authorized(&self, p: &crate::policy::Policy, signer: &KeyId, reference: &str) -> bool {
421
        if p.is_revoked(signer) {
422
            return false;
423
        }
424
        let Some(rule) = p.rule_for(reference) else { return false };
425
        rule.keys.iter().any(|k| {
426
            !p.is_revoked(k)
427
                && p.identity(k)
428
                    .cloned()
429
                    .or_else(|| self.store.get_identity(k).ok())
430
                    .is_some_and(|id| id.delegates.contains(signer))
431
        })
432
    }
433
434
    fn check_ref_attest(
435
        &self,
436
        sa: &SignedAttest,
437
        name: &str,
438
        old_state: &ObjectRef,
439
        new_state: &ObjectRef,
440
        last_serial: Option<u64>,
441
        allow_equal: bool,
442
    ) -> std::result::Result<u64, String> {
443
        let AttestBody::Ref {
444
            name: n,
445
            old_state: o,
446
            new_state: nw,
447
            serial,
448
        } = &sa.attest.body
449
        else {
450
            return Err("attestation is not a ref attestation".into());
451
        };
452
        if n != name || o != old_state || nw != new_state {
453
            return Err("attestation does not describe this update".into());
454
        }
455
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
456
            return Err("attestation is for a different repository".into());
457
        }
458
        if let Some(last) = last_serial {
459
            if *serial < last || (*serial == last && !allow_equal) {
460
                return Err(format!(
461
                    "attestation serial {serial} is not greater than the last seen {last}"
462
                ));
463
            }
464
        }
465
        let r = sa.attest.hash();
466
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
467
        let id = self
468
            .store
469
            .get_identity(&sig.key)
470
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
471
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
472
        Ok(*serial)
473
    }
474
475
    /// Accept a push (spec §16.4). Without a trust policy every repository
476
    /// is unverified, so unsigned changes and unattested updates are accepted;
477
    /// attestations that are present must still be valid. With a policy,
478
    /// every change and update is checked against it. A newer policy in the
479
    /// push is applied first when it is signed by the current roots.
480
    pub fn receive_push(
481
        &self,
482
        bundle: Bundle,
483
        updates: Vec<RefUpdate>,
484
        policy: Option<SignedPolicy>,
485
        tags: Vec<crate::protocol::TagRef>,
486
    ) -> Result<Vec<RefResult>> {
487
        Ok(self.receive_push_report(bundle, updates, policy, tags)?.results)
488
    }
489
490
    /// `receive_push` with what a host wants to log: each accepted
491
    /// reference's old and new state and heads, and the changes this push
492
    /// stored (hub spec §6.12).
493
    pub fn receive_push_report(
494
        &self,
495
        bundle: Bundle,
496
        updates: Vec<RefUpdate>,
497
        policy: Option<SignedPolicy>,
498
        tags: Vec<crate::protocol::TagRef>,
499
    ) -> Result<PushReport> {
500
        let mut report = PushReport::default();
501
        let results = &mut report.results;
502
        if let Some(sp) = policy {
503
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
504
                Ok(()) => {
505
                    results.push(RefResult {
506
                        name: "policy".into(),
507
                        ok: true,
508
                        reason: format!("serial {}", sp.policy.serial),
509
                    });
510
                }
511
                Err(e) => {
512
                    results.push(RefResult {
513
                        name: "policy".into(),
514
                        ok: false,
515
                        reason: e,
516
                    });
517
                    for u in updates {
518
                        results.push(RefResult {
519
                            name: u.name,
520
                            ok: false,
521
                            reason: "policy update was rejected".into(),
522
                        });
523
                    }
524
                    return Ok(report);
525
                }
526
            }
527
        }
528
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
529
        match self.import_bundle(&bundle, policy.is_some()) {
530
            Ok(imported) => report.imported = imported,
531
            Err(e) => {
532
                for u in updates {
533
                    results.push(RefResult {
534
                        name: u.name,
535
                        ok: false,
536
                        reason: e.to_string(),
537
                    });
538
                }
539
                return Ok(report);
540
            }
541
        }
542
        let (op_ref, op) = self.head_op()?;
543
        let mut view = op.view.clone();
544
        let mut names = Vec::new();
545
        for u in updates {
546
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
547
            let (ok, reason) = match outcome {
548
                Ok(()) => (true, String::new()),
549
                Err(e) => (false, e),
550
            };
551
            if ok {
552
                names.push(u.name.clone());
553
                let heads = self.store.get_state(&u.new_state).map(|s| s.heads).unwrap_or_default();
554
                report.updated.push(RefUpdated { name: u.name.clone(), old_state: u.old_state, new_state: u.new_state, heads });
555
            }
556
            results.push(RefResult {
557
                name: u.name,
558
                ok,
559
                reason,
560
            });
561
        }
562
        for t in &tags {
563
            let name = format!("tags/{}", t.name);
564
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
565
                Ok(()) => {
566
                    names.push(name.clone());
567
                    results.push(RefResult {
568
                        name,
569
                        ok: true,
570
                        reason: String::new(),
571
                    });
572
                }
573
                Err(e) => results.push(RefResult {
574
                    name,
575
                    ok: false,
576
                    reason: e,
577
                }),
578
            }
579
        }
580
        if !names.is_empty() {
581
            self.record_op(
582
                &[op_ref],
583
                &format!("push received: {}", names.join(" ")),
584
                view,
585
            )?;
586
        }
587
        Ok(report)
588
    }
589
590
    fn apply_update(
591
        &self,
592
        view: &mut View,
593
        u: &RefUpdate,
594
        policy: Option<&crate::policy::Policy>,
595
    ) -> std::result::Result<(), String> {
596
        if u.name == "policy" {
597
            return Err(
598
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
599
            );
600
        }
601
        let empty = self
602
            .store
603
            .put_state(&StateObject::new(vec![]))
604
            .map_err(|e| e.to_string())?;
605
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
606
        if current != u.old_state {
607
            return Err("stale: the remote bookmark has moved; pull first".into());
608
        }
609
        let new_state = self
610
            .store
611
            .get_state(&u.new_state)
612
            .map_err(|_| "new state object is missing".to_string())?;
613
        for h in &new_state.heads {
614
            if !self.store.has(h) {
615
                return Err(format!("head {} is missing", h.short(12)));
616
            }
617
        }
618
        if !u.force {
619
            let old_heads = self
620
                .store
621
                .get_state(&current)
622
                .map_err(|e| e.to_string())?
623
                .heads;
624
            let closure = self
625
                .closure_in_store(&new_state.heads)
626
                .map_err(|e| e.to_string())?;
627
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
628
                return Err(format!(
629
                    "not a fast-forward: current head {} would be dropped (use --force)",
630
                    h.short(12)
631
                ));
632
            }
633
        }
634
        if let Some(p) = policy {
635
            let Some(sa) = &u.attestation else {
636
                return Err(format!(
637
                    "{:?} requires a signed reference attestation under this repository's policy",
638
                    u.name
639
                ));
640
            };
641
            let signer = sa
642
                .sigs
643
                .first()
644
                .map(|s| s.key)
645
                .ok_or("attestation carries no signature")?;
646
            if !p.authorizes(&signer, &u.name) && !self.delegate_authorized(p, &signer, &u.name) {
647
                return Err(format!(
648
                    "key {} may not update {:?} under this repository's policy",
649
                    signer.short(12),
650
                    u.name
651
                ));
652
            }
653
            let old_heads = self
654
                .store
655
                .get_state(&current)
656
                .map_err(|e| e.to_string())?
657
                .heads;
658
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
659
        }
660
        if let Some(sa) = &u.attestation {
661
            let last = self
662
                .latest_ref_attest(&u.name)
663
                .map_err(|e| e.to_string())?
664
                .and_then(|(_, a)| match a.attest.body {
665
                    AttestBody::Ref { serial, .. } => Some(serial),
666
                    _ => None,
667
                });
668
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
669
            let r = self
670
                .store
671
                .put_attest(&sa.attest)
672
                .map_err(|e| e.to_string())?;
673
            for sig in &sa.sigs {
674
                self.store
675
                    .put_signature(&r, sig)
676
                    .map_err(|e| e.to_string())?;
677
            }
678
            self.set_ref_attest(&u.name, &r)
679
                .map_err(|e| e.to_string())?;
680
        }
681
        view.bookmarks.insert(u.name.clone(), u.new_state);
682
        Ok(())
683
    }
684
685
    // ------------------------------------------------------------ client side
686
687
    fn remote_url(&self, name: &str) -> Result<String> {
688
        self.config.remotes.get(name).cloned().ok_or_else(|| {
689
            RepoError::Msg(format!(
690
                "no remote named {name:?}; add one with `oxy remote add`"
691
            ))
692
        })
693
    }
694
695
    /// Credentials and trust for a remote: `remote.<name>.token` (else
696
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
697
    /// Refuse a remote that is another repository. An **unbound** remote
698
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
699
    /// for pushes, which bind it to this repository's id (spec §16.1).
700
    fn check_remote_id(
701
        &self,
702
        remote: &dyn crate::protocol::Remote,
703
        remote_name: &str,
704
        allow_unbound: bool,
705
    ) -> Result<()> {
706
        let theirs = remote.repo_id()?;
707
        if theirs == self.id()? {
708
            return Ok(());
709
        }
710
        if theirs == crate::protocol::UNBOUND_ID {
711
            if allow_unbound {
712
                return Ok(());
713
            }
714
            return fail(format!(
715
                "remote {remote_name:?} is empty and unbound: push to it first"
716
            ));
717
        }
718
        fail(format!(
719
            "remote {remote_name:?} is a different repository (repository IDs differ)"
720
        ))
721
    }
722
723
    fn remote_options(&self, name: &str) -> RemoteOptions {
724
        RemoteOptions {
725
            repo_id: self.id().ok(),
726
            token: self
727
                .config
728
                .remote_tokens
729
                .get(name)
730
                .cloned()
731
                .or_else(|| std::env::var("OXY_TOKEN").ok()),
732
            ca: self
733
                .config
734
                .remote_cas
735
                .get(name)
736
                .map(PathBuf::from)
737
                .or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
738
        }
739
    }
740
741
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
742
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
743
    }
744
745
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
746
        self.oxy
747
            .join("remotes")
748
            .join(remote)
749
            .join(format!("{bookmark}.serial"))
750
    }
751
752
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
753
        fs::read_to_string(self.serial_path(remote, bookmark))
754
            .ok()
755
            .and_then(|s| s.trim().parse().ok())
756
    }
757
758
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
759
        let p = self.serial_path(remote, bookmark);
760
        fs::create_dir_all(p.parent().unwrap())?;
761
        write_atomic(&p, serial.to_string().as_bytes())
762
    }
763
764
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
765
        self.oxy.join("remotes").join(remote).join("policy.serial")
766
    }
767
768
    /// The highest policy serial `remote` has ever presented.
769
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
770
        fs::read_to_string(self.policy_serial_path(remote))
771
            .ok()
772
            .and_then(|s| s.trim().parse().ok())
773
    }
774
775
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
776
        let p = self.policy_serial_path(remote);
777
        fs::create_dir_all(p.parent().unwrap())?;
778
        write_atomic(&p, serial.to_string().as_bytes())
779
    }
780
781
    fn lazy_dir(&self) -> PathBuf {
782
        self.oxy.join("lazy")
783
    }
784
785
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
786
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
787
        fs::create_dir_all(self.lazy_dir())?;
788
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
789
    }
790
791
    /// Which remote promised an absent blob, if any.
792
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
793
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
794
            .ok()
795
            .map(|s| s.trim().to_string())
796
    }
797
798
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
799
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
800
        let Some(remote_name) = self.lazy_remote(blob) else {
801
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
802
        };
803
        let remote = self.open_named_remote(&remote_name)?;
804
        let objects = remote.objects(&[*blob])?;
805
        for (ty, body) in objects {
806
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
807
                self.store.put(ty, &body)?;
808
            }
809
        }
810
        if !self.store.has(blob) {
811
            return fail(format!(
812
                "{remote_name} did not send blob {}",
813
                blob.short(12)
814
            ));
815
        }
816
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
817
        Ok(())
818
    }
819
820
    /// After importing from `remote`, record every blob the changes reference
821
    /// that the store lacks as lazily available from that remote.
822
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
823
        let mut n = 0;
824
        for h in changes {
825
            let c = self.store.get_change(h)?;
826
            for e in &c.edits {
827
                if let Edit::Replace { old, new, .. } = e {
828
                    for b in [old, new].into_iter().flatten() {
829
                        if !self.store.has(b) {
830
                            self.register_lazy(b, remote)?;
831
                            n += 1;
832
                        }
833
                    }
834
                }
835
            }
836
        }
837
        Ok(n)
838
    }
839
840
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
841
    fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
842
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
843
        for st in view
844
            .bookmarks
845
            .values()
846
            .chain(view.remotes.values().flat_map(|b| b.values()))
847
        {
848
            if let Ok(s) = self.store.get_state(st) {
849
                have.extend(s.heads);
850
            }
851
        }
852
        have.extend(view.workspaces.values().copied());
853
        Ok(have.into_iter().collect())
854
    }
855
856
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
857
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
858
        let remote = self.open_named_remote(remote_name)?;
859
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
860
        let resp = remote.refs()?;
861
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
862
        // and signed by roots we trust, or on first contact. A remote that
863
        // once presented a policy may never present none or an older one:
864
        // that is a downgrade. A remote that never presented one is
865
        // unverified, and this fetch is checked only as far as possible.
866
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
867
        let seen = self.remote_policy_serial(remote_name);
868
        let mut unverified = false;
869
        match &resp.policy {
870
            Some(sp) => {
871
                if seen.is_some_and(|s| sp.policy.serial < s) {
872
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
873
                }
874
                match &local_policy {
875
                    Some(l) if sp.policy.serial < l.serial => {}
876
                    Some(l) if sp.policy.serial == l.serial => {
877
                        if sp.policy.hash() != l.hash() {
878
                            return fail(format!(
879
                                "{remote_name} presents a different policy with the same serial {}",
880
                                l.serial
881
                            ));
882
                        }
883
                    }
884
                    _ => {
885
                        self.adopt_policy_chain(
886
                            &resp.history,
887
                            sp,
888
                            &format!("oxy fetch {remote_name}"),
889
                        )
890
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
891
                    }
892
                }
893
                self.record_policy_serial(remote_name, sp.policy.serial)?;
894
            }
895
            None => {
896
                if seen.is_some() {
897
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
898
                }
899
                unverified = true;
900
            }
901
        }
902
        let policy = if unverified {
903
            None
904
        } else {
905
            self.current_policy()?.map(|(_, sp)| sp.policy)
906
        };
907
        let (op_ref, op) = self.head_op()?;
908
        let mut view = op.view.clone();
909
        let have = self.known_heads(&view)?;
910
        let mut report = Vec::new();
911
        let max_blob = self.config.max_blob;
912
        for r in resp.refs {
913
            let needed = remote.negotiate(&have, &r.heads)?;
914
            let bundle = remote.fetch(&needed, max_blob)?;
915
            // Changes are not individually re-verified here: the bookmark's
916
            // attestation (checked below) binds its whole state, and the
917
            // receiver of the push verified the added changes at that time.
918
            let imported = self.import_bundle(&bundle, false)?;
919
            if max_blob.is_some() {
920
                self.register_missing_blobs(&imported, remote_name)?;
921
            }
922
            for h in &r.heads {
923
                if !self.store.has(h) {
924
                    return fail(format!("remote did not send head {}", h.short(12)));
925
                }
926
            }
927
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
928
            if state != r.state {
929
                return fail(format!(
930
                    "remote state {} does not match its heads",
931
                    r.state.short(12)
932
                ));
933
            }
934
            if let Some(p) = &policy {
935
                let Some(sa) = &r.attestation else {
936
                    return fail(format!(
937
                        "{remote_name}/{} has no attestation, which its policy requires",
938
                        r.name
939
                    ));
940
                };
941
                let signer = sa
942
                    .sigs
943
                    .first()
944
                    .map(|s| s.key)
945
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
946
                if !p.authorizes(&signer, &r.name) {
947
                    return fail(format!(
948
                        "{remote_name}/{}: attested by {}, which the policy does not authorize",
949
                        r.name,
950
                        signer.short(12)
951
                    ));
952
                }
953
            }
954
            if let Some(sa) = &r.attestation {
955
                let AttestBody::Ref {
956
                    old_state,
957
                    new_state,
958
                    ..
959
                } = &sa.attest.body
960
                else {
961
                    return fail("remote sent a non-ref attestation for a bookmark");
962
                };
963
                let (old_state, new_state) = (*old_state, *new_state);
964
                let serial = self
965
                    .check_ref_attest(
966
                        sa,
967
                        &r.name,
968
                        &old_state,
969
                        &new_state,
970
                        self.last_seen_serial(remote_name, &r.name),
971
                        true,
972
                    )
973
                    .map_err(|e| {
974
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
975
                    })?;
976
                if new_state != r.state {
977
                    return fail(format!(
978
                        "attestation for {}/{} does not cover its current state",
979
                        remote_name, r.name
980
                    ));
981
                }
982
                let ar = self.store.put_attest(&sa.attest)?;
983
                for sig in &sa.sigs {
984
                    self.store.put_signature(&ar, sig)?;
985
                }
986
                self.record_serial(remote_name, &r.name, serial)?;
987
            }
988
            view.remotes
989
                .entry(remote_name.to_string())
990
                .or_default()
991
                .insert(r.name.clone(), state);
992
            report.push((r.name, r.heads, imported.len()));
993
        }
994
        let mut new_tags = 0;
995
        for t in &resp.tags {
996
            if view.tags.contains_key(&t.name) {
997
                continue;
998
            }
999
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
1000
            let missing: Vec<ChangeHash> = t
1001
                .heads
1002
                .iter()
1003
                .filter(|h| !self.store.has(h))
1004
                .copied()
1005
                .collect();
1006
            if !missing.is_empty() {
1007
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1008
                let bundle = remote.fetch(&needed, max_blob)?;
1009
                self.import_bundle(&bundle, false)?;
1010
            }
1011
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1012
            self.adopt_tag(&mut view, t, policy.as_ref())
1013
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
1014
            new_tags += 1;
1015
        }
1016
        if view != op.view {
1017
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1018
        }
1019
        let _ = self.run_hook(
1020
            "post-fetch",
1021
            &format!(
1022
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1023
                json_str(remote_name),
1024
                json_array(report.iter().map(|(n, heads, _)| format!(
1025
                    "{{\"name\":{},\"heads\":{}}}",
1026
                    json_str(n),
1027
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1028
                )))
1029
            ),
1030
        );
1031
        Ok(FetchReport {
1032
            refs: report,
1033
            unverified,
1034
            new_tags,
1035
        })
1036
    }
1037
1038
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1039
    /// the changes within `depth` steps of its heads, and the boundary below.
1040
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1041
        let remote = self.open_named_remote(remote_name)?;
1042
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1043
        let resp = remote.refs()?;
1044
        let bookmark = self.config.bookmark.clone();
1045
        if let Some(sp) = &resp.policy {
1046
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1047
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1048
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1049
        }
1050
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1051
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1052
        };
1053
        if r.heads.is_empty() {
1054
            return Ok(0);
1055
        }
1056
        // Base: the remote's checkpoint of exactly these heads.
1057
        let cp_bundle = remote.checkpoint(&r.heads)?;
1058
        let mut cp_ref = None;
1059
        for (ty, body) in &cp_bundle.objects {
1060
            let put = self.store.put(*ty, body)?;
1061
            if *ty == ObjectType::Checkpoint {
1062
                cp_ref = Some(put);
1063
            }
1064
        }
1065
        let Some(cp_ref) = cp_ref else {
1066
            return fail(format!("{remote_name} sent no checkpoint"));
1067
        };
1068
        self.install_checkpoint(&bookmark, &cp_ref)?;
1069
        // History window.
1070
        let wanted = remote.shallow(&r.heads, depth)?;
1071
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1072
        let imported = self.import_bundle_shallow(&bundle, false)?;
1073
        if self.config.max_blob.is_some() {
1074
            self.register_missing_blobs(&imported, remote_name)?;
1075
        }
1076
        self.refresh_boundary(&imported)?;
1077
        if let Some(sa) = &r.attestation {
1078
            let ar = self.store.put_attest(&sa.attest)?;
1079
            for sig in &sa.sigs {
1080
                self.store.put_signature(&ar, sig)?;
1081
            }
1082
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1083
                self.record_serial(remote_name, &r.name, serial)?;
1084
            }
1085
        }
1086
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1087
        let (op_ref, op) = self.head_op()?;
1088
        let mut view = op.view.clone();
1089
        view.remotes
1090
            .entry(remote_name.to_string())
1091
            .or_default()
1092
            .insert(r.name.clone(), state);
1093
        self.record_op(
1094
            &[op_ref],
1095
            &format!("oxy fetch {remote_name} --depth {depth}"),
1096
            view,
1097
        )?;
1098
        Ok(imported.len())
1099
    }
1100
1101
    /// Fetch, then take the union of the local bookmark's state with the
1102
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1103
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1104
        self.fetch(remote_name)?;
1105
        let (op_ref, op) = self.head_op()?;
1106
        let bookmark = self.config.bookmark.clone();
1107
        let local = self.heads_of(&op.view, &bookmark)?;
1108
        let Some(remote_state) = op
1109
            .view
1110
            .remotes
1111
            .get(remote_name)
1112
            .and_then(|b| b.get(&bookmark))
1113
            .copied()
1114
        else {
1115
            return Ok(PullReport {
1116
                heads: local,
1117
                changed: false,
1118
                checked_out: false,
1119
            });
1120
        };
1121
        let remote_heads = self.store.get_state(&remote_state)?.heads;
1122
        let mut all = local.clone();
1123
        all.extend(remote_heads);
1124
        let st = self.load_state(&all)?;
1125
        let mut heads = st.maximal(&all);
1126
        heads.sort();
1127
        let mut sorted_local = local.clone();
1128
        sorted_local.sort();
1129
        if heads == sorted_local {
1130
            return Ok(PullReport {
1131
                heads,
1132
                changed: false,
1133
                checked_out: false,
1134
            });
1135
        }
1136
        let mut view = op.view.clone();
1137
        view.bookmarks.insert(
1138
            bookmark.clone(),
1139
            self.store.put_state(&StateObject::new(heads.clone()))?,
1140
        );
1141
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1142
        // Follow along if the working copy was clean and on the old heads.
1143
        let snap = self.snapshot("oxy pull")?;
1144
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1145
        let mut base = snap.base.maximal(&snap.wc.deps);
1146
        base.sort();
1147
        let mut checked_out = false;
1148
        if clean && base == sorted_local {
1149
            self.checkout(&heads, false, "oxy pull (checkout)")?;
1150
            checked_out = true;
1151
        }
1152
        Ok(PullReport {
1153
            heads,
1154
            changed: true,
1155
            checked_out,
1156
        })
1157
    }
1158
1159
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1160
    /// changes and attesting the reference when a key is available.
1161
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1162
        let bookmark = self.config.bookmark.clone();
1163
        self.push_bookmark(remote_name, &bookmark, force)
1164
    }
1165
1166
    /// `push` for a named bookmark (`oxy push -b NAME`).
1167
    pub fn push_bookmark(
1168
        &self,
1169
        remote_name: &str,
1170
        bookmark: &str,
1171
        force: bool,
1172
    ) -> Result<Vec<RefResult>> {
1173
        let (op_ref, op) = self.head_op()?;
1174
        if !op.view.bookmarks.contains_key(bookmark) {
1175
            return fail(format!("no bookmark {bookmark}"));
1176
        }
1177
        let bookmark = bookmark.to_string();
1178
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1179
        // pre-push hook: may veto before the remote is contacted.
1180
        self.run_hook(
1181
            "pre-push",
1182
            &format!(
1183
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1184
                json_str(remote_name),
1185
                json_str(&bookmark),
1186
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1187
            ),
1188
        )?;
1189
        let remote = self.open_named_remote(remote_name)?;
1190
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1191
        let resp = remote.refs()?;
1192
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1193
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1194
        let policy_to_send = match (&local_policy, &resp.policy) {
1195
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1196
            (Some(l), None) => Some(l.clone()),
1197
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
1198
                return fail(format!(
1199
                    "{remote_name} has a newer policy (serial {}); fetch first",
1200
                    r.policy.serial
1201
                ));
1202
            }
1203
            _ => None,
1204
        };
1205
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1206
        if remote_has_policy && self.secret_key()?.is_none() {
1207
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1208
        }
1209
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1210
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1211
            .tag_refs()?
1212
            .into_iter()
1213
            .filter(|t| !remote_tags.contains(&t.name))
1214
            .collect();
1215
        let refs = resp.refs;
1216
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1217
        let (remote_state, remote_heads, last_serial) =
1218
            match refs.iter().find(|r| r.name == bookmark) {
1219
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1220
                None => (empty, vec![], None),
1221
            };
1222
        let new_state = self
1223
            .store
1224
            .put_state(&StateObject::new(local_heads.clone()))?;
1225
        // A push that carries a policy re-attests the bookmark even when its
1226
        // state is unchanged, so the current attestation is always by a key
1227
        // the current policy authorizes (a revoked key's attestation would
1228
        // otherwise be refused by every later fetch).
1229
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
1230
            return Ok(vec![RefResult {
1231
                name: bookmark,
1232
                ok: true,
1233
                reason: "already up to date".into(),
1234
            }]);
1235
        }
1236
        for h in &remote_heads {
1237
            if !self.store.has(h) {
1238
                return fail(format!(
1239
                    "the remote has change {} which you do not; pull first",
1240
                    h.short(12)
1241
                ));
1242
            }
1243
        }
1244
        if !force {
1245
            let closure = self.closure_in_store(&local_heads)?;
1246
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1247
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1248
            }
1249
        }
1250
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1251
        let mut bundle = self.bundle_for(&to_send)?;
1252
        let key = self.secret_key()?.map(|(k, _)| k);
1253
        if let Some(key) = key {
1254
            // Seal this author's changes that carry no valid authenticator,
1255
            // and adopt anonymous ones (zero author, spec §14.4).
1256
            let mut unsigned = Vec::new();
1257
            for h in &to_send {
1258
                let c = self.store.get_change(h)?;
1259
                if (c.author == key || c.author.is_zero())
1260
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1261
                {
1262
                    unsigned.push(*h);
1263
                }
1264
            }
1265
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
1266
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1267
                bundle.attests.push(sa);
1268
            }
1269
            bundle = self.bundle_for(&to_send)?;
1270
        }
1271
        bundle.objects.push((
1272
            ObjectType::State,
1273
            StateObject::new(local_heads.clone()).encode(),
1274
        ));
1275
        let attestation = match key {
1276
            Some(_) => Some(self.sign_attest(&Attest {
1277
                repo: self.id()?,
1278
                hlc: Hlc::now(),
1279
                body: AttestBody::Ref {
1280
                    name: bookmark.clone(),
1281
                    old_state: remote_state,
1282
                    new_state,
1283
                    serial: last_serial.unwrap_or(0) + 1,
1284
                },
1285
            })?),
1286
            None => None,
1287
        };
1288
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1289
            AttestBody::Ref { serial, .. } => Some(serial),
1290
            _ => None,
1291
        });
1292
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1293
        // Tag states must be present on the remote: bundle their changes too.
1294
        for t in &tags_to_send {
1295
            let extra = self.negotiate(&remote_heads, &t.heads)?;
1296
            let extra: Vec<ChangeHash> =
1297
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
1298
            if !extra.is_empty() {
1299
                let more = self.bundle_for(&extra)?;
1300
                bundle.changes.extend(more.changes);
1301
                bundle.attests.extend(more.attests);
1302
                bundle.objects.extend(more.objects);
1303
            }
1304
            bundle.objects.push((
1305
                ObjectType::State,
1306
                StateObject::new(t.heads.clone()).encode(),
1307
            ));
1308
        }
1309
        if let Some(l) = &policy_to_send {
1310
            let remote_serial = resp_policy_serial;
1311
            bundle.policies = self
1312
                .policy_history()?
1313
                .into_iter()
1314
                .filter(|sp| {
1315
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1316
                        && sp.policy.serial < l.policy.serial
1317
                })
1318
                .collect();
1319
        }
1320
        let results = remote.push(
1321
            bundle,
1322
            vec![RefUpdate {
1323
                name: bookmark.clone(),
1324
                old_state: remote_state,
1325
                new_state,
1326
                force,
1327
                attestation,
1328
            }],
1329
            policy_to_send,
1330
            tags_to_send,
1331
        )?;
1332
        if let (Some(serial), true) = (
1333
            sent_serial,
1334
            results.iter().any(|r| r.ok && r.name == "policy"),
1335
        ) {
1336
            self.record_policy_serial(remote_name, serial)?;
1337
        }
1338
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1339
            let mut view = op.view.clone();
1340
            view.remotes
1341
                .entry(remote_name.to_string())
1342
                .or_default()
1343
                .insert(bookmark.clone(), new_state);
1344
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1345
            if let Some(s) = serial {
1346
                self.record_serial(remote_name, &bookmark, s)?;
1347
            }
1348
        }
1349
        Ok(results)
1350
    }
1351
1352
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1353
    /// bookmark set to the remote's, working copy checked out.
1354
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1355
        Self::clone_with(url, dest, None, &[])
1356
    }
1357
1358
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1359
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1360
    /// unless a size is given, so out-of-scope binaries are never fetched).
1361
    pub fn clone_with(
1362
        url: &str,
1363
        dest: &Path,
1364
        max_blob: Option<u64>,
1365
        sparse: &[String],
1366
    ) -> Result<Repo> {
1367
        Self::clone_full(url, dest, max_blob, sparse, None)
1368
    }
1369
1370
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1371
    /// changes within `depth` steps of them; the rest is the boundary.
1372
    pub fn clone_shallow(
1373
        url: &str,
1374
        dest: &Path,
1375
        depth: u32,
1376
        max_blob: Option<u64>,
1377
        sparse: &[String],
1378
    ) -> Result<Repo> {
1379
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1380
    }
1381
1382
    fn clone_full(
1383
        url: &str,
1384
        dest: &Path,
1385
        max_blob: Option<u64>,
1386
        sparse: &[String],
1387
        depth: Option<u32>,
1388
    ) -> Result<Repo> {
1389
        let options = RemoteOptions {
1390
            token: std::env::var("OXY_TOKEN").ok(),
1391
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
1392
            repo_id: None,
1393
        };
1394
        let remote = open_remote(url, &options)?;
1395
        let id = remote.repo_id()?;
1396
        if id == crate::protocol::UNBOUND_ID {
1397
            return fail(format!(
1398
                "{url} is empty and unbound: push a repository to it first"
1399
            ));
1400
        }
1401
        let mut repo = Repo::init_with_id(dest, id)?;
1402
        repo.config.set("remote.origin.url", url)?;
1403
        if let Some(m) = max_blob {
1404
            repo.config.set("filter.max-blob", &m.to_string())?;
1405
        } else if !sparse.is_empty() {
1406
            repo.config.set("filter.max-blob", "0")?;
1407
        }
1408
        if !sparse.is_empty() {
1409
            repo.config.set("filter.paths", &sparse.join(","))?;
1410
        }
1411
        repo.save_config()?;
1412
        if let Some(depth) = depth {
1413
            repo.fetch_shallow("origin", depth)?;
1414
        } else {
1415
            repo.fetch("origin")?;
1416
        }
1417
        let (op_ref, op) = repo.head_op()?;
1418
        let bookmark = repo.config.bookmark.clone();
1419
        if let Some(state) = op
1420
            .view
1421
            .remotes
1422
            .get("origin")
1423
            .and_then(|b| b.get(&bookmark))
1424
            .copied()
1425
        {
1426
            let heads = repo.store.get_state(&state)?.heads;
1427
            let mut view = op.view.clone();
1428
            view.bookmarks.insert(bookmark, state);
1429
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1430
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
1431
        }
1432
        Ok(repo)
1433
    }
1434
}