OXYGENHUB
# d82e44097323 oxygen / crates / oxy-core / src / repo / sync.rs
54.0 KiB · Rust · last changed Proposal clients: oxy seal --proposal, oxy proposal show|land, seal-only pushes, http_get for hub APIs 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 fetch brought in.
6
#[derive(Debug, Clone, PartialEq, Eq, Default)]
7
pub struct FetchReport {
8
    /// Bookmark name, its heads, and how many changes were new.
9
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
10
    /// Tags adopted from the remote.
11
    pub new_tags: usize,
12
    /// The remote has never presented a policy, so nothing was verified
13
    /// against one (spec §14.5: warn loudly).
14
    pub unverified: bool,
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct PullReport {
19
    pub heads: Vec<ChangeHash>,
20
    pub changed: bool,
21
    pub checked_out: bool,
22
}
23
24
impl Repo {
25
    // ------------------------------------------------------------ serving (spec §16)
26
27
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
28
        self.oxy.join("attest").join(bookmark)
29
    }
30
31
    /// The latest reference attestation stored for a bookmark.
32
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
33
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
34
            Ok(h) => {
35
                let r = ObjectRef::from_hex(h.trim())
36
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
37
                Ok(Some((
38
                    r,
39
                    SignedAttest {
40
                        attest: self.store.get_attest(&r)?,
41
                        sigs: self.store.signatures(&r)?,
42
                    },
43
                )))
44
            }
45
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
46
            Err(e) => Err(e.into()),
47
        }
48
    }
49
50
    fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
51
        fs::create_dir_all(self.oxy.join("attest"))?;
52
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
53
    }
54
55
    pub fn remote_refs(&self) -> Result<RefsResponse> {
56
        let view = self.view()?;
57
        let mut out = Vec::new();
58
        for (name, state) in &view.bookmarks {
59
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
60
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
61
                AttestBody::Ref { serial, .. } => Some(serial),
62
                _ => None,
63
            });
64
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
65
            out.push(RemoteRef {
66
                name: name.clone(),
67
                state: *state,
68
                heads: self.store.get_state(state)?.heads,
69
                attestation,
70
                last_serial,
71
            });
72
        }
73
        let policy = self.current_policy()?.map(|(_, sp)| sp);
74
        let history = self
75
            .policy_history()?
76
            .into_iter()
77
            .filter(|sp| {
78
                policy
79
                    .as_ref()
80
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
81
            })
82
            .collect();
83
        Ok(RefsResponse {
84
            refs: out,
85
            policy,
86
            tags: self.tag_refs()?,
87
            history,
88
        })
89
    }
90
91
    /// Every change reachable from `heads` that is in the store.
92
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
93
        let mut seen = BTreeSet::new();
94
        let mut stack: Vec<ChangeHash> = heads.to_vec();
95
        while let Some(h) = stack.pop() {
96
            if seen.contains(&h) || !self.store.has(&h) {
97
                continue;
98
            }
99
            seen.insert(h);
100
            stack.extend(self.store.get_change(&h)?.deps);
101
        }
102
        Ok(seen)
103
    }
104
105
    /// The changes within `depth` dependency steps of `heads` (spec §17),
106
    /// nearest first; depth 1 is the heads themselves.
107
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
108
        let mut out = Vec::new();
109
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
110
        let mut layer: Vec<ChangeHash> = heads.to_vec();
111
        for _ in 0..depth.max(1) {
112
            let mut next = Vec::new();
113
            for h in layer {
114
                if !seen.insert(h) || !self.store.has(&h) {
115
                    continue;
116
                }
117
                let c = self.store.get_change(&h)?;
118
                next.extend(c.deps.iter().copied());
119
                out.push(h);
120
            }
121
            if next.is_empty() {
122
                break;
123
            }
124
            layer = next;
125
        }
126
        out.reverse();
127
        Ok(out)
128
    }
129
130
    fn shallow_path(&self) -> PathBuf {
131
        self.oxy.join("shallow")
132
    }
133
134
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
135
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
136
        fs::read_to_string(self.shallow_path())
137
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
138
            .unwrap_or_default()
139
    }
140
141
    pub fn is_shallow(&self) -> bool {
142
        !self.boundary().is_empty()
143
    }
144
145
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
146
        if boundary.is_empty() {
147
            let _ = fs::remove_file(self.shallow_path());
148
            return Ok(());
149
        }
150
        let text: String = boundary
151
            .iter()
152
            .map(|h| format!("{}\n", h.to_hex()))
153
            .collect();
154
        write_atomic(&self.shallow_path(), text.as_bytes())
155
    }
156
157
    /// Recompute the boundary from what is stored: every dependency of a
158
    /// stored change that is not itself stored.
159
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
160
        let mut boundary = self.boundary();
161
        boundary.retain(|h| !self.store.has(h));
162
        for h in imported {
163
            for d in self.store.get_change(h)?.deps {
164
                if !self.store.has(&d) {
165
                    boundary.insert(d);
166
                }
167
            }
168
        }
169
        self.write_boundary(&boundary)
170
    }
171
172
    /// Fetch `depth` more levels of history below the shallow boundary.
173
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
174
        let boundary = self.boundary();
175
        if boundary.is_empty() {
176
            return Ok(0);
177
        }
178
        let remote = self.open_named_remote(remote_name)?;
179
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
180
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
181
        let imported = self.import_bundle_shallow(&bundle, false)?;
182
        if self.config.max_blob.is_some() {
183
            self.register_missing_blobs(&imported, remote_name)?;
184
        }
185
        self.refresh_boundary(&imported)?;
186
        Ok(imported.len())
187
    }
188
189
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
190
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
191
        let have = self.closure_in_store(have)?;
