OXYGENHUB
# 5259a3af8ee6 oxygen / crates / oxy-core / src / repo / sync.rs
34.3 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 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
    /// The remote has never presented a policy, so nothing was verified
11
    /// against one (spec §14.5: warn loudly).
12
    pub unverified: bool,
13
}
14
15
#[derive(Debug, Clone, PartialEq, Eq)]
16
pub struct PullReport {
17
    pub heads: Vec<ChangeHash>,
18
    pub changed: bool,
19
    pub checked_out: bool,
20
}
21
22
impl Repo {
23
    // ------------------------------------------------------------ serving (spec §16)
24
25
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
26
        self.oxy.join("attest").join(bookmark)
27
    }
28
29
    /// The latest reference attestation stored for a bookmark.
30
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
31
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
32
            Ok(h) => {
33
                let r = ObjectRef::from_hex(h.trim()).ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
34
                Ok(Some((r, SignedAttest { attest: self.store.get_attest(&r)?, sigs: self.store.signatures(&r)? })))
35
            }
36
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
37
            Err(e) => Err(e.into()),
38
        }
39
    }
40
41
    fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
42
        fs::create_dir_all(self.oxy.join("attest"))?;
43
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
44
    }
45
46
    pub fn remote_refs(&self) -> Result<RefsResponse> {
47
        let view = self.view()?;
48
        let mut out = Vec::new();
49
        for (name, state) in &view.bookmarks {
50
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
51
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
52
                AttestBody::Ref { serial, .. } => Some(serial),
53
                _ => None,
54
            });
55
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
56
            out.push(RemoteRef { name: name.clone(), state: *state, heads: self.store.get_state(state)?.heads, attestation, last_serial });
57
        }
58
        Ok(RefsResponse { refs: out, policy: self.current_policy()?.map(|(_, sp)| sp) })
59
    }
60
61
    /// Every change reachable from `heads` that is in the store.
62
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
63
        let mut seen = BTreeSet::new();
64
        let mut stack: Vec<ChangeHash> = heads.to_vec();
65
        while let Some(h) = stack.pop() {
66
            if seen.contains(&h) || !self.store.has(&h) {
67
                continue;
68
            }
69
            seen.insert(h);
70
            stack.extend(self.store.get_change(&h)?.deps);
71
        }
72
        Ok(seen)
73
    }
74
75
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
76
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
77
        let have = self.closure_in_store(have)?;
78
        let mut out = Vec::new();
79
        let mut done: BTreeSet<ChangeHash> = have.clone();
80
        // Iterative post-order DFS.
81
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
82
        while let Some((h, expanded)) = stack.pop() {
83
            if done.contains(&h) {
84
                continue;
85
            }
86
            if !self.store.has(&h) {
87
                return fail(format!("change {} is not in this repository", h.short(12)));
88
            }
89
            if expanded {
90
                done.insert(h);
91
                out.push(h);
92
                continue;
93
            }
94
            stack.push((h, true));
95
            for d in self.store.get_change(&h)?.deps {
96
                if !done.contains(&d) {
97
                    stack.push((d, false));
98
                }
99
            }
100
        }
101
        Ok(out)
102
    }
103
104
    /// Bundle changes (in the given dependency order) with their signatures,
105
    /// seals, identities, blobs, chunks.
106
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
107
        self.bundle_for_filtered(changes, None)
108
    }
109
110
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
111
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
112
        let mut out = Vec::new();
113
        for r in refs {
114
            let (ty, body) = match self.store.get(r) {
115
                Ok(x) => x,
116
                Err(StoreError::NotFound(_)) => continue,
117
                Err(e) => return Err(e.into()),
118
            };
119
            if ty == ObjectType::Blob {
120
                for c in Blob::decode(&body)?.chunks {
121
                    if let Ok((cty, cb)) = self.store.get(&c) {
122
                        out.push((cty, cb));
123
                    }
124
                }
125
            }
126
            out.push((ty, body));
127
        }
128
        Ok(out)
129
    }
