OXYGENHUB
# b2ef93bb2366 oxygen / crates / oxy-core / src / repo / sync.rs
44.2 KiB · Rust · last changed A push reports a tag it adds as an update 1 month ago source blame history raw
1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a fetch brought in.
6
#[derive(Debug, Clone, PartialEq, Eq, Default)]
7
pub struct FetchReport {
8
    /// Bookmark name, its heads, and how many changes were new.
9
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
10
    /// Tags adopted from the remote.
11
    pub new_tags: usize,
12
    /// The remote has never presented a policy, so nothing was verified
13
    /// against one (spec §14.5: warn loudly).
14
    pub unverified: bool,
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct PullReport {
19
    pub heads: Vec<ChangeHash>,
20
    pub changed: bool,
21
    pub checked_out: bool,
22
}
23
24
impl Repo {
25
    // ------------------------------------------------------------ serving (spec §16)
26
27
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
28
        self.oxy.join("attest").join(bookmark)
29
    }
30
31
    /// The latest reference attestation stored for a bookmark.
32
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
33
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
34
            Ok(h) => {
35
                let r = ObjectRef::from_hex(h.trim()).ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
36
                Ok(Some((r, SignedAttest { attest: self.store.get_attest(&r)?, sigs: self.store.signatures(&r)? })))
37
            }
38
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
39
            Err(e) => Err(e.into()),
40
        }
41
    }
42
43
    fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
44
        fs::create_dir_all(self.oxy.join("attest"))?;
45
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
46
    }
47
48
    pub fn remote_refs(&self) -> Result<RefsResponse> {
49
        let view = self.view()?;
50
        let mut out = Vec::new();
51
        for (name, state) in &view.bookmarks {
52
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
53
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
54
                AttestBody::Ref { serial, .. } => Some(serial),
55
                _ => None,
56
            });
57
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
58
            out.push(RemoteRef { name: name.clone(), state: *state, heads: self.store.get_state(state)?.heads, attestation, last_serial });
59
        }
60
        Ok(RefsResponse { refs: out, policy: self.current_policy()?.map(|(_, sp)| sp), tags: self.tag_refs()? })
61
    }
62
63
    /// Every change reachable from `heads` that is in the store.
64
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
65
        let mut seen = BTreeSet::new();
66
        let mut stack: Vec<ChangeHash> = heads.to_vec();
67
        while let Some(h) = stack.pop() {
68
            if seen.contains(&h) || !self.store.has(&h) {
69
                continue;
70
            }
71
            seen.insert(h);
72
            stack.extend(self.store.get_change(&h)?.deps);
73
        }
74
        Ok(seen)
75
    }
76
77
    /// The changes within `depth` dependency steps of `heads` (spec §17),
78
    /// nearest first; depth 1 is the heads themselves.
79
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
80
        let mut out = Vec::new();
81
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
82
        let mut layer: Vec<ChangeHash> = heads.to_vec();
83
        for _ in 0..depth.max(1) {
84
            let mut next = Vec::new();
85
            for h in layer {
86
                if !seen.insert(h) || !self.store.has(&h) {
87
                    continue;
88
                }
89
                let c = self.store.get_change(&h)?;
90
                next.extend(c.deps.iter().copied());
91
                out.push(h);
92
            }
93
            if next.is_empty() {
94
                break;
95
            }
96
            layer = next;
97
        }
98
        out.reverse();
99
        Ok(out)
100
    }
101
102
    fn shallow_path(&self) -> PathBuf {
103
        self.oxy.join("shallow")
104
    }
105
106
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
107
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
108
        fs::read_to_string(self.shallow_path()).map(|t| t.lines().filter_map(ObjectRef::from_hex).collect()).unwrap_or_default()
109
    }
110
111
    pub fn is_shallow(&self) -> bool {
112
        !self.boundary().is_empty()
113
    }
114
115
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
116
        if boundary.is_empty() {
117
            let _ = fs::remove_file(self.shallow_path());
118
            return Ok(());
119
        }
120
        let text: String = boundary.iter().map(|h| format!("{}\n", h.to_hex())).collect();
121
        write_atomic(&self.shallow_path(), text.as_bytes())
122
    }
123
124
    /// Recompute the boundary from what is stored: every dependency of a
125
    /// stored change that is not itself stored.
126
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
127
        let mut boundary = self.boundary();
128
        boundary.retain(|h| !self.store.has(h));
129
        for h in imported {
130
            for d in self.store.get_change(h)?.deps {
131
                if !self.store.has(&d) {
132
                    boundary.insert(d);
133
                }
134
            }
135
        }
136
        self.write_boundary(&boundary)