192
        // In a shallow repository the walk stops at the boundary, whose
193
        // changes the remote is assumed to hold.
194
        let boundary = self.boundary();
195
        let mut out = Vec::new();
196
        let mut done: BTreeSet<ChangeHash> = have.clone();
197
        done.extend(boundary.iter().copied());
198
        // Iterative post-order DFS.
199
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
200
        while let Some((h, expanded)) = stack.pop() {
201
            if done.contains(&h) {
202
                continue;
203
            }
204
            if !self.store.has(&h) {
205
                return fail(format!("change {} is not in this repository", h.short(12)));
206
            }
207
            if expanded {
208
                done.insert(h);
209
                out.push(h);
210
                continue;
211
            }
212
            stack.push((h, true));
213
            for d in self.store.get_change(&h)?.deps {
214
                if !done.contains(&d) {
215
                    stack.push((d, false));
216
                }
217
            }
218
        }
219
        Ok(out)
220
    }
221
222
    /// Bundle changes (in the given dependency order) with their signatures,
223
    /// seals, identities, blobs, chunks.
224
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
225
        self.bundle_for_filtered(changes, None)
226
    }
227
228
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
229
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
230
        let mut out = Vec::new();
231
        for r in refs {
232
            let (ty, body) = match self.store.get(r) {
233
                Ok(x) => x,
234
                Err(StoreError::NotFound(_)) => continue,
235
                Err(e) => return Err(e.into()),
236
            };
237
            if ty == ObjectType::Blob {
238
                for c in Blob::decode(&body)?.chunks {
239
                    if let Ok((cty, cb)) = self.store.get(&c) {
240
                        out.push((cty, cb));
241
                    }
242
                }
243
            }
244
            out.push((ty, body));
245
        }
246
        Ok(out)
247
    }
248
249
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
250
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
251
    pub fn bundle_for_filtered(
252
        &self,
253
        changes: &[ChangeHash],
254
        max_blob: Option<u64>,
255
    ) -> Result<Bundle> {
256
        let mut bundle = Bundle::default();
257
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
258
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
259
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
260
            if !r.is_zero() && self.store.has(r) {
261
                objects.insert(*r);
262
            }
263
        };
264
        for h in changes {
265
            let c = self.store.get_change(h)?;
266
            let sigs = self.store.signatures(h)?;
267
            add_object(&c.author, &mut objects);
268
            for s in &sigs {
269
                add_object(&s.key, &mut objects);
270
            }
271
            for e in &c.edits {
272
                if let Edit::Replace { old, new, .. } = e {
273
                    for b in [old, new].into_iter().flatten() {
274
                        if self.store.has(b) {
275
                            if let Ok(blob) =
276
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
277
                            {
278
                                if max_blob.is_some_and(|m| blob.length > m) {
279
                                    continue;
280
                                }
281
                                objects.insert(*b);
282
                                objects.extend(blob.chunks.iter().copied());
283
                            }
284
                        }
285
                    }
286
                }
287
            }
288
            for s in self.store.seals_for(h)? {
289
                seals.insert(s);
290
            }
291
            bundle.changes.push((c, sigs));
292
        }
293
        for r in seals {
294
            let attest = self.store.get_attest(&r)?;
295
            let sigs = self.store.signatures(&r)?;
296
            for s in &sigs {
297
                add_object(&s.key, &mut objects);
298
            }
299
            bundle.attests.push(SignedAttest { attest, sigs });
300
        }
301
        for r in objects {
302
            let (ty, body) = self.store.get(&r)?;
303
            bundle.objects.push((ty, body));
304
        }
305
        Ok(bundle)
306
    }
307
308
    /// Store a bundle's contents. With `strict`, every change must
309
    /// authenticate (signature or seal by its author or a delegate).
310
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
311
        self.import_bundle_inner(bundle, strict, false)
312
    }
313
314
    /// Like `import_bundle`, accepting changes whose dependencies are absent
315
    /// (they join the shallow boundary).
316
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
317
        self.import_bundle_inner(bundle, strict, true)
318
    }
319
320
    fn import_bundle_inner(
321
        &self,
322
        bundle: &Bundle,
323
        strict: bool,
324
        shallow: bool,
325
    ) -> Result<Vec<ChangeHash>> {
326
        let batch = self.store.begin_batch()?;
327
        let result = self.import_bundle_batched(bundle, strict, shallow);
328
        batch.finish()?;
329
        result
330
    }
331
332
    fn import_bundle_batched(
333
        &self,
334
        bundle: &Bundle,
335
        strict: bool,
336
        shallow: bool,
337
    ) -> Result<Vec<ChangeHash>> {
338
        for (ty, body) in &bundle.objects {
339
            match ty {
340
                ObjectType::Chunk
341
                | ObjectType::Blob
342
                | ObjectType::Identity
343
                | ObjectType::State
344
                | ObjectType::Checkpoint => {
345
                    self.store.put(*ty, body)?;
346
                }
347
                other => return fail(format!("bundle may not carry {} objects", other.name())),
348
            }
349
        }
350
        for sa in &bundle.attests {
351
            let r = self.store.put_attest(&sa.attest)?;
352
            for sig in &sa.sigs {
353
                self.store.put_signature(&r, sig)?;
354
            }
355
            if let AttestBody::Seal { hashes } = &sa.attest.body {
356
                for h in hashes {
357
                    self.store.index_seal(h, &r)?;
358
                }
359
            }
360
        }
361
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
362
        let boundary = self.boundary();
363
        let mut imported = Vec::new();
364
        for (c, sigs) in &bundle.changes {
365
            let h = c.hash();
366
            for d in &c.deps {
367
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
368
                {
369
                    return fail(format!(
370
                        "change {} depends on {}, which is neither stored nor in the bundle",
371
                        h.short(12),
372
                        d.short(12)
373
                    ));
374
                }
375
            }
376
            self.store.put_change(c)?;
377
            for sig in sigs {
378
                self.store.put_signature(&h, sig)?;
379
            }
380
            imported.push(h);
381
        }
382
        if strict {
383
            for h in &imported {
384
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
385
                    return fail(format!(
386
                        "change {} is not authenticated by its author",
387
                        h.short(12)
388
                    ));
389
                }
390
            }
391
        }