130
131
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
132
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
133
    pub fn bundle_for_filtered(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
134
        let mut bundle = Bundle::default();
135
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
136
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
137
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
138
            if !r.is_zero() && self.store.has(r) {
139
                objects.insert(*r);
140
            }
141
        };
142
        for h in changes {
143
            let c = self.store.get_change(h)?;
144
            let sigs = self.store.signatures(h)?;
145
            add_object(&c.author, &mut objects);
146
            for s in &sigs {
147
                add_object(&s.key, &mut objects);
148
            }
149
            for e in &c.edits {
150
                if let Edit::Replace { old, new, .. } = e {
151
                    for b in [old, new].into_iter().flatten() {
152
                        if self.store.has(b) {
153
                            if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?) {
154
                                if max_blob.is_some_and(|m| blob.length > m) {
155
                                    continue;
156
                                }
157
                                objects.insert(*b);
158
                                objects.extend(blob.chunks.iter().copied());
159
                            }
160
                        }
161
                    }
162
                }
163
            }
164
            for s in self.store.seals_for(h)? {
165
                seals.insert(s);
166
            }
167
            bundle.changes.push((c, sigs));
168
        }
169
        for r in seals {
170
            let attest = self.store.get_attest(&r)?;
171
            let sigs = self.store.signatures(&r)?;
172
            for s in &sigs {
173
                add_object(&s.key, &mut objects);
174
            }
175
            bundle.attests.push(SignedAttest { attest, sigs });
176
        }
177
        for r in objects {
178
            let (ty, body) = self.store.get(&r)?;
179
            bundle.objects.push((ty, body));
180
        }
181
        Ok(bundle)
182
    }
183
184
    /// Store a bundle's contents. With `strict`, every change must
185
    /// authenticate (signature or seal by its author or a delegate).
186
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
187
        for (ty, body) in &bundle.objects {
188
            match ty {
189
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Identity | ObjectType::State => {
190
                    self.store.put(*ty, body)?;
191
                }
192
                other => return fail(format!("bundle may not carry {} objects", other.name())),
193
            }
194
        }
195
        for sa in &bundle.attests {
196
            let r = self.store.put_attest(&sa.attest)?;
197
            for sig in &sa.sigs {
198
                self.store.put_signature(&r, sig)?;
199
            }
200
            if let AttestBody::Seal { hashes } = &sa.attest.body {
201
                for h in hashes {
202
                    self.store.index_seal(h, &r)?;
203
                }
204
            }
205
        }
206
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
207
        let mut imported = Vec::new();
208
        for (c, sigs) in &bundle.changes {
209
            let h = c.hash();
210
            for d in &c.deps {
211
                if !self.store.has(d) && !incoming.contains(d) {
212
                    return fail(format!("change {} depends on {}, which is neither stored nor in the bundle", h.short(12), d.short(12)));
213
                }
214
            }
215
            self.store.put_change(c)?;
216
            for sig in sigs {
217
                self.store.put_signature(&h, sig)?;
218
            }
219
            imported.push(h);
220
        }
221
        if strict {
222
            for h in &imported {
223
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
224
                    return fail(format!("change {} is not authenticated by its author", h.short(12)));
225
                }
226
            }
227
        }
228
        Ok(imported)
229
    }
230
231
    /// Verify a reference attestation against an update it claims to describe.
232
    /// `allow_equal` lets a client re-read the attestation it already has; a
233
    /// server receiving a push requires a strictly greater serial.
234
    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> {
235
        let AttestBody::Ref { name: n, old_state: o, new_state: nw, serial } = &sa.attest.body else {
236
            return Err("attestation is not a ref attestation".into());
237
        };
238
        if n != name || o != old_state || nw != new_state {
239
            return Err("attestation does not describe this update".into());
240
        }
241
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
242
            return Err("attestation is for a different repository".into());
243
        }
244
        if let Some(last) = last_serial {
245
            if *serial < last || (*serial == last && !allow_equal) {
246
                return Err(format!("attestation serial {serial} is not greater than the last seen {last}"));
247
            }
248
        }