137
    }
138
139
    /// Fetch `depth` more levels of history below the shallow boundary.
140
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
141
        let boundary = self.boundary();
142
        if boundary.is_empty() {
143
            return Ok(0);
144
        }
145
        let remote = self.open_named_remote(remote_name)?;
146
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
147
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
148
        let imported = self.import_bundle_shallow(&bundle, false)?;
149
        if self.config.max_blob.is_some() {
150
            self.register_missing_blobs(&imported, remote_name)?;
151
        }
152
        self.refresh_boundary(&imported)?;
153
        Ok(imported.len())
154
    }
155
156
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
157
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
158
        let have = self.closure_in_store(have)?;
159
        // In a shallow repository the walk stops at the boundary, whose
160
        // changes the remote is assumed to hold.
161
        let boundary = self.boundary();
162
        let mut out = Vec::new();
163
        let mut done: BTreeSet<ChangeHash> = have.clone();
164
        done.extend(boundary.iter().copied());
165
        // Iterative post-order DFS.
166
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
167
        while let Some((h, expanded)) = stack.pop() {
168
            if done.contains(&h) {
169
                continue;
170
            }
171
            if !self.store.has(&h) {
172
                return fail(format!("change {} is not in this repository", h.short(12)));
173
            }
174
            if expanded {
175
                done.insert(h);
176
                out.push(h);
177
                continue;
178
            }
179
            stack.push((h, true));
180
            for d in self.store.get_change(&h)?.deps {
181
                if !done.contains(&d) {
182
                    stack.push((d, false));
183
                }
184
            }
185
        }
186
        Ok(out)
187
    }
188
189
    /// Bundle changes (in the given dependency order) with their signatures,
190
    /// seals, identities, blobs, chunks.
191
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
192
        self.bundle_for_filtered(changes, None)
193
    }
194
195
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
196
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
197
        let mut out = Vec::new();
198
        for r in refs {
199
            let (ty, body) = match self.store.get(r) {
200
                Ok(x) => x,
201
                Err(StoreError::NotFound(_)) => continue,
202
                Err(e) => return Err(e.into()),
203
            };
204
            if ty == ObjectType::Blob {
205
                for c in Blob::decode(&body)?.chunks {
206
                    if let Ok((cty, cb)) = self.store.get(&c) {
207
                        out.push((cty, cb));
208
                    }
209
                }
210
            }
211
            out.push((ty, body));
212
        }
213
        Ok(out)
214
    }
215
216
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
217
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
218
    pub fn bundle_for_filtered(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
219
        let mut bundle = Bundle::default();
220
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
221
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
222
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
223
            if !r.is_zero() && self.store.has(r) {
224
                objects.insert(*r);
225
            }
226
        };
227
        for h in changes {
228
            let c = self.store.get_change(h)?;
229
            let sigs = self.store.signatures(h)?;
230
            add_object(&c.author, &mut objects);
231
            for s in &sigs {
232
                add_object(&s.key, &mut objects);
233
            }
234
            for e in &c.edits {
235
                if let Edit::Replace { old, new, .. } = e {
236
                    for b in [old, new].into_iter().flatten() {
237
                        if self.store.has(b) {
238
                            if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?) {
239
                                if max_blob.is_some_and(|m| blob.length > m) {
240
                                    continue;
241
                                }
242
                                objects.insert(*b);
243
                                objects.extend(blob.chunks.iter().copied());
244
                            }
245
                        }
246
                    }
247
                }
248
            }
249
            for s in self.store.seals_for(h)? {
250
                seals.insert(s);
251
            }
252
            bundle.changes.push((c, sigs));
253
        }
254
        for r in seals {
255
            let attest = self.store.get_attest(&r)?;
256
            let sigs = self.store.signatures(&r)?;
257
            for s in &sigs {
258
                add_object(&s.key, &mut objects);
259
            }
260
            bundle.attests.push(SignedAttest { attest, sigs });
261
        }
262
        for r in objects {
263
            let (ty, body) = self.store.get(&r)?;
264
            bundle.objects.push((ty, body));
265
        }
266
        Ok(bundle)
267
    }
268
269
    /// Store a bundle's contents. With `strict`, every change must
270
    /// authenticate (signature or seal by its author or a delegate).
271
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
272
        self.import_bundle_inner(bundle, strict, false)
273
    }
274
275
    /// Like `import_bundle`, accepting changes whose dependencies are absent
276
    /// (they join the shallow boundary).
277
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
278
        self.import_bundle_inner(bundle, strict, true)
279
    }
