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