249
        let r = sa.attest.hash();
250
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
251
        let id = self.store.get_identity(&sig.key).map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
252
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
253
        Ok(*serial)
254
    }
255
256
    /// Accept a push (spec §16.4). Without a trust policy every repository
257
    /// is unverified, so unsigned changes and unattested updates are accepted;
258
    /// attestations that are present must still be valid. With a policy,
259
    /// every change and update is checked against it. A newer policy in the
260
    /// push is applied first when it is signed by the current roots.
261
    pub fn receive_push(&self, bundle: Bundle, updates: Vec<RefUpdate>, policy: Option<SignedPolicy>) -> Result<Vec<RefResult>> {
262
        let mut results = Vec::new();
263
        if let Some(sp) = policy {
264
            let current = self.current_policy()?.map(|(_, c)| c.policy);
265
            match self.check_policy(&sp, current.as_ref()) {
266
                Ok(()) => {
267
                    self.set_policy(&sp, &format!("push received: policy serial {}", sp.policy.serial))?;
268
                    results.push(RefResult { name: "policy".into(), ok: true, reason: format!("serial {}", sp.policy.serial) });
269
                }
270
                Err(e) => {
271
                    results.push(RefResult { name: "policy".into(), ok: false, reason: e });
272
                    for u in updates {
273
                        results.push(RefResult { name: u.name, ok: false, reason: "policy update was rejected".into() });
274
                    }
275
                    return Ok(results);
276
                }
277
            }
278
        }
279
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
280
        if let Err(e) = self.import_bundle(&bundle, policy.is_some()) {
281
            for u in updates {
282
                results.push(RefResult { name: u.name, ok: false, reason: e.to_string() });
283
            }
284
            return Ok(results);
285
        }
286
        let (op_ref, op) = self.head_op()?;
287
        let mut view = op.view.clone();
288
        let mut names = Vec::new();
289
        for u in updates {
290
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
291
            let (ok, reason) = match outcome {
292
                Ok(()) => (true, String::new()),
293
                Err(e) => (false, e),
294
            };
295
            if ok {
296
                names.push(u.name.clone());
297
            }
298
            results.push(RefResult { name: u.name, ok, reason });
299
        }
300
        if !names.is_empty() {
301
            self.record_op(&[op_ref], &format!("push received: {}", names.join(" ")), view)?;
302
        }
303
        Ok(results)
304
    }
305
306
    fn apply_update(&self, view: &mut View, u: &RefUpdate, policy: Option<&crate::policy::Policy>) -> std::result::Result<(), String> {
307
        if u.name == "policy" {
308
            return Err("the policy reference is updated by sending a policy, not a bookmark update".into());
309
        }
310
        let empty = self.store.put_state(&StateObject::new(vec![])).map_err(|e| e.to_string())?;
311
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
312
        if current != u.old_state {
313
            return Err("stale: the remote bookmark has moved; pull first".into());
314
        }
315
        let new_state = self.store.get_state(&u.new_state).map_err(|_| "new state object is missing".to_string())?;
316
        for h in &new_state.heads {
317
            if !self.store.has(h) {
318
                return Err(format!("head {} is missing", h.short(12)));
319
            }
320
        }
321
        if !u.force {
322
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
323
            let closure = self.closure_in_store(&new_state.heads).map_err(|e| e.to_string())?;
324
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
325
                return Err(format!("not a fast-forward: current head {} would be dropped (use --force)", h.short(12)));
326
            }
327
        }
328
        if let Some(p) = policy {
329
            let Some(sa) = &u.attestation else {
330
                return Err(format!("{:?} requires a signed reference attestation under this repository's policy", u.name));
331
            };
332
            let signer = sa.sigs.first().map(|s| s.key).ok_or("attestation carries no signature")?;
333
            if !p.authorizes(&signer, &u.name) {
334
                return Err(format!("key {} may not update {:?} under this repository's policy", signer.short(12), u.name));
335
            }
336
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
337
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
338
        }
