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