392
        Ok(imported)
393
    }
394
395
    /// Verify a reference attestation against an update it claims to describe.
396
    /// `allow_equal` lets a client re-read the attestation it already has; a
397
    /// server receiving a push requires a strictly greater serial.
398
    fn check_ref_attest(
399
        &self,
400
        sa: &SignedAttest,
401
        name: &str,
402
        old_state: &ObjectRef,
403
        new_state: &ObjectRef,
404
        last_serial: Option<u64>,
405
        allow_equal: bool,
406
    ) -> std::result::Result<u64, String> {
407
        let AttestBody::Ref {
408
            name: n,
409
            old_state: o,
410
            new_state: nw,
411
            serial,
412
        } = &sa.attest.body
413
        else {
414
            return Err("attestation is not a ref attestation".into());
415
        };
416
        if n != name || o != old_state || nw != new_state {
417
            return Err("attestation does not describe this update".into());
418
        }
419
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
420
            return Err("attestation is for a different repository".into());
421
        }
422
        if let Some(last) = last_serial {
423
            if *serial < last || (*serial == last && !allow_equal) {
424
                return Err(format!(
425
                    "attestation serial {serial} is not greater than the last seen {last}"
426
                ));
427
            }
428
        }
429
        let r = sa.attest.hash();
430
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
431
        let id = self
432
            .store
433
            .get_identity(&sig.key)
434
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
435
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
436
        Ok(*serial)
437
    }
438
439
    /// Accept a push (spec §16.4). Without a trust policy every repository
440
    /// is unverified, so unsigned changes and unattested updates are accepted;
441
    /// attestations that are present must still be valid. With a policy,
442
    /// every change and update is checked against it. A newer policy in the
443
    /// push is applied first when it is signed by the current roots.
444
    pub fn receive_push(
445
        &self,
446
        bundle: Bundle,
447
        updates: Vec<RefUpdate>,
448
        policy: Option<SignedPolicy>,
449
        tags: Vec<crate::protocol::TagRef>,
450
    ) -> Result<Vec<RefResult>> {
451
        let mut results = Vec::new();
452
        if let Some(sp) = policy {
453
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
454
                Ok(()) => {
455
                    results.push(RefResult {
456
                        name: "policy".into(),
457
                        ok: true,
458
                        reason: format!("serial {}", sp.policy.serial),
459
                    });
460
                }
461
                Err(e) => {
462
                    results.push(RefResult {
463
                        name: "policy".into(),
464
                        ok: false,
465
                        reason: e,
466
                    });
467
                    for u in updates {
468
                        results.push(RefResult {
469
                            name: u.name,
470
                            ok: false,
471
                            reason: "policy update was rejected".into(),
472
                        });
473
                    }
474
                    return Ok(results);
475
                }
476
            }
477
        }
478
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
479
        if let Err(e) = self.import_bundle(&bundle, policy.is_some()) {
480
            for u in updates {
481
                results.push(RefResult {
482
                    name: u.name,
483
                    ok: false,
484
                    reason: e.to_string(),
485
                });
486
            }
487
            return Ok(results);
488
        }
489
        let (op_ref, op) = self.head_op()?;
490
        let mut view = op.view.clone();
491
        let mut names = Vec::new();
492
        for u in updates {
493
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
494
            let (ok, reason) = match outcome {
495
                Ok(()) => (true, String::new()),
496
                Err(e) => (false, e),
497
            };
498
            if ok {
499
                names.push(u.name.clone());
500
            }
501
            results.push(RefResult {
502
                name: u.name,
503
                ok,
504
                reason,
505
            });
506
        }
507
        for t in &tags {
508
            let name = format!("tags/{}", t.name);
509
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
510
                Ok(()) => {
511
                    names.push(name.clone());
512
                    results.push(RefResult {
513
                        name,
514
                        ok: true,
515
                        reason: String::new(),
516
                    });
517
                }
518
                Err(e) => results.push(RefResult {
519
                    name,
520
                    ok: false,
521
                    reason: e,
522
                }),
523
            }
524
        }
525
        if !names.is_empty() {
526
            self.record_op(
527
                &[op_ref],
528
                &format!("push received: {}", names.join(" ")),
529
                view,
530
            )?;
531
        }
532
        Ok(results)
533
    }
534
535
    fn apply_update(
536
        &self,
537
        view: &mut View,
538
        u: &RefUpdate,
539
        policy: Option<&crate::policy::Policy>,
540
    ) -> std::result::Result<(), String> {
541
        if u.name == "policy" {
542
            return Err(
543
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
544
            );
545
        }
546
        let empty = self
547
            .store
548
            .put_state(&StateObject::new(vec![]))
549
            .map_err(|e| e.to_string())?;
550
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
551
        if current != u.old_state {
552
            return Err("stale: the remote bookmark has moved; pull first".into());
553
        }
554
        let new_state = self
555
            .store
556
            .get_state(&u.new_state)
557
            .map_err(|_| "new state object is missing".to_string())?;
558
        for h in &new_state.heads {
559
            if !self.store.has(h) {
560
                return Err(format!("head {} is missing", h.short(12)));
561
            }
562
        }
563
        if !u.force {
564
            let old_heads = self
565
                .store
566
                .get_state(&current)
567
                .map_err(|e| e.to_string())?
568
                .heads;
569
            let closure = self
570
                .closure_in_store(&new_state.heads)
571
                .map_err(|e| e.to_string())?;
572
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
573
                return Err(format!(
574
                    "not a fast-forward: current head {} would be dropped (use --force)",
575
                    h.short(12)
576
                ));
577
            }
578
        }