339
        if let Some(sa) = &u.attestation {
340
            let last = self.latest_ref_attest(&u.name).map_err(|e| e.to_string())?.and_then(|(_, a)| match a.attest.body {
341
                AttestBody::Ref { serial, .. } => Some(serial),
342
                _ => None,
343
            });
344
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
345
            let r = self.store.put_attest(&sa.attest).map_err(|e| e.to_string())?;
346
            for sig in &sa.sigs {
347
                self.store.put_signature(&r, sig).map_err(|e| e.to_string())?;
348
            }
349
            self.set_ref_attest(&u.name, &r).map_err(|e| e.to_string())?;
350
        }
351
        view.bookmarks.insert(u.name.clone(), u.new_state);
352
        Ok(())
353
    }
354
355
    // ------------------------------------------------------------ client side
356
357
    fn remote_url(&self, name: &str) -> Result<String> {
358
        self.config.remotes.get(name).cloned().ok_or_else(|| RepoError::Msg(format!("no remote named {name:?}; add one with `oxy remote add`")))
359
    }
360
361
    /// Credentials and trust for a remote: `remote.<name>.token` (else
362
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
363
    fn remote_options(&self, name: &str) -> RemoteOptions {
364
        RemoteOptions {
365
            token: self.config.remote_tokens.get(name).cloned().or_else(|| std::env::var("OXY_TOKEN").ok()),
366
            ca: self.config.remote_cas.get(name).map(PathBuf::from).or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
367
        }
368
    }
369
370
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
371
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
372
    }
373
374
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
375
        self.oxy.join("remotes").join(remote).join(format!("{bookmark}.serial"))
376
    }
377
378
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
379
        fs::read_to_string(self.serial_path(remote, bookmark)).ok().and_then(|s| s.trim().parse().ok())
380
    }
381
382
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
383
        let p = self.serial_path(remote, bookmark);
384
        fs::create_dir_all(p.parent().unwrap())?;
385
        write_atomic(&p, serial.to_string().as_bytes())
386
    }
387
388
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
389
        self.oxy.join("remotes").join(remote).join("policy.serial")
390
    }
391
392
    /// The highest policy serial `remote` has ever presented.
393
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
394
        fs::read_to_string(self.policy_serial_path(remote)).ok().and_then(|s| s.trim().parse().ok())
395
    }
396
397
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
398
        let p = self.policy_serial_path(remote);
399
        fs::create_dir_all(p.parent().unwrap())?;
400
        write_atomic(&p, serial.to_string().as_bytes())
401
    }
402
403
    fn lazy_dir(&self) -> PathBuf {
404
        self.oxy.join("lazy")
405
    }
406
407
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
408
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
409
        fs::create_dir_all(self.lazy_dir())?;
410
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
411
    }
412
413
    /// Which remote promised an absent blob, if any.
414
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
415
        fs::read_to_string(self.lazy_dir().join(blob.to_hex())).ok().map(|s| s.trim().to_string())
416
    }
417
418
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
419
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
420
        let Some(remote_name) = self.lazy_remote(blob) else {
421
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
422
        };
423
        let remote = self.open_named_remote(&remote_name)?;
424
        let objects = remote.objects(&[*blob])?;
425
        for (ty, body) in objects {
426
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
427
                self.store.put(ty, &body)?;
428
            }
429
        }
430
        if !self.store.has(blob) {
431
            return fail(format!("{remote_name} did not send blob {}", blob.short(12)));
432
        }
433
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
434
        Ok(())
435
    }
436
437
    /// After importing from `remote`, record every blob the changes reference
438
    /// that the store lacks as lazily available from that remote.
439
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
440
        let mut n = 0;
441
        for h in changes {
442
            let c = self.store.get_change(h)?;
443
            for e in &c.edits {
444
                if let Edit::Replace { old, new, .. } = e {
445
                    for b in [old, new].into_iter().flatten() {
446
                        if !self.store.has(b) {
447
                            self.register_lazy(b, remote)?;
448
                            n += 1;
449
                        }
450
                    }
451
                }
452
            }
453
        }