280
281
    fn import_bundle_inner(&self, bundle: &Bundle, strict: bool, shallow: bool) -> Result<Vec<ChangeHash>> {
282
        for (ty, body) in &bundle.objects {
283
            match ty {
284
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Identity | ObjectType::State | ObjectType::Checkpoint => {
285
                    self.store.put(*ty, body)?;
286
                }
287
                other => return fail(format!("bundle may not carry {} objects", other.name())),
288
            }
289
        }
290
        for sa in &bundle.attests {
291
            let r = self.store.put_attest(&sa.attest)?;
292
            for sig in &sa.sigs {
293
                self.store.put_signature(&r, sig)?;
294
            }
295
            if let AttestBody::Seal { hashes } = &sa.attest.body {
296
                for h in hashes {
297
                    self.store.index_seal(h, &r)?;
298
                }
299
            }
300
        }
301
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
302
        let boundary = self.boundary();
303
        let mut imported = Vec::new();
304
        for (c, sigs) in &bundle.changes {
305
            let h = c.hash();
306
            for d in &c.deps {
307
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d) {
308
                    return fail(format!("change {} depends on {}, which is neither stored nor in the bundle", h.short(12), d.short(12)));
309
                }
310
            }
311
            self.store.put_change(c)?;
312
            for sig in sigs {
313
                self.store.put_signature(&h, sig)?;
314
            }
315
            imported.push(h);
316
        }
317
        if strict {
318
            for h in &imported {
319
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
320
                    return fail(format!("change {} is not authenticated by its author", h.short(12)));
321
                }
322
            }
323
        }
324
        Ok(imported)
325
    }
326
327
    /// Verify a reference attestation against an update it claims to describe.
328
    /// `allow_equal` lets a client re-read the attestation it already has; a
329
    /// server receiving a push requires a strictly greater serial.
330
    fn check_ref_attest(&self, sa: &SignedAttest, name: &str, old_state: &ObjectRef, new_state: &ObjectRef, last_serial: Option<u64>, allow_equal: bool) -> std::result::Result<u64, String> {
331
        let AttestBody::Ref { name: n, old_state: o, new_state: nw, serial } = &sa.attest.body else {
332
            return Err("attestation is not a ref attestation".into());
333
        };
334
        if n != name || o != old_state || nw != new_state {
335
            return Err("attestation does not describe this update".into());
336
        }
337
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
338
            return Err("attestation is for a different repository".into());
339
        }
340
        if let Some(last) = last_serial {
341
            if *serial < last || (*serial == last && !allow_equal) {
342
                return Err(format!("attestation serial {serial} is not greater than the last seen {last}"));
343
            }
344
        }
345
        let r = sa.attest.hash();
346
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
347
        let id = self.store.get_identity(&sig.key).map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
348
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
349
        Ok(*serial)
350
    }
351
352
    /// Accept a push (spec §16.4). Without a trust policy every repository
353
    /// is unverified, so unsigned changes and unattested updates are accepted;
354
    /// attestations that are present must still be valid. With a policy,
355
    /// every change and update is checked against it. A newer policy in the
356
    /// push is applied first when it is signed by the current roots.
357
    pub fn receive_push(&self, bundle: Bundle, updates: Vec<RefUpdate>, policy: Option<SignedPolicy>, tags: Vec<crate::protocol::TagRef>) -> Result<Vec<RefResult>> {
358
        let mut results = Vec::new();
359
        if let Some(sp) = policy {
360
            let current = self.current_policy()?.map(|(_, c)| c.policy);
361
            match self.check_policy(&sp, current.as_ref()) {
362
                Ok(()) => {
363
                    self.set_policy(&sp, &format!("push received: policy serial {}", sp.policy.serial))?;
364
                    results.push(RefResult { name: "policy".into(), ok: true, reason: format!("serial {}", sp.policy.serial) });
365
                }
366
                Err(e) => {
367
                    results.push(RefResult { name: "policy".into(), ok: false, reason: e });
368
                    for u in updates {
369
                        results.push(RefResult { name: u.name, ok: false, reason: "policy update was rejected".into() });
370
                    }
371
                    return Ok(results);
372
                }
373
            }
374
        }
375
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
376
        if let Err(e) = self.import_bundle(&bundle, policy.is_some()) {
377
            for u in updates {
378
                results.push(RefResult { name: u.name, ok: false, reason: e.to_string() });
379
            }
380
            return Ok(results);
381
        }
382
        let (op_ref, op) = self.head_op()?;
383
        let mut view = op.view.clone();
384
        let mut names = Vec::new();
385
        for u in updates {
386
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
387
            let (ok, reason) = match outcome {
388
                Ok(()) => (true, String::new()),
389
                Err(e) => (false, e),
390
            };
391
            if ok {
392
                names.push(u.name.clone());
393
            }
394
            results.push(RefResult { name: u.name, ok, reason });
395
        }
396
        for t in &tags {
397
            let name = format!("tags/{}", t.name);
398
            let new = !view.tags.contains_key(&t.name);
399
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
400
                Ok(()) => {
401
                    // A tag new here is an update too, so a hub can start
402
                    // its pipeline's tag jobs (oxygenflow#24); one it
403
                    // already had, sent again, is not.
404
                    if new {
405
                        report.updated.push(RefUpdated {
406
                            name: name.clone(),
407
                            old_state: ObjectRef::ZERO,
408
                            new_state: t.state,
409
                            heads: t.heads.clone(),
410
                        });
411
                    }
412
                    names.push(name.clone());
413
                    results.push(RefResult { name, ok: true, reason: String::new() });
414
                }
415
                Err(e) => results.push(RefResult { name, ok: false, reason: e }),
416
            }
417
        }