579
        if let Some(p) = policy {
580
            let Some(sa) = &u.attestation else {
581
                return Err(format!(
582
                    "{:?} requires a signed reference attestation under this repository's policy",
583
                    u.name
584
                ));
585
            };
586
            let signer = sa
587
                .sigs
588
                .first()
589
                .map(|s| s.key)
590
                .ok_or("attestation carries no signature")?;
591
            if !p.authorizes(&signer, &u.name) {
592
                return Err(format!(
593
                    "key {} may not update {:?} under this repository's policy",
594
                    signer.short(12),
595
                    u.name
596
                ));
597
            }
598
            let old_heads = self
599
                .store
600
                .get_state(&current)
601
                .map_err(|e| e.to_string())?
602
                .heads;
603
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
604
        }
605
        if let Some(sa) = &u.attestation {
606
            let last = self
607
                .latest_ref_attest(&u.name)
608
                .map_err(|e| e.to_string())?
609
                .and_then(|(_, a)| match a.attest.body {
610
                    AttestBody::Ref { serial, .. } => Some(serial),
611
                    _ => None,
612
                });
613
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
614
            let r = self
615
                .store
616
                .put_attest(&sa.attest)
617
                .map_err(|e| e.to_string())?;
618
            for sig in &sa.sigs {
619
                self.store
620
                    .put_signature(&r, sig)
621
                    .map_err(|e| e.to_string())?;
622
            }
623
            self.set_ref_attest(&u.name, &r)
624
                .map_err(|e| e.to_string())?;
625
        }
626
        view.bookmarks.insert(u.name.clone(), u.new_state);
627
        Ok(())
628
    }
629
630
    // ------------------------------------------------------------ client side
631
632
    fn remote_url(&self, name: &str) -> Result<String> {
633
        self.config.remotes.get(name).cloned().ok_or_else(|| {
634
            RepoError::Msg(format!(
635
                "no remote named {name:?}; add one with `oxy remote add`"
636
            ))
637
        })
638
    }
639
640
    /// Credentials and trust for a remote: `remote.<name>.token` (else
641
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
642
    /// Refuse a remote that is another repository. An **unbound** remote
643
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
644
    /// for pushes, which bind it to this repository's id (spec §16.1).
645
    fn check_remote_id(
646
        &self,
647
        remote: &dyn crate::protocol::Remote,
648
        remote_name: &str,
649
        allow_unbound: bool,
650
    ) -> Result<()> {
651
        let theirs = remote.repo_id()?;
652
        if theirs == self.id()? {
653
            return Ok(());
654
        }
655
        if theirs == crate::protocol::UNBOUND_ID {
656
            if allow_unbound {
657
                return Ok(());
658
            }
659
            return fail(format!(
660
                "remote {remote_name:?} is empty and unbound: push to it first"
661
            ));
662
        }
663
        fail(format!(
664
            "remote {remote_name:?} is a different repository (repository IDs differ)"
665
        ))
666
    }
667
668
    fn remote_options(&self, name: &str) -> RemoteOptions {
669
        RemoteOptions {
670
            repo_id: self.id().ok(),
671
            token: self
672
                .config
673
                .remote_tokens
674
                .get(name)
675
                .cloned()
676
                .or_else(|| std::env::var("OXY_TOKEN").ok()),
677
            ca: self
678
                .config
679
                .remote_cas
680
                .get(name)
681
                .map(PathBuf::from)
682
                .or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
683
        }
684
    }
685
686
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
687
    /// no changes and no reference updates, which the receiver stores.
688
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
689
        let remote = self.open_named_remote(remote_name)?;
690
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
691
        let mut bundle = Bundle::default();
692
        for r in seals {
693
            let attest = self.store.get_attest(r)?;
694
            let sigs = self.store.signatures(r)?;
695
            bundle.attests.push(crate::protocol::SignedAttest { attest, sigs });
696
        }
697
        let results = remote.push(bundle, vec![], None, vec![])?;
698
        if let Some(r) = results.iter().find(|r| !r.ok) {
699
            return fail(format!("{}: {}", r.name, r.reason));
700
        }
701
        Ok(())
702
    }
703
704
    /// The remote whose URL starts with `base` (a hub), if configured.
705
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
706
        let base = base.trim_end_matches('/');
707
        self.config.remotes.iter().find(|(_, url)| url.trim_end_matches('/') == base).map(|(name, _)| name.clone())
708
    }
709
710
    /// Open a remote by name or, failing that, by URL with the default
711
    /// credentials (`OXY_TOKEN`, `OXY_CA`).
712
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
713
        if let Some(name) = self.remote_for_url(url) {
714
            return Ok((name.clone(), self.open_named_remote(&name)?));
715
        }
716
        let options = RemoteOptions {
717
            token: std::env::var("OXY_TOKEN").ok(),
718
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
719
            repo_id: self.id().ok(),
720
        };
721
        Ok((url.to_string(), open_remote(url, &options)?))
722
    }
723
724
    /// Credentials for a URL: those of the configured remote with that
725
    /// URL, else the environment's.
726
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
727
        match self.remote_for_url(url) {
728
            Some(name) => self.remote_options(&name),
729
            None => RemoteOptions {
730
                token: std::env::var("OXY_TOKEN").ok(),
731
                ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
732
                repo_id: self.id().ok(),
733
            },
734
        }