454
        Ok(n)
455
    }
456
457
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
458
    fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
459
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
460
        for st in view.bookmarks.values().chain(view.remotes.values().flat_map(|b| b.values())) {
461
            if let Ok(s) = self.store.get_state(st) {
462
                have.extend(s.heads);
463
            }
464
        }
465
        have.extend(view.workspaces.values().copied());
466
        Ok(have.into_iter().collect())
467
    }
468
469
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
470
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
471
        let remote = self.open_named_remote(remote_name)?;
472
        if remote.repo_id()? != self.id()? {
473
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
474
        }
475
        let resp = remote.refs()?;
476
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
477
        // and signed by roots we trust, or on first contact. A remote that
478
        // once presented a policy may never present none or an older one:
479
        // that is a downgrade. A remote that never presented one is
480
        // unverified, and this fetch is checked only as far as possible.
481
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
482
        let seen = self.remote_policy_serial(remote_name);
483
        let mut unverified = false;
484
        match &resp.policy {
485
            Some(sp) => {
486
                if seen.is_some_and(|s| sp.policy.serial < s) {
487
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
488
                }
489
                match &local_policy {
490
                    Some(l) if sp.policy.serial < l.serial => {}
491
                    Some(l) if sp.policy.serial == l.serial => {
492
                        if sp.policy.hash() != l.hash() {
493
                            return fail(format!("{remote_name} presents a different policy with the same serial {}", l.serial));
494
                        }
495
                    }
496
                    local => {
497
                        self.check_policy(sp, local.as_ref()).map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
498
                        self.set_policy(sp, &format!("oxy fetch {remote_name} (policy serial {})", sp.policy.serial))?;
499
                    }
500
                }
501
                self.record_policy_serial(remote_name, sp.policy.serial)?;
502
            }
503
            None => {
504
                if seen.is_some() {
505
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
506
                }
507
                unverified = true;
508
            }
509
        }
510
        let policy = if unverified { None } else { self.current_policy()?.map(|(_, sp)| sp.policy) };
511
        let (op_ref, op) = self.head_op()?;
512
        let mut view = op.view.clone();
513
        let have = self.known_heads(&view)?;
514
        let mut report = Vec::new();
515
        let max_blob = self.config.max_blob;
516
        for r in resp.refs {
517
            let needed = remote.negotiate(&have, &r.heads)?;
518
            let bundle = remote.fetch(&needed, max_blob)?;
519
            // Changes are not individually re-verified here: the bookmark's
520
            // attestation (checked below) binds its whole state, and the
521
            // receiver of the push verified the added changes at that time.
522
            let imported = self.import_bundle(&bundle, false)?;
523
            if max_blob.is_some() {
524
                self.register_missing_blobs(&imported, remote_name)?;
525
            }
526
            for h in &r.heads {
527
                if !self.store.has(h) {
528
                    return fail(format!("remote did not send head {}", h.short(12)));
529
                }
530
            }
531
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
532
            if state != r.state {
533
                return fail(format!("remote state {} does not match its heads", r.state.short(12)));
534
            }
535
            if let Some(p) = &policy {
536
                let Some(sa) = &r.attestation else {
537
                    return fail(format!("{remote_name}/{} has no attestation, which its policy requires", r.name));
538
                };
539
                let signer = sa.sigs.first().map(|s| s.key).ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
540
                if !p.authorizes(&signer, &r.name) {
541
                    return fail(format!("{remote_name}/{}: attested by {}, which the policy does not authorize", r.name, signer.short(12)));
542
                }
543
            }
544
            if let Some(sa) = &r.attestation {
545
                let AttestBody::Ref { old_state, new_state, .. } = &sa.attest.body else {
546
                    return fail("remote sent a non-ref attestation for a bookmark");
547
                };
548
                let (old_state, new_state) = (*old_state, *new_state);
549
                let serial = self
550
                    .check_ref_attest(sa, &r.name, &old_state, &new_state, self.last_seen_serial(remote_name, &r.name), true)
551
                    .map_err(|e| RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name)))?;