418
        if !names.is_empty() {
419
            self.record_op(&[op_ref], &format!("push received: {}", names.join(" ")), view)?;
420
        }
421
        Ok(results)
422
    }
423
424
    fn apply_update(&self, view: &mut View, u: &RefUpdate, policy: Option<&crate::policy::Policy>) -> std::result::Result<(), String> {
425
        if u.name == "policy" {
426
            return Err("the policy reference is updated by sending a policy, not a bookmark update".into());
427
        }
428
        let empty = self.store.put_state(&StateObject::new(vec![])).map_err(|e| e.to_string())?;
429
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
430
        if current != u.old_state {
431
            return Err("stale: the remote bookmark has moved; pull first".into());
432
        }
433
        let new_state = self.store.get_state(&u.new_state).map_err(|_| "new state object is missing".to_string())?;
434
        for h in &new_state.heads {
435
            if !self.store.has(h) {
436
                return Err(format!("head {} is missing", h.short(12)));
437
            }
438
        }
439
        if !u.force {
440
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
441
            let closure = self.closure_in_store(&new_state.heads).map_err(|e| e.to_string())?;
442
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
443
                return Err(format!("not a fast-forward: current head {} would be dropped (use --force)", h.short(12)));
444
            }
445
        }
446
        if let Some(p) = policy {
447
            let Some(sa) = &u.attestation else {
448
                return Err(format!("{:?} requires a signed reference attestation under this repository's policy", u.name));
449
            };
450
            let signer = sa.sigs.first().map(|s| s.key).ok_or("attestation carries no signature")?;
451
            if !p.authorizes(&signer, &u.name) {
452
                return Err(format!("key {} may not update {:?} under this repository's policy", signer.short(12), u.name));
453
            }
454
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
455
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
456
        }
457
        if let Some(sa) = &u.attestation {
458
            let last = self.latest_ref_attest(&u.name).map_err(|e| e.to_string())?.and_then(|(_, a)| match a.attest.body {
459
                AttestBody::Ref { serial, .. } => Some(serial),
460
                _ => None,
461
            });
462
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
463
            let r = self.store.put_attest(&sa.attest).map_err(|e| e.to_string())?;
464
            for sig in &sa.sigs {
465
                self.store.put_signature(&r, sig).map_err(|e| e.to_string())?;
466
            }
467
            self.set_ref_attest(&u.name, &r).map_err(|e| e.to_string())?;
468
        }
469
        view.bookmarks.insert(u.name.clone(), u.new_state);
470
        Ok(())
471
    }
472
473
    // ------------------------------------------------------------ client side
474
475
    fn remote_url(&self, name: &str) -> Result<String> {
476
        self.config.remotes.get(name).cloned().ok_or_else(|| RepoError::Msg(format!("no remote named {name:?}; add one with `oxy remote add`")))
477
    }
478
479
    /// Credentials and trust for a remote: `remote.<name>.token` (else
480
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
481
    fn remote_options(&self, name: &str) -> RemoteOptions {
482
        RemoteOptions {
483
            token: self.config.remote_tokens.get(name).cloned().or_else(|| std::env::var("OXY_TOKEN").ok()),
484
            ca: self.config.remote_cas.get(name).map(PathBuf::from).or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
485
        }
486
    }
487
488
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
489
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
490
    }
491
492
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
493
        self.oxy.join("remotes").join(remote).join(format!("{bookmark}.serial"))
494
    }
495
496
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
497
        fs::read_to_string(self.serial_path(remote, bookmark)).ok().and_then(|s| s.trim().parse().ok())
498
    }
499
500
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
501
        let p = self.serial_path(remote, bookmark);
