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