552
                if new_state != r.state {
553
                    return fail(format!("attestation for {}/{} does not cover its current state", remote_name, r.name));
554
                }
555
                let ar = self.store.put_attest(&sa.attest)?;
556
                for sig in &sa.sigs {
557
                    self.store.put_signature(&ar, sig)?;
558
                }
559
                self.record_serial(remote_name, &r.name, serial)?;
560
            }
561
            view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state);
562
            report.push((r.name, r.heads, imported.len()));
563
        }
564
        if view != op.view {
565
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
566
        }
567
        Ok(FetchReport { refs: report, unverified })
568
    }
569
570
    /// Fetch, then take the union of the local bookmark's state with the
571
    /// remote's: no merge change, conflicts become reified (spec §9.4).
572
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
573
        self.fetch(remote_name)?;
574
        let (op_ref, op) = self.head_op()?;
575
        let bookmark = self.config.bookmark.clone();
576
        let local = self.heads_of(&op.view, &bookmark)?;
577
        let Some(remote_state) = op.view.remotes.get(remote_name).and_then(|b| b.get(&bookmark)).copied() else {
578
            return Ok(PullReport { heads: local, changed: false, checked_out: false });
579
        };
580
        let remote_heads = self.store.get_state(&remote_state)?.heads;
581
        let mut all = local.clone();
582
        all.extend(remote_heads);
583
        let st = self.load_state(&all)?;
584
        let mut heads = st.maximal(&all);
585
        heads.sort();
586
        let mut sorted_local = local.clone();
587
        sorted_local.sort();
588
        if heads == sorted_local {
589
            return Ok(PullReport { heads, changed: false, checked_out: false });
590
        }
591
        let mut view = op.view.clone();
592
        view.bookmarks.insert(bookmark.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
593
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
594
        // Follow along if the working copy was clean and on the old heads.
595
        let snap = self.snapshot("oxy pull")?;
596
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
597
        let mut base = snap.base.maximal(&snap.wc.deps);
598
        base.sort();
599
        let mut checked_out = false;
600
        if clean && base == sorted_local {
601
            self.checkout(&heads, false, "oxy pull (checkout)")?;
602
            checked_out = true;
603
        }
604
        Ok(PullReport { heads, changed: true, checked_out })
605
    }
606
607
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
608
    /// changes and attesting the reference when a key is available.
609
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
610
        let remote = self.open_named_remote(remote_name)?;
611
        if remote.repo_id()? != self.id()? {
612
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
613
        }
614
        let (op_ref, op) = self.head_op()?;
615
        let bookmark = self.config.bookmark.clone();
616
        let local_heads = self.heads_of(&op.view, &bookmark)?;
617
        let resp = remote.refs()?;
618
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
619
        let policy_to_send = match (&local_policy, &resp.policy) {
620
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
621
            (Some(l), None) => Some(l.clone()),
622
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
623
                return fail(format!("{remote_name} has a newer policy (serial {}); fetch first", r.policy.serial));
624
            }
625
            _ => None,
626
        };
627
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
628
        if remote_has_policy && self.secret_key()?.is_none() {
629
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
630
        }
631
        let refs = resp.refs;
632
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
633
        let (remote_state, remote_heads, last_serial) = match refs.iter().find(|r| r.name == bookmark) {
634
            Some(r) => (r.state, r.heads.clone(), r.last_serial),
635
            None => (empty, vec![], None),
636
        };
637
        let new_state = self.store.put_state(&StateObject::new(local_heads.clone()))?;
638
        // A push that carries a policy re-attests the bookmark even when its
639
        // state is unchanged, so the current attestation is always by a key
640
        // the current policy authorizes (a revoked key's attestation would
641
        // otherwise be refused by every later fetch).
642
        if new_state == remote_state && policy_to_send.is_none() {
643
            return Ok(vec![RefResult { name: bookmark, ok: true, reason: "already up to date".into() }]);
644
        }
