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