735
    }
736
737
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
738
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
739
    }
740
741
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
742
        self.oxy
743
            .join("remotes")
744
            .join(remote)
745
            .join(format!("{bookmark}.serial"))
746
    }
747
748
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
749
        fs::read_to_string(self.serial_path(remote, bookmark))
750
            .ok()
751
            .and_then(|s| s.trim().parse().ok())
752
    }
753
754
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
755
        let p = self.serial_path(remote, bookmark);
756
        fs::create_dir_all(p.parent().unwrap())?;
757
        write_atomic(&p, serial.to_string().as_bytes())
758
    }
759
760
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
761
        self.oxy.join("remotes").join(remote).join("policy.serial")
762
    }
763
764
    /// The highest policy serial `remote` has ever presented.
765
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
766
        fs::read_to_string(self.policy_serial_path(remote))
767
            .ok()
768
            .and_then(|s| s.trim().parse().ok())
769
    }
770
771
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
772
        let p = self.policy_serial_path(remote);
773
        fs::create_dir_all(p.parent().unwrap())?;
774
        write_atomic(&p, serial.to_string().as_bytes())
775
    }
776
777
    fn lazy_dir(&self) -> PathBuf {
778
        self.oxy.join("lazy")
779
    }
780
781
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
782
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
783
        fs::create_dir_all(self.lazy_dir())?;
784
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
785
    }
786
787
    /// Which remote promised an absent blob, if any.
788
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
789
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
790
            .ok()
791
            .map(|s| s.trim().to_string())
792
    }
793
794
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
795
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
796
        let Some(remote_name) = self.lazy_remote(blob) else {
797
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
798
        };
799
        let remote = self.open_named_remote(&remote_name)?;
800
        let objects = remote.objects(&[*blob])?;
801
        for (ty, body) in objects {
802
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
803
                self.store.put(ty, &body)?;
804
            }
805
        }
806
        if !self.store.has(blob) {
807
            return fail(format!(
808
                "{remote_name} did not send blob {}",
809
                blob.short(12)
810
            ));
811
        }
812
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
813
        Ok(())
814
    }
815
816
    /// After importing from `remote`, record every blob the changes reference
817
    /// that the store lacks as lazily available from that remote.
818
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
819
        let mut n = 0;
820
        for h in changes {
821
            let c = self.store.get_change(h)?;
822
            for e in &c.edits {
823
                if let Edit::Replace { old, new, .. } = e {
824
                    for b in [old, new].into_iter().flatten() {
825
                        if !self.store.has(b) {
826
                            self.register_lazy(b, remote)?;
827
                            n += 1;
828
                        }
829
                    }
830
                }
831
            }
832
        }
833
        Ok(n)
834
    }
835
836
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
837
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
838
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
839
        for st in view
840
            .bookmarks
841
            .values()
842
            .chain(view.remotes.values().flat_map(|b| b.values()))
843
        {
844
            if let Ok(s) = self.store.get_state(st) {
845
                have.extend(s.heads);
846
            }
847
        }
848
        have.extend(view.workspaces.values().copied());
849
        Ok(have.into_iter().collect())
850
    }
851
852
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
853
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
854
        let remote = self.open_named_remote(remote_name)?;
855
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
856
        let resp = remote.refs()?;
857
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
858
        // and signed by roots we trust, or on first contact. A remote that
859
        // once presented a policy may never present none or an older one:
860
        // that is a downgrade. A remote that never presented one is
861
        // unverified, and this fetch is checked only as far as possible.
862
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
863
        let seen = self.remote_policy_serial(remote_name);
864
        let mut unverified = false;
865
        match &resp.policy {
866
            Some(sp) => {
867
                if seen.is_some_and(|s| sp.policy.serial < s) {
868
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
869
                }
870
                match &local_policy {
871
                    Some(l) if sp.policy.serial < l.serial => {}
872
                    Some(l) if sp.policy.serial == l.serial => {
873
                        if sp.policy.hash() != l.hash() {
874
                            return fail(format!(
875
                                "{remote_name} presents a different policy with the same serial {}",
876
                                l.serial
877
                            ));
878
                        }
879
                    }
880
                    _ => {
881
                        self.adopt_policy_chain(
882
                            &resp.history,
883
                            sp,
884
                            &format!("oxy fetch {remote_name}"),
885
                        )
886
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
887
                    }
888
                }
889
                self.record_policy_serial(remote_name, sp.policy.serial)?;
890
            }
891
            None => {
892
                if seen.is_some() {
893
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
894
                }
895
                unverified = true;
896
            }
897
        }
898
        let policy = if unverified {
899
            None
900
        } else {
901
            self.current_policy()?.map(|(_, sp)| sp.policy)
902
        };
903
        let (op_ref, op) = self.head_op()?;
904
        let mut view = op.view.clone();
905
        let have = self.known_heads(&view)?;
906
        let mut report = Vec::new();
907
        let max_blob = self.config.max_blob;