502
        fs::create_dir_all(p.parent().unwrap())?;
503
        write_atomic(&p, serial.to_string().as_bytes())
504
    }
505
506
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
507
        self.oxy.join("remotes").join(remote).join("policy.serial")
508
    }
509
510
    /// The highest policy serial `remote` has ever presented.
511
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
512
        fs::read_to_string(self.policy_serial_path(remote)).ok().and_then(|s| s.trim().parse().ok())
513
    }
514
515
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
516
        let p = self.policy_serial_path(remote);
517
        fs::create_dir_all(p.parent().unwrap())?;
518
        write_atomic(&p, serial.to_string().as_bytes())
519
    }
520
521
    fn lazy_dir(&self) -> PathBuf {
522
        self.oxy.join("lazy")
523
    }
524
525
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
526
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
527
        fs::create_dir_all(self.lazy_dir())?;
528
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
529
    }
530
531
    /// Which remote promised an absent blob, if any.
532
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
533
        fs::read_to_string(self.lazy_dir().join(blob.to_hex())).ok().map(|s| s.trim().to_string())
534
    }
535
536
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
537
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
538
        let Some(remote_name) = self.lazy_remote(blob) else {
539
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
540
        };
541
        let remote = self.open_named_remote(&remote_name)?;
542
        let objects = remote.objects(&[*blob])?;
543
        for (ty, body) in objects {
544
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
545
                self.store.put(ty, &body)?;
546
            }
547
        }
548
        if !self.store.has(blob) {
549
            return fail(format!("{remote_name} did not send blob {}", blob.short(12)));
550
        }
551
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
552
        Ok(())
553
    }
554
555
    /// After importing from `remote`, record every blob the changes reference
556
    /// that the store lacks as lazily available from that remote.
557
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
558
        let mut n = 0;
559
        for h in changes {
560
            let c = self.store.get_change(h)?;
561
            for e in &c.edits {
562
                if let Edit::Replace { old, new, .. } = e {
563
                    for b in [old, new].into_iter().flatten() {
564
                        if !self.store.has(b) {
565
                            self.register_lazy(b, remote)?;
566
                            n += 1;
567
                        }
568
                    }
569
                }
570
            }
571
        }
572
        Ok(n)
573
    }
574
575
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
576
    fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
577
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
578
        for st in view.bookmarks.values().chain(view.remotes.values().flat_map(|b| b.values())) {
579
            if let Ok(s) = self.store.get_state(st) {
580
                have.extend(s.heads);
581
            }
582
        }
583
        have.extend(view.workspaces.values().copied());
584
        Ok(have.into_iter().collect())
585
    }
586
587
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
588
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
589
        let remote = self.open_named_remote(remote_name)?;
590
        if remote.repo_id()? != self.id()? {
591
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
592
        }
593
        let resp = remote.refs()?;
594
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
595
        // and signed by roots we trust, or on first contact. A remote that
596
        // once presented a policy may never present none or an older one:
597
        // that is a downgrade. A remote that never presented one is
598
        // unverified, and this fetch is checked only as far as possible.
599
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
600
        let seen = self.remote_policy_serial(remote_name);
601
        let mut unverified = false;
602
        match &resp.policy {
603
            Some(sp) => {
604
                if seen.is_some_and(|s| sp.policy.serial < s) {
605
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
606
                }
607
                match &local_policy {
608
                    Some(l) if sp.policy.serial < l.serial => {}
609
                    Some(l) if sp.policy.serial == l.serial => {
610
                        if sp.policy.hash() != l.hash() {
611
                            return fail(format!("{remote_name} presents a different policy with the same serial {}", l.serial));
612
                        }
613
                    }
614
                    local => {
615
                        self.check_policy(sp, local.as_ref()).map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
616
                        self.set_policy(sp, &format!("oxy fetch {remote_name} (policy serial {})", sp.policy.serial))?;
617
                    }
618
                }
619
                self.record_policy_serial(remote_name, sp.policy.serial)?;
620
            }
621
            None => {
622
                if seen.is_some() {
623
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
624
                }
625
                unverified = true;
626
            }
627
        }
628
        let policy = if unverified { None } else { self.current_policy()?.map(|(_, sp)| sp.policy) };
629
        let (op_ref, op) = self.head_op()?;
630
        let mut view = op.view.clone();
631
        let have = self.known_heads(&view)?;
632
        let mut report = Vec::new();
633
        let max_blob = self.config.max_blob;