645
        for h in &remote_heads {
646
            if !self.store.has(h) {
647
                return fail(format!("the remote has change {} which you do not; pull first", h.short(12)));
648
            }
649
        }
650
        if !force {
651
            let closure = self.closure_in_store(&local_heads)?;
652
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
653
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
654
            }
655
        }
656
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
657
        let mut bundle = self.bundle_for(&to_send)?;
658
        let key = self.secret_key()?.map(|(k, _)| k);
659
        if let Some(key) = key {
660
            // Seal this author's changes that carry no valid authenticator.
661
            let mut unsigned = Vec::new();
662
            for h in &to_send {
663
                let c = self.store.get_change(h)?;
664
                if c.author == key && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
665
                    unsigned.push(*h);
666
                }
667
            }
668
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
669
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
670
                bundle.attests.push(sa);
671
            }
672
            bundle = self.bundle_for(&to_send)?;
673
        }
674
        bundle.objects.push((ObjectType::State, StateObject::new(local_heads.clone()).encode()));
675
        let attestation = match key {
676
            Some(_) => Some(self.sign_attest(&Attest {
677
                repo: self.id()?,
678
                hlc: Hlc::now(),
679
                body: AttestBody::Ref { name: bookmark.clone(), old_state: remote_state, new_state, serial: last_serial.unwrap_or(0) + 1 },
680
            })?),
681
            None => None,
682
        };
683
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
684
            AttestBody::Ref { serial, .. } => Some(serial),
685
            _ => None,
686
        });
687
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
688
        let results = remote.push(bundle, vec![RefUpdate { name: bookmark.clone(), old_state: remote_state, new_state, force, attestation }], policy_to_send)?;
689
        if let (Some(serial), true) = (sent_serial, results.iter().any(|r| r.ok && r.name == "policy")) {
690
            self.record_policy_serial(remote_name, serial)?;
691
        }
692
        if results.iter().any(|r| r.ok && r.name == bookmark) {
693
            let mut view = op.view.clone();
694
            view.remotes.entry(remote_name.to_string()).or_default().insert(bookmark.clone(), new_state);
695
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
696
            if let Some(s) = serial {
697
                self.record_serial(remote_name, &bookmark, s)?;
698
            }
699
        }
700
        Ok(results)
701
    }
702
703
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
704
    /// bookmark set to the remote's, working copy checked out.
705
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
706
        Self::clone_with(url, dest, None, &[])
707
    }
708
709
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
710
    /// read, and materializing only `sparse` paths (which implies lazy blobs
711
    /// unless a size is given, so out-of-scope binaries are never fetched).
712
    pub fn clone_with(url: &str, dest: &Path, max_blob: Option<u64>, sparse: &[String]) -> Result<Repo> {
713
        let options = RemoteOptions {
714
            token: std::env::var("OXY_TOKEN").ok(),
715
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
716
        };
717
        let remote = open_remote(url, &options)?;
718
        let id = remote.repo_id()?;
719
        let mut repo = Repo::init_with_id(dest, id)?;
720
        repo.config.set("remote.origin.url", url)?;
721
        if let Some(m) = max_blob {
722
            repo.config.set("filter.max-blob", &m.to_string())?;
723
        } else if !sparse.is_empty() {
724
            repo.config.set("filter.max-blob", "0")?;
725
        }
726
        if !sparse.is_empty() {
727
            repo.config.set("filter.paths", &sparse.join(","))?;
728
        }
729
        repo.save_config()?;
730
        repo.fetch("origin")?;
731
        let (op_ref, op) = repo.head_op()?;
732
        let bookmark = repo.config.bookmark.clone();
733
        if let Some(state) = op.view.remotes.get("origin").and_then(|b| b.get(&bookmark)).copied() {
734
            let heads = repo.store.get_state(&state)?.heads;
735
            let mut view = op.view.clone();
736
            view.bookmarks.insert(bookmark, state);
737
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
738
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
739
        }
740
        Ok(repo)
741
    }
742
}