908
        for r in resp.refs {
909
            let needed = remote.negotiate(&have, &r.heads)?;
910
            let bundle = remote.fetch(&needed, max_blob)?;
911
            // Changes are not individually re-verified here: the bookmark's
912
            // attestation (checked below) binds its whole state, and the
913
            // receiver of the push verified the added changes at that time.
914
            let imported = self.import_bundle(&bundle, false)?;
915
            if max_blob.is_some() {
916
                self.register_missing_blobs(&imported, remote_name)?;
917
            }
918
            for h in &r.heads {
919
                if !self.store.has(h) {
920
                    return fail(format!("remote did not send head {}", h.short(12)));
921
                }
922
            }
923
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
924
            if state != r.state {
925
                return fail(format!(
926
                    "remote state {} does not match its heads",
927
                    r.state.short(12)
928
                ));
929
            }
930
            if let Some(p) = &policy {
931
                let Some(sa) = &r.attestation else {
932
                    return fail(format!(
933
                        "{remote_name}/{} has no attestation, which its policy requires",
934
                        r.name
935
                    ));
936
                };
937
                let signer = sa
938
                    .sigs
939
                    .first()
940
                    .map(|s| s.key)
941
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
942
                if !p.authorizes(&signer, &r.name) {
943
                    return fail(format!(
944
                        "{remote_name}/{}: attested by {}, which the policy does not authorize",
945
                        r.name,
946
                        signer.short(12)
947
                    ));
948
                }
949
            }
950
            if let Some(sa) = &r.attestation {
951
                let AttestBody::Ref {
952
                    old_state,
953
                    new_state,
954
                    ..
955
                } = &sa.attest.body
956
                else {
957
                    return fail("remote sent a non-ref attestation for a bookmark");
958
                };
959
                let (old_state, new_state) = (*old_state, *new_state);
960
                let serial = self
961
                    .check_ref_attest(
962
                        sa,
963
                        &r.name,
964
                        &old_state,
965
                        &new_state,
966
                        self.last_seen_serial(remote_name, &r.name),
967
                        true,
968
                    )
969
                    .map_err(|e| {
970
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
971
                    })?;
972
                if new_state != r.state {
973
                    return fail(format!(
974
                        "attestation for {}/{} does not cover its current state",
975
                        remote_name, r.name
976
                    ));
977
                }
978
                let ar = self.store.put_attest(&sa.attest)?;
979
                for sig in &sa.sigs {
980
                    self.store.put_signature(&ar, sig)?;
981
                }
982
                self.record_serial(remote_name, &r.name, serial)?;
983
            }
984
            view.remotes
985
                .entry(remote_name.to_string())
986
                .or_default()
987
                .insert(r.name.clone(), state);
988
            report.push((r.name, r.heads, imported.len()));
989
        }
990
        let mut new_tags = 0;
991
        for t in &resp.tags {
992
            if view.tags.contains_key(&t.name) {
993
                continue;
994
            }
995
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
996
            let missing: Vec<ChangeHash> = t
997
                .heads
998
                .iter()
999
                .filter(|h| !self.store.has(h))
1000
                .copied()
1001
                .collect();
1002
            if !missing.is_empty() {
1003
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1004
                let bundle = remote.fetch(&needed, max_blob)?;
1005
                self.import_bundle(&bundle, false)?;
1006
            }
1007
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1008
            self.adopt_tag(&mut view, t, policy.as_ref())
1009
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
1010
            new_tags += 1;
1011
        }
1012
        if view != op.view {
1013
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1014
        }
1015
        let _ = self.run_hook(
1016
            "post-fetch",
1017
            &format!(
1018
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1019
                json_str(remote_name),
1020
                json_array(report.iter().map(|(n, heads, _)| format!(
1021
                    "{{\"name\":{},\"heads\":{}}}",
1022
                    json_str(n),
1023
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1024
                )))
1025
            ),
1026
        );
1027
        Ok(FetchReport {
1028
            refs: report,
1029
            unverified,
1030
            new_tags,
1031
        })
1032
    }
1033
1034
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1035
    /// the changes within `depth` steps of its heads, and the boundary below.
1036
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1037
        let remote = self.open_named_remote(remote_name)?;
1038
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1039
        let resp = remote.refs()?;
1040
        let bookmark = self.config.bookmark.clone();
1041
        if let Some(sp) = &resp.policy {
1042
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1043
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1044
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1045
        }
1046
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1047
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1048
        };
1049
        if r.heads.is_empty() {
1050
            return Ok(0);
1051
        }
1052
        // Base: the remote's checkpoint of exactly these heads.
1053
        let cp_bundle = remote.checkpoint(&r.heads)?;
1054
        let mut cp_ref = None;
1055
        for (ty, body) in &cp_bundle.objects {
1056
            let put = self.store.put(*ty, body)?;
1057
            if *ty == ObjectType::Checkpoint {
1058
                cp_ref = Some(put);
1059
            }
1060
        }
1061
        let Some(cp_ref) = cp_ref else {
1062
            return fail(format!("{remote_name} sent no checkpoint"));
1063
        };
1064
        self.install_checkpoint(&bookmark, &cp_ref)?;
1065
        // History window.
1066
        let wanted = remote.shallow(&r.heads, depth)?;
1067
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1068
        let imported = self.import_bundle_shallow(&bundle, false)?;
1069
        if self.config.max_blob.is_some() {
1070
            self.register_missing_blobs(&imported, remote_name)?;
1071
        }
1072
        self.refresh_boundary(&imported)?;
1073
        if let Some(sa) = &r.attestation {
1074
            let ar = self.store.put_attest(&sa.attest)?;
1075
            for sig in &sa.sigs {
1076
                self.store.put_signature(&ar, sig)?;
1077
            }
1078
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1079
                self.record_serial(remote_name, &r.name, serial)?;
1080
            }
1081
        }
1082
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1083
        let (op_ref, op) = self.head_op()?;
1084
        let mut view = op.view.clone();
1085
        view.remotes
1086
            .entry(remote_name.to_string())
1087
            .or_default()
1088
            .insert(r.name.clone(), state);
1089
        self.record_op(
1090
            &[op_ref],
1091
            &format!("oxy fetch {remote_name} --depth {depth}"),
1092
            view,
1093
        )?;
1094
        Ok(imported.len())
1095
    }