634
        for r in resp.refs {
635
            let needed = remote.negotiate(&have, &r.heads)?;
636
            let bundle = remote.fetch(&needed, max_blob)?;
637
            // Changes are not individually re-verified here: the bookmark's
638
            // attestation (checked below) binds its whole state, and the
639
            // receiver of the push verified the added changes at that time.
640
            let imported = self.import_bundle(&bundle, false)?;
641
            if max_blob.is_some() {
642
                self.register_missing_blobs(&imported, remote_name)?;
643
            }
644
            for h in &r.heads {
645
                if !self.store.has(h) {
646
                    return fail(format!("remote did not send head {}", h.short(12)));
647
                }
648
            }
649
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
650
            if state != r.state {
651
                return fail(format!("remote state {} does not match its heads", r.state.short(12)));
652
            }
653
            if let Some(p) = &policy {
654
                let Some(sa) = &r.attestation else {
655
                    return fail(format!("{remote_name}/{} has no attestation, which its policy requires", r.name));
656
                };
657
                let signer = sa.sigs.first().map(|s| s.key).ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
658
                if !p.authorizes(&signer, &r.name) {
659
                    return fail(format!("{remote_name}/{}: attested by {}, which the policy does not authorize", r.name, signer.short(12)));
660
                }
661
            }
662
            if let Some(sa) = &r.attestation {
663
                let AttestBody::Ref { old_state, new_state, .. } = &sa.attest.body else {
664
                    return fail("remote sent a non-ref attestation for a bookmark");
665
                };
666
                let (old_state, new_state) = (*old_state, *new_state);
667
                let serial = self
668
                    .check_ref_attest(sa, &r.name, &old_state, &new_state, self.last_seen_serial(remote_name, &r.name), true)
669
                    .map_err(|e| RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name)))?;
670
                if new_state != r.state {
671
                    return fail(format!("attestation for {}/{} does not cover its current state", remote_name, r.name));
672
                }
673
                let ar = self.store.put_attest(&sa.attest)?;
674
                for sig in &sa.sigs {
675
                    self.store.put_signature(&ar, sig)?;
676
                }
677
                self.record_serial(remote_name, &r.name, serial)?;
678
            }
679
            view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state);
680
            report.push((r.name, r.heads, imported.len()));
681
        }
682
        let mut new_tags = 0;
683
        for t in &resp.tags {
684
            if view.tags.contains_key(&t.name) {
685
                continue;
686
            }
687
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
688
            let missing: Vec<ChangeHash> = t.heads.iter().filter(|h| !self.store.has(h)).copied().collect();
689
            if !missing.is_empty() {
690
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
691
                let bundle = remote.fetch(&needed, max_blob)?;
692
                self.import_bundle(&bundle, false)?;
693
            }
694
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
695
            self.adopt_tag(&mut view, t, policy.as_ref()).map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
696
            new_tags += 1;
697
        }
698
        if view != op.view {
699
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
700
        }
701
        Ok(FetchReport { refs: report, unverified, new_tags })
702
    }
703
704
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
705
    /// the changes within `depth` steps of its heads, and the boundary below.
706
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
707
        let remote = self.open_named_remote(remote_name)?;
708
        if remote.repo_id()? != self.id()? {
709
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
710
        }
711
        let resp = remote.refs()?;
712
        let bookmark = self.config.bookmark.clone();
713
        if let Some(sp) = &resp.policy {
714
            let local = self.current_policy()?.map(|(_, sp)| sp.policy);
715
            self.check_policy(sp, local.as_ref()).map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
716
            self.set_policy(sp, &format!("oxy clone --depth (policy serial {})", sp.policy.serial))?;
717
            self.record_policy_serial(remote_name, sp.policy.serial)?;
718
        }
719
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
720
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
721
        };
722
        if r.heads.is_empty() {
723
            return Ok(0);
724
        }
725
        // Base: the remote's checkpoint of exactly these heads.
726
        let cp_bundle = remote.checkpoint(&r.heads)?;
727
        let mut cp_ref = None;
728
        for (ty, body) in &cp_bundle.objects {
729
            let put = self.store.put(*ty, body)?;
730
            if *ty == ObjectType::Checkpoint {
731
                cp_ref = Some(put);
732
            }
733
        }
734
        let Some(cp_ref) = cp_ref else { return fail(format!("{remote_name} sent no checkpoint")) };
735
        self.install_checkpoint(&bookmark, &cp_ref)?;
736
        // History window.
737
        let wanted = remote.shallow(&r.heads, depth)?;
738
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
739
        let imported = self.import_bundle_shallow(&bundle, false)?;
740
        if self.config.max_blob.is_some() {
741
            self.register_missing_blobs(&imported, remote_name)?;
742
        }
743
        self.refresh_boundary(&imported)?;