1096
1097
    /// Fetch, then take the union of the local bookmark's state with the
1098
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1099
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1100
        self.fetch(remote_name)?;
1101
        let (op_ref, op) = self.head_op()?;
1102
        let bookmark = self.config.bookmark.clone();
1103
        let local = self.heads_of(&op.view, &bookmark)?;
1104
        let Some(remote_state) = op
1105
            .view
1106
            .remotes
1107
            .get(remote_name)
1108
            .and_then(|b| b.get(&bookmark))
1109
            .copied()
1110
        else {
1111
            return Ok(PullReport {
1112
                heads: local,
1113
                changed: false,
1114
                checked_out: false,
1115
            });
1116
        };
1117
        let remote_heads = self.store.get_state(&remote_state)?.heads;
1118
        let mut all = local.clone();
1119
        all.extend(remote_heads);
1120
        let st = self.load_state(&all)?;
1121
        let mut heads = st.maximal(&all);
1122
        heads.sort();
1123
        let mut sorted_local = local.clone();
1124
        sorted_local.sort();
1125
        if heads == sorted_local {
1126
            return Ok(PullReport {
1127
                heads,
1128
                changed: false,
1129
                checked_out: false,
1130
            });
1131
        }
1132
        let mut view = op.view.clone();
1133
        view.bookmarks.insert(
1134
            bookmark.clone(),
1135
            self.store.put_state(&StateObject::new(heads.clone()))?,
1136
        );
1137
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1138
        // Follow along if the working copy was clean and on the old heads.
1139
        let snap = self.snapshot("oxy pull")?;
1140
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1141
        let mut base = snap.base.maximal(&snap.wc.deps);
1142
        base.sort();
1143
        let mut checked_out = false;
1144
        if clean && base == sorted_local {
1145
            self.checkout(&heads, false, "oxy pull (checkout)")?;
1146
            checked_out = true;
1147
        }
1148
        Ok(PullReport {
1149
            heads,
1150
            changed: true,
1151
            checked_out,
1152
        })
1153
    }
1154
1155
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1156
    /// changes and attesting the reference when a key is available.
1157
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1158
        let bookmark = self.config.bookmark.clone();
1159
        self.push_bookmark(remote_name, &bookmark, force)
1160
    }
1161
1162
    /// `push` for a named bookmark (`oxy push -b NAME`).
1163
    pub fn push_bookmark(
1164
        &self,
1165
        remote_name: &str,
1166
        bookmark: &str,
1167
        force: bool,
1168
    ) -> Result<Vec<RefResult>> {
1169
        let (op_ref, op) = self.head_op()?;
1170
        if !op.view.bookmarks.contains_key(bookmark) {
1171
            return fail(format!("no bookmark {bookmark}"));
1172
        }
1173
        let bookmark = bookmark.to_string();
1174
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1175
        // pre-push hook: may veto before the remote is contacted.
1176
        self.run_hook(
1177
            "pre-push",
1178
            &format!(
1179
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1180
                json_str(remote_name),
1181
                json_str(&bookmark),
1182
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1183
            ),
1184
        )?;
1185
        let remote = self.open_named_remote(remote_name)?;
1186
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1187
        let resp = remote.refs()?;
1188
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1189
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1190
        let policy_to_send = match (&local_policy, &resp.policy) {
1191
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1192
            (Some(l), None) => Some(l.clone()),
1193
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
1194
                return fail(format!(
1195
                    "{remote_name} has a newer policy (serial {}); fetch first",
1196
                    r.policy.serial
1197
                ));
1198
            }
1199
            _ => None,
1200
        };
1201
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1202
        if remote_has_policy && self.secret_key()?.is_none() {
1203
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1204
        }
1205
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1206
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1207
            .tag_refs()?
1208
            .into_iter()
1209
            .filter(|t| !remote_tags.contains(&t.name))
1210
            .collect();
1211
        let refs = resp.refs;
1212
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1213
        let (remote_state, remote_heads, last_serial) =
1214
            match refs.iter().find(|r| r.name == bookmark) {
1215
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1216
                None => (empty, vec![], None),
1217
            };
1218
        let new_state = self
1219
            .store
1220
            .put_state(&StateObject::new(local_heads.clone()))?;
1221
        // A push that carries a policy re-attests the bookmark even when its
1222
        // state is unchanged, so the current attestation is always by a key
1223
        // the current policy authorizes (a revoked key's attestation would
1224
        // otherwise be refused by every later fetch).
1225
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
1226
            return Ok(vec![RefResult {
1227
                name: bookmark,
1228
                ok: true,
1229
                reason: "already up to date".into(),
1230
            }]);
1231
        }
1232
        for h in &remote_heads {
1233
            if !self.store.has(h) {
1234
                return fail(format!(
1235
                    "the remote has change {} which you do not; pull first",
1236
                    h.short(12)
1237
                ));
1238
            }
1239
        }
1240
        if !force {
1241
            let closure = self.closure_in_store(&local_heads)?;
1242
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1243
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1244
            }
1245
        }
1246
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1247
        let mut bundle = self.bundle_for(&to_send)?;
1248
        let key = self.secret_key()?.map(|(k, _)| k);
1249
        if let Some(key) = key {
1250
            // Seal this author's changes that carry no valid authenticator,
1251
            // and adopt anonymous ones (zero author, spec §14.4).
1252
            let mut unsigned = Vec::new();
1253
            for h in &to_send {
1254
                let c = self.store.get_change(h)?;
1255
                if (c.author == key || c.author.is_zero())
1256
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1257
                {
1258
                    unsigned.push(*h);
1259
                }
1260
            }
1261
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
1262
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1263
                bundle.attests.push(sa);
1264
            }