744
        if let Some(sa) = &r.attestation {
745
            let ar = self.store.put_attest(&sa.attest)?;
746
            for sig in &sa.sigs {
747
                self.store.put_signature(&ar, sig)?;
748
            }
749
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
750
                self.record_serial(remote_name, &r.name, serial)?;
751
            }
752
        }
753
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
754
        let (op_ref, op) = self.head_op()?;
755
        let mut view = op.view.clone();
756
        view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state);
757
        self.record_op(&[op_ref], &format!("oxy fetch {remote_name} --depth {depth}"), view)?;
758
        Ok(imported.len())
759
    }
760
761
    /// Fetch, then take the union of the local bookmark's state with the
762
    /// remote's: no merge change, conflicts become reified (spec §9.4).
763
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
764
        self.fetch(remote_name)?;
765
        let (op_ref, op) = self.head_op()?;
766
        let bookmark = self.config.bookmark.clone();
767
        let local = self.heads_of(&op.view, &bookmark)?;
768
        let Some(remote_state) = op.view.remotes.get(remote_name).and_then(|b| b.get(&bookmark)).copied() else {
769
            return Ok(PullReport { heads: local, changed: false, checked_out: false });
770
        };
771
        let remote_heads = self.store.get_state(&remote_state)?.heads;
772
        let mut all = local.clone();
773
        all.extend(remote_heads);
774
        let st = self.load_state(&all)?;
775
        let mut heads = st.maximal(&all);
776
        heads.sort();
777
        let mut sorted_local = local.clone();
778
        sorted_local.sort();
779
        if heads == sorted_local {
780
            return Ok(PullReport { heads, changed: false, checked_out: false });
781
        }
782
        let mut view = op.view.clone();
783
        view.bookmarks.insert(bookmark.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
784
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
785
        // Follow along if the working copy was clean and on the old heads.
786
        let snap = self.snapshot("oxy pull")?;
787
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
788
        let mut base = snap.base.maximal(&snap.wc.deps);
789
        base.sort();
790
        let mut checked_out = false;
791
        if clean && base == sorted_local {
792
            self.checkout(&heads, false, "oxy pull (checkout)")?;
793
            checked_out = true;
794
        }
795
        Ok(PullReport { heads, changed: true, checked_out })
796
    }
797
798
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
799
    /// changes and attesting the reference when a key is available.
800
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
801
        let remote = self.open_named_remote(remote_name)?;
802
        if remote.repo_id()? != self.id()? {
803
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
804
        }
805
        let (op_ref, op) = self.head_op()?;
806
        let bookmark = self.config.bookmark.clone();
807
        let local_heads = self.heads_of(&op.view, &bookmark)?;
808
        let resp = remote.refs()?;
809
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
810
        let policy_to_send = match (&local_policy, &resp.policy) {
811
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
812
            (Some(l), None) => Some(l.clone()),
813
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
814
                return fail(format!("{remote_name} has a newer policy (serial {}); fetch first", r.policy.serial));
815
            }
816
            _ => None,
817
        };
818
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
819
        if remote_has_policy && self.secret_key()?.is_none() {
820
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
821
        }
822
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
823
        let tags_to_send: Vec<crate::protocol::TagRef> = self.tag_refs()?.into_iter().filter(|t| !remote_tags.contains(&t.name)).collect();
824
        let refs = resp.refs;
825
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
826
        let (remote_state, remote_heads, last_serial) = match refs.iter().find(|r| r.name == bookmark) {
827
            Some(r) => (r.state, r.heads.clone(), r.last_serial),
828
            None => (empty, vec![], None),
829
        };
830
        let new_state = self.store.put_state(&StateObject::new(local_heads.clone()))?;
831
        // A push that carries a policy re-attests the bookmark even when its
832
        // state is unchanged, so the current attestation is always by a key
833
        // the current policy authorizes (a revoked key's attestation would
834
        // otherwise be refused by every later fetch).
835
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
836
            return Ok(vec![RefResult { name: bookmark, ok: true, reason: "already up to date".into() }]);
837
        }
838
        for h in &remote_heads {
839
            if !self.store.has(h) {
840
                return fail(format!("the remote has change {} which you do not; pull first", h.short(12)));
841
            }
842
        }
843
        if !force {
844
            let closure = self.closure_in_store(&local_heads)?;
845
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
846
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
847
            }
848
        }
849
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
850
        let mut bundle = self.bundle_for(&to_send)?;
851
        let key = self.secret_key()?.map(|(k, _)| k);
852
        if let Some(key) = key {
853
            // Seal this author's changes that carry no valid authenticator.
854
            let mut unsigned = Vec::new();
855
            for h in &to_send {
856
                let c = self.store.get_change(h)?;
857
                if c.author == key && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
858
                    unsigned.push(*h);
859
                }
860
            }
861
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
862
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
863
                bundle.attests.push(sa);
864
            }
865
            bundle = self.bundle_for(&to_send)?;
866
        }
867
        bundle.objects.push((ObjectType::State, StateObject::new(local_heads.clone()).encode()));
868
        let attestation = match key {
869
            Some(_) => Some(self.sign_attest(&Attest {
870
                repo: self.id()?,
871
                hlc: Hlc::now(),
872
                body: AttestBody::Ref { name: bookmark.clone(), old_state: remote_state, new_state, serial: last_serial.unwrap_or(0) + 1 },
873
            })?),
874
            None => None,
875
        };
876
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
877
            AttestBody::Ref { serial, .. } => Some(serial),
878
            _ => None,
879
        });
880
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
881
        // Tag states must be present on the remote: bundle their changes too.
882
        for t in &tags_to_send {
883
            let extra = self.negotiate(&remote_heads, &t.heads)?;
884
            let extra: Vec<ChangeHash> = extra.into_iter().filter(|h| !to_send.contains(h)).collect();
885
            if !extra.is_empty() {
886
                let more = self.bundle_for(&extra)?;
887
                bundle.changes.extend(more.changes);
888
                bundle.attests.extend(more.attests);
889
                bundle.objects.extend(more.objects);
890
            }
891
            bundle.objects.push((ObjectType::State, StateObject::new(t.heads.clone()).encode()));
892
        }
893
        let results = remote.push(bundle, vec![RefUpdate { name: bookmark.clone(), old_state: remote_state, new_state, force, attestation }], policy_to_send, tags_to_send)?;
894
        if let (Some(serial), true) = (sent_serial, results.iter().any(|r| r.ok && r.name == "policy")) {
895
            self.record_policy_serial(remote_name, serial)?;
896
        }
897
        if results.iter().any(|r| r.ok && r.name == bookmark) {
898
            let mut view = op.view.clone();
899
            view.remotes.entry(remote_name.to_string()).or_default().insert(bookmark.clone(), new_state);
900
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
901
            if let Some(s) = serial {
902
                self.record_serial(remote_name, &bookmark, s)?;
903
            }
904
        }
905
        Ok(results)
906
    }
907
908
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
909
    /// bookmark set to the remote's, working copy checked out.
910
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
911
        Self::clone_with(url, dest, None, &[])
912
    }
913
914
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
915
    /// read, and materializing only `sparse` paths (which implies lazy blobs
916
    /// unless a size is given, so out-of-scope binaries are never fetched).
917
    pub fn clone_with(url: &str, dest: &Path, max_blob: Option<u64>, sparse: &[String]) -> Result<Repo> {
918
        Self::clone_full(url, dest, max_blob, sparse, None)
919
    }
920
921
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
922
    /// changes within `depth` steps of them; the rest is the boundary.
923
    pub fn clone_shallow(url: &str, dest: &Path, depth: u32, max_blob: Option<u64>, sparse: &[String]) -> Result<Repo> {
924
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
925
    }
926
927
    fn clone_full(url: &str, dest: &Path, max_blob: Option<u64>, sparse: &[String], depth: Option<u32>) -> Result<Repo> {
928
        let options = RemoteOptions {
929
            token: std::env::var("OXY_TOKEN").ok(),
930
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
931
        };
932
        let remote = open_remote(url, &options)?;
933
        let id = remote.repo_id()?;
934
        let mut repo = Repo::init_with_id(dest, id)?;
935
        repo.config.set("remote.origin.url", url)?;
936
        if let Some(m) = max_blob {
937
            repo.config.set("filter.max-blob", &m.to_string())?;
938
        } else if !sparse.is_empty() {
939
            repo.config.set("filter.max-blob", "0")?;
940
        }
941
        if !sparse.is_empty() {
942
            repo.config.set("filter.paths", &sparse.join(","))?;
943
        }
944
        repo.save_config()?;
945
        if let Some(depth) = depth {
946
            repo.fetch_shallow("origin", depth)?;
947
        } else {
948
            repo.fetch("origin")?;
949
        }
950
        let (op_ref, op) = repo.head_op()?;
951
        let bookmark = repo.config.bookmark.clone();
952
        if let Some(state) = op.view.remotes.get("origin").and_then(|b| b.get(&bookmark)).copied() {
953
            let heads = repo.store.get_state(&state)?.heads;
954
            let mut view = op.view.clone();
955
            view.bookmarks.insert(bookmark, state);
956
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
957
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
958
        }
959
        Ok(repo)
960
    }
961
}