1265
            bundle = self.bundle_for(&to_send)?;
1266
        }
1267
        bundle.objects.push((
1268
            ObjectType::State,
1269
            StateObject::new(local_heads.clone()).encode(),
1270
        ));
1271
        let attestation = match key {
1272
            Some(_) => Some(self.sign_attest(&Attest {
1273
                repo: self.id()?,
1274
                hlc: Hlc::now(),
1275
                body: AttestBody::Ref {
1276
                    name: bookmark.clone(),
1277
                    old_state: remote_state,
1278
                    new_state,
1279
                    serial: last_serial.unwrap_or(0) + 1,
1280
                },
1281
            })?),
1282
            None => None,
1283
        };
1284
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1285
            AttestBody::Ref { serial, .. } => Some(serial),
1286
            _ => None,
1287
        });
1288
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1289
        // Tag states must be present on the remote: bundle their changes too.
1290
        for t in &tags_to_send {
1291
            let extra = self.negotiate(&remote_heads, &t.heads)?;
1292
            let extra: Vec<ChangeHash> =
1293
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
1294
            if !extra.is_empty() {
1295
                let more = self.bundle_for(&extra)?;
1296
                bundle.changes.extend(more.changes);
1297
                bundle.attests.extend(more.attests);
1298
                bundle.objects.extend(more.objects);
1299
            }
1300
            bundle.objects.push((
1301
                ObjectType::State,
1302
                StateObject::new(t.heads.clone()).encode(),
1303
            ));
1304
        }
1305
        if let Some(l) = &policy_to_send {
1306
            let remote_serial = resp_policy_serial;
1307
            bundle.policies = self
1308
                .policy_history()?
1309
                .into_iter()
1310
                .filter(|sp| {
1311
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1312
                        && sp.policy.serial < l.policy.serial
1313
                })
1314
                .collect();
1315
        }
1316
        let results = remote.push(
1317
            bundle,
1318
            vec![RefUpdate {
1319
                name: bookmark.clone(),
1320
                old_state: remote_state,
1321
                new_state,
1322
                force,
1323
                attestation,
1324
            }],
1325
            policy_to_send,
1326
            tags_to_send,
1327
        )?;
1328
        if let (Some(serial), true) = (
1329
            sent_serial,
1330
            results.iter().any(|r| r.ok && r.name == "policy"),
1331
        ) {
1332
            self.record_policy_serial(remote_name, serial)?;
1333
        }
1334
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1335
            let mut view = op.view.clone();
1336
            view.remotes
1337
                .entry(remote_name.to_string())
1338
                .or_default()
1339
                .insert(bookmark.clone(), new_state);
1340
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1341
            if let Some(s) = serial {
1342
                self.record_serial(remote_name, &bookmark, s)?;
1343
            }
1344
        }
1345
        Ok(results)
1346
    }
1347
1348
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1349
    /// bookmark set to the remote's, working copy checked out.
1350
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1351
        Self::clone_with(url, dest, None, &[])
1352
    }
1353
1354
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1355
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1356
    /// unless a size is given, so out-of-scope binaries are never fetched).
1357
    pub fn clone_with(
1358
        url: &str,
1359
        dest: &Path,
1360
        max_blob: Option<u64>,
1361
        sparse: &[String],
1362
    ) -> Result<Repo> {
1363
        Self::clone_full(url, dest, max_blob, sparse, None)
1364
    }
1365
1366
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1367
    /// changes within `depth` steps of them; the rest is the boundary.
1368
    pub fn clone_shallow(
1369
        url: &str,
1370
        dest: &Path,
1371
        depth: u32,
1372
        max_blob: Option<u64>,
1373
        sparse: &[String],
1374
    ) -> Result<Repo> {
1375
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1376
    }
1377
1378
    fn clone_full(
1379
        url: &str,
1380
        dest: &Path,
1381
        max_blob: Option<u64>,
1382
        sparse: &[String],
1383
        depth: Option<u32>,
1384
    ) -> Result<Repo> {
1385
        let options = RemoteOptions {
1386
            token: std::env::var("OXY_TOKEN").ok(),
1387
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
1388
            repo_id: None,
1389
        };
1390
        let remote = open_remote(url, &options)?;
1391
        let id = remote.repo_id()?;
1392
        if id == crate::protocol::UNBOUND_ID {
1393
            return fail(format!(
1394
                "{url} is empty and unbound: push a repository to it first"
1395
            ));
1396
        }
1397
        let mut repo = Repo::init_with_id(dest, id)?;
1398
        repo.config.set("remote.origin.url", url)?;
1399
        if let Some(m) = max_blob {
1400
            repo.config.set("filter.max-blob", &m.to_string())?;
1401
        } else if !sparse.is_empty() {
1402
            repo.config.set("filter.max-blob", "0")?;
1403
        }
1404
        if !sparse.is_empty() {
1405
            repo.config.set("filter.paths", &sparse.join(","))?;
1406
        }
1407
        repo.save_config()?;
1408
        if let Some(depth) = depth {
1409
            repo.fetch_shallow("origin", depth)?;
1410
        } else {
1411
            repo.fetch("origin")?;
1412
        }
1413
        let (op_ref, op) = repo.head_op()?;
1414
        let bookmark = repo.config.bookmark.clone();
1415
        if let Some(state) = op
1416
            .view
1417
            .remotes
1418
            .get("origin")
1419
            .and_then(|b| b.get(&bookmark))
1420
            .copied()
1421
        {
1422
            let heads = repo.store.get_state(&state)?.heads;
1423
            let mut view = op.view.clone();
1424
            view.bookmarks.insert(bookmark, state);
1425
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1426
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
1427
        }
1428
        Ok(repo)
1429
    }
1430
}