OXYGENHUB
# e5f8eb2a2006 oxygen / crates / oxy-core / src / repo / sync.rs
90.9 KiB · Rust · last changed Grants let certified keys act for an author (keyless step 5a) 19 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
75167672 Andy McCall 662
    fn check_ref_attest(
663
        &self,
664
        sa: &SignedAttest,
665
        name: &str,
666
        old_state: &ObjectRef,
667
        new_state: &ObjectRef,
668
        last_serial: Option<u64>,
669
        allow_equal: bool,
670
    ) -> std::result::Result<u64, String> {
671
        let AttestBody::Ref {
672
            name: n,
673
            old_state: o,
674
            new_state: nw,
675
            serial,
676
        } = &sa.attest.body
677
        else {
98286406 Andy McCall ↶ 678
            return Err("attestation is not a ref attestation".into());
679
        };
680
        if n != name || o != old_state || nw != new_state {
681
            return Err("attestation does not describe this update".into());
682
        }
683
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
684
            return Err("attestation is for a different repository".into());
685
        }
686
        if let Some(last) = last_serial {
687
            if *serial < last || (*serial == last && !allow_equal) {
75167672 Andy McCall 688
                return Err(format!(
689
                    "attestation serial {serial} is not greater than the last seen {last}"
690
                ));
98286406 Andy McCall ↶ 691
            }
692
        }
693
        let r = sa.attest.hash();
694
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
75167672 Andy McCall 695
        let id = self
696
            .store
697
            .get_identity(&sig.key)
698
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
98286406 Andy McCall ↶ 699
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
700
        Ok(*serial)
701
    }
702
83e0677b Andy McCall ↶ 703
    /// Accept a push (spec §16.4). Without a trust policy every repository
98286406 Andy McCall ↶ 704
    /// is unverified, so unsigned changes and unattested updates are accepted;
83e0677b Andy McCall ↶ 705
    /// attestations that are present must still be valid. With a policy,
706
    /// every change and update is checked against it. A newer policy in the
707
    /// push is applied first when it is signed by the current roots.
75167672 Andy McCall 708
    pub fn receive_push(
709
        &self,
710
        bundle: Bundle,
711
        updates: Vec<RefUpdate>,
712
        policy: Option<SignedPolicy>,
713
        tags: Vec<crate::protocol::TagRef>,
714
    ) -> Result<Vec<RefResult>> {
119bbf50 Andy McCall ↶ 715
        Ok(self
716
            .receive_push_report(bundle, updates, policy, tags)?
717
            .results)
7aa2dc93 Andy McCall ↶ 718
    }
719
720
    /// `receive_push` with what a host wants to log: each accepted
721
    /// reference's old and new state and heads, and the changes this push
722
    /// stored (hub spec §6.12).
723
    pub fn receive_push_report(
724
        &self,
725
        bundle: Bundle,
726
        updates: Vec<RefUpdate>,
727
        policy: Option<SignedPolicy>,
728
        tags: Vec<crate::protocol::TagRef>,
729
    ) -> Result<PushReport> {
730
        let mut report = PushReport::default();
731
        let results = &mut report.results;
83e0677b Andy McCall ↶ 732
        if let Some(sp) = policy {
28fc23d7 Andy McCall ↶ 733
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
83e0677b Andy McCall ↶ 734
                Ok(()) => {
75167672 Andy McCall 735
                    results.push(RefResult {
736
                        name: "policy".into(),
737
                        ok: true,
738
                        reason: format!("serial {}", sp.policy.serial),
739
                    });
83e0677b Andy McCall ↶ 740
                }
741
                Err(e) => {
75167672 Andy McCall 742
                    results.push(RefResult {
743
                        name: "policy".into(),
744
                        ok: false,
745
                        reason: e,
746
                    });
83e0677b Andy McCall ↶ 747
                    for u in updates {
75167672 Andy McCall 748
                        results.push(RefResult {
749
                            name: u.name,
750
                            ok: false,
751
                            reason: "policy update was rejected".into(),
752
                        });
83e0677b Andy McCall ↶ 753
                    }
7aa2dc93 Andy McCall ↶ 754
                    return Ok(report);
83e0677b Andy McCall ↶ 755
                }
756
            }
757
        }
758
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
cb8b8082 Andy McCall ↶ 759
        // A push of objects alone (one batch of a long history, oxygen#95)
760
        // names no reference: its outcome is reported as `objects`.
761
        let objects_only = updates.is_empty() && tags.is_empty();
7aa2dc93 Andy McCall ↶ 762
        match self.import_bundle(&bundle, policy.is_some()) {
cb8b8082 Andy McCall ↶ 763
            Ok(imported) => {
764
                if objects_only {
765
                    results.push(RefResult {
766
                        name: OBJECTS_RESULT.into(),
767
                        ok: true,
768
                        reason: format!("{} changes stored", imported.len()),
769
                    });
770
                }
771
                report.imported = imported;
772
            }
7aa2dc93 Andy McCall ↶ 773
            Err(e) => {
cb8b8082 Andy McCall ↶ 774
                if objects_only {
775
                    results.push(RefResult {
776
                        name: OBJECTS_RESULT.into(),
777
                        ok: false,
778
                        reason: e.to_string(),
779
                    });
780
                }
7aa2dc93 Andy McCall ↶ 781
                for u in updates {
782
                    results.push(RefResult {
783
                        name: u.name,
784
                        ok: false,
785
                        reason: e.to_string(),
786
                    });
787
                }
788
                return Ok(report);
83e0677b Andy McCall ↶ 789
            }
790
        }
98286406 Andy McCall ↶ 791
        let (op_ref, op) = self.head_op()?;
792
        let mut view = op.view.clone();
793
        let mut names = Vec::new();
794
        for u in updates {
83e0677b Andy McCall ↶ 795
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
98286406 Andy McCall ↶ 796
            let (ok, reason) = match outcome {
797
                Ok(()) => (true, String::new()),
798
                Err(e) => (false, e),
799
            };
800
            if ok {
801
                names.push(u.name.clone());
119bbf50 Andy McCall ↶ 802
                let heads = self
803
                    .store
804
                    .get_state(&u.new_state)
805
                    .map(|s| s.heads)
806
                    .unwrap_or_default();
807
                report.updated.push(RefUpdated {
808
                    name: u.name.clone(),
809
                    old_state: u.old_state,
810
                    new_state: u.new_state,
811
                    heads,
812
                });
98286406 Andy McCall ↶ 813
            }
75167672 Andy McCall 814
            results.push(RefResult {
815
                name: u.name,
816
                ok,
817
                reason,
818
            });
98286406 Andy McCall ↶ 819
        }
132b884b Andy McCall ↶ 820
        for t in &tags {
821
            let name = format!("tags/{}", t.name);
822
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
823
                Ok(()) => {
824
                    names.push(name.clone());
75167672 Andy McCall 825
                    results.push(RefResult {
826
                        name,
827
                        ok: true,
828
                        reason: String::new(),
829
                    });
132b884b Andy McCall ↶ 830
                }
75167672 Andy McCall 831
                Err(e) => results.push(RefResult {
832
                    name,
833
                    ok: false,
834
                    reason: e,
835
                }),
132b884b Andy McCall ↶ 836
            }
837
        }
98286406 Andy McCall ↶ 838
        if !names.is_empty() {
75167672 Andy McCall 839
            self.record_op(
840
                &[op_ref],
841
                &format!("push received: {}", names.join(" ")),
842
                view,
843
            )?;
98286406 Andy McCall ↶ 844
        }
7aa2dc93 Andy McCall ↶ 845
        Ok(report)
98286406 Andy McCall ↶ 846
    }
847
be451356 Andy McCall ↶ 848
    /// Check an update's attestation against the latest one for its
849
    /// reference and store it as the new latest. Failures say what was
850
    /// being done, for which reference, so a refused push can be diagnosed
851
    /// from its reason alone.
852
    fn record_update_attest(
853
        &self,
854
        u: &RefUpdate,
855
        sa: &SignedAttest,
856
    ) -> std::result::Result<(), String> {
857
        let name = &u.name;
858
        let last = self
859
            .latest_ref_attest(name)
860
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
861
            .and_then(|(_, a)| match a.attest.body {
862
                AttestBody::Ref { serial, .. } => Some(serial),
863
                _ => None,
864
            });
865
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
866
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
867
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
868
        for sig in &sa.sigs {
869
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
f53cbe7a Andy McCall ↶ 870
        }
871
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
872
        // Signed by a short-lived key: a host records when it accepted it.
873
        let certified = sa
874
            .sigs
875
            .first()
876
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
877
        if certified {
878
            self.record_acceptance(&r).map_err(|e| store(&e))?;
be451356 Andy McCall ↶ 879
        }
f53cbe7a Andy McCall ↶ 880
        Ok(())
be451356 Andy McCall ↶ 881
    }
882
f53cbe7a Andy McCall ↶ 883
    /// Record that this host accepted attestation `r` now, signed with its
884
    /// acceptor key (spec §14.7); nothing without one.
885
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
886
        let Some(acceptor) = &self.acceptor else {
887
            return Ok(());
888
        };
889
        let (id, sk) = (&acceptor.0, &acceptor.1);
890
        let attest = Attest {
891
            repo: self.id()?,
892
            hlc: Hlc::now(),
893
            body: AttestBody::Accepted { attest: *r },
894
        };
895
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
896
        self.store.put_identity(id)?;
897
        let a = self.store.put_attest(&attest)?;
898
        self.store.put_signature(&a, &sig)?;
899
        self.store.index_add_pub("accepted", r, &a)?;
900
        Ok(())
901
    }
902
903
    /// The host's acceptance of attestation `r`, if one was recorded.
904
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
905
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
906
            return Ok(None);
907
        };
908
        Ok(Some(SignedAttest {
909
            attest: self.store.get_attest(&a)?,
910
            sigs: self.store.signatures(&a)?,
911
        }))
912
    }
913
914
    /// When a certified signer's attestation `sa` is checked on a fetch: the
915
    /// host's acceptance time, if `accepted` is signed by the issuer of the
916
    /// signer's certificate and accepts `sa`; else the attestation's own
917
    /// time, which the signer chose.
918
    pub(crate) fn certified_time(
919
        &self,
920
        signer: &KeyId,
921
        sa: &SignedAttest,
922
        accepted: Option<&SignedAttest>,
923
    ) -> u64 {
924
        let own = sa.attest.hlc.wall_ms;
925
        let Some(acc) = accepted else {
926
            return own;
927
        };
928
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
929
            return own;
930
        };
931
        let Ok(cert) = self.store.get_certificate(&c) else {
932
            return own;
933
        };
934
        let AttestBody::Accepted { attest } = &acc.attest.body else {
935
            return own;
936
        };
937
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
938
            return own;
939
        };
940
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
941
            return own;
942
        };
943
        if *attest == sa.attest.hash()
944
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
945
        {
946
            acc.attest.hlc.wall_ms
947
        } else {
948
            own
949
        }
950
    }
951
f8c69576 Andy McCall ↶ 952
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
8c30d814 Andy McCall ↶ 953
    /// at `old_state`, is never the bookmark a non-bare repository has
954
    /// checked out (a bare one's default is its host's to protect, see
955
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
956
    /// an attestation by a key that may update it.
f8c69576 Andy McCall ↶ 957
    /// The deletion's attestation stays the bookmark's latest, so an older
958
    /// one cannot be replayed to bring it back.
959
    fn apply_deletion(
960
        &self,
961
        view: &mut View,
962
        u: &RefUpdate,
963
        policy: Option<&crate::policy::Policy>,
964
    ) -> std::result::Result<(), String> {
965
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
966
            return Err(format!("no bookmark {:?} to delete", u.name));
967
        };
968
        if current != u.old_state {
969
            return Err("stale: the remote bookmark has moved; pull first".into());
970
        }
8c30d814 Andy McCall ↶ 971
        if !self.is_bare() && u.name == self.config.bookmark {
f8c69576 Andy McCall ↶ 972
            return Err(format!(
8c30d814 Andy McCall ↶ 973
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
f8c69576 Andy McCall ↶ 974
                u.name
975
            ));
976
        }
977
        if let Some(p) = policy {
978
            let Some(sa) = &u.attestation else {
979
                return Err(format!(
980
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
981
                    u.name
982
                ));
983
            };
984
            let signer = sa
985
                .sigs
986
                .first()
987
                .map(|s| s.key)
988
                .ok_or("attestation carries no signature")?;
f0a517d2 Andy McCall ↶ 989
            // Received now: the receiver's own clock is the trusted time.
990
            let now = Hlc::now().wall_ms;
7ba155f2 Andy McCall ↶ 991
            if !p.authorizes(&signer, &u.name)
992
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
f0a517d2 Andy McCall ↶ 993
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
7ba155f2 Andy McCall ↶ 994
            {
f8c69576 Andy McCall ↶ 995
                return Err(format!(
996
                    "key {} may not delete {:?} under this repository's policy",
997
                    signer.short(12),
998
                    u.name
999
                ));
1000
            }
1001
        }
1002
        if let Some(sa) = &u.attestation {
be451356 Andy McCall ↶ 1003
            self.record_update_attest(u, sa)?;
f8c69576 Andy McCall ↶ 1004
        }
1005
        view.bookmarks.remove(&u.name);
1006
        Ok(())
1007
    }
1008
75167672 Andy McCall 1009
    fn apply_update(
1010
        &self,
1011
        view: &mut View,
1012
        u: &RefUpdate,
1013
        policy: Option<&crate::policy::Policy>,
1014
    ) -> std::result::Result<(), String> {
83e0677b Andy McCall ↶ 1015
        if u.name == "policy" {
75167672 Andy McCall 1016
            return Err(
1017
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
1018
            );
83e0677b Andy McCall ↶ 1019
        }
75167672 Andy McCall 1020
        let empty = self
1021
            .store
1022
            .put_state(&StateObject::new(vec![]))
1023
            .map_err(|e| e.to_string())?;
f8c69576 Andy McCall ↶ 1024
        if u.new_state.is_zero() {
1025
            return self.apply_deletion(view, u, policy);
1026
        }
98286406 Andy McCall ↶ 1027
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1028
        if current != u.old_state {
1029
            return Err("stale: the remote bookmark has moved; pull first".into());
1030
        }
75167672 Andy McCall 1031
        let new_state = self
1032
            .store
1033
            .get_state(&u.new_state)
1034
            .map_err(|_| "new state object is missing".to_string())?;
98286406 Andy McCall ↶ 1035
        for h in &new_state.heads {
1036
            if !self.store.has(h) {
1037
                return Err(format!("head {} is missing", h.short(12)));
1038
            }
1039
        }
1040
        if !u.force {
75167672 Andy McCall 1041
            let old_heads = self
1042
                .store
1043
                .get_state(&current)
1044
                .map_err(|e| e.to_string())?
1045
                .heads;
1046
            let closure = self
1047
                .closure_in_store(&new_state.heads)
1048
                .map_err(|e| e.to_string())?;
98286406 Andy McCall ↶ 1049
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
75167672 Andy McCall 1050
                return Err(format!(
1051
                    "not a fast-forward: current head {} would be dropped (use --force)",
1052
                    h.short(12)
1053
                ));
98286406 Andy McCall ↶ 1054
            }
1055
        }
83e0677b Andy McCall ↶ 1056
        if let Some(p) = policy {
1057
            let Some(sa) = &u.attestation else {
75167672 Andy McCall 1058
                return Err(format!(
1059
                    "{:?} requires a signed reference attestation under this repository's policy",
1060
                    u.name
1061
                ));
83e0677b Andy McCall ↶ 1062
            };
75167672 Andy McCall 1063
            let signer = sa
1064
                .sigs
1065
                .first()
1066
                .map(|s| s.key)
1067
                .ok_or("attestation carries no signature")?;
f0a517d2 Andy McCall ↶ 1068
            // Received now: the receiver's own clock is the trusted time.
1069
            let now = Hlc::now().wall_ms;
7ba155f2 Andy McCall ↶ 1070
            if !p.authorizes(&signer, &u.name)
1071
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
f0a517d2 Andy McCall ↶ 1072
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
7ba155f2 Andy McCall ↶ 1073
            {
75167672 Andy McCall 1074
                return Err(format!(
1075
                    "key {} may not update {:?} under this repository's policy",
1076
                    signer.short(12),
1077
                    u.name
1078
                ));
83e0677b Andy McCall ↶ 1079
            }
75167672 Andy McCall 1080
            let old_heads = self
1081
                .store
1082
                .get_state(&current)
1083
                .map_err(|e| e.to_string())?
1084
                .heads;
83e0677b Andy McCall ↶ 1085
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1086
        }
98286406 Andy McCall ↶ 1087
        if let Some(sa) = &u.attestation {
be451356 Andy McCall ↶ 1088
            self.record_update_attest(u, sa)?;
98286406 Andy McCall ↶ 1089
        }
1090
        view.bookmarks.insert(u.name.clone(), u.new_state);
1091
        Ok(())
1092
    }
1093
1094
    // ------------------------------------------------------------ client side
1095
1096
    fn remote_url(&self, name: &str) -> Result<String> {
75167672 Andy McCall 1097
        self.config.remotes.get(name).cloned().ok_or_else(|| {
42ccf504 Andy McCall ↶ 1098
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
1099
            RepoError::Msg(match names.as_slice() {
1100
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
1101
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1102
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
1103
                    names.join(", "),
1104
                    names[0],
1105
                    names[0]
1106
                ),
1107
                _ => format!(
1108
                    "no remote named {name:?}; this repository has {}",
1109
                    names.join(", ")
1110
                ),
1111
            })
75167672 Andy McCall 1112
        })
98286406 Andy McCall ↶ 1113
    }
1114
75167672 Andy McCall 1115
    /// Refuse a remote that is another repository. An **unbound** remote
1116
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1117
    /// for pushes, which bind it to this repository's id (spec §16.1).
05e71ed6 Andy McCall ↶ 1118
    fn check_remote_id(
1119
        &self,
1120
        remote: &dyn crate::protocol::Remote,
1121
        remote_name: &str,
1122
        allow_unbound: bool,
1123
    ) -> Result<()> {
75167672 Andy McCall 1124
        let theirs = remote.repo_id()?;
1125
        if theirs == self.id()? {
1126
            return Ok(());
1127
        }
1128
        if theirs == crate::protocol::UNBOUND_ID {
1129
            if allow_unbound {
1130
                return Ok(());
1131
            }
05e71ed6 Andy McCall ↶ 1132
            return fail(format!(
1133
                "remote {remote_name:?} is empty and unbound: push to it first"
1134
            ));
75167672 Andy McCall 1135
        }
05e71ed6 Andy McCall ↶ 1136
        fail(format!(
3e5772cc Andy McCall ↶ 1137
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
05e71ed6 Andy McCall ↶ 1138
        ))
75167672 Andy McCall 1139
    }
1140
ff1f62fe Andy McCall ↶ 1141
    /// Credentials and trust for a remote: `remote.<name>.token` and
1142
    /// `remote.<name>.ca`, else the defaults for its URL
1143
    /// ([`Repo::fill_credentials`]).
3e5772cc Andy McCall ↶ 1144
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
ff1f62fe Andy McCall ↶ 1145
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
1146
        let mut options = RemoteOptions {
75167672 Andy McCall 1147
            repo_id: self.id().ok(),
ff1f62fe Andy McCall ↶ 1148
            token: self.config.remote_tokens.get(name).cloned(),
1149
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
9f9e72b9 Andy McCall ↶ 1150
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
68a92484 Andy McCall ↶ 1151
            ..RemoteOptions::default()
ff1f62fe Andy McCall ↶ 1152
        };
1153
        self.fill_credentials(&url, &mut options);
1154
        options
1155
    }
1156
1157
    /// The user's credential store (`credentials.toml` beside the user
1158
    /// configuration file).
1159
    pub fn credentials(&self) -> crate::credentials::Credentials {
1160
        crate::credentials::Credentials::at(
1161
            self.user_config
1162
                .parent()
1163
                .map(Path::to_path_buf)
1164
                .unwrap_or_else(default_home),
1165
        )
1166
    }
1167
1168
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1169
    /// then the user's credential store for its hub, then a remote on the
1170
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
68a92484 Andy McCall ↶ 1171
    /// When the token is not this remote's own or the environment's, the
1172
    /// other tokens enclosing checkouts hold for the hub are kept to try
1173
    /// if it is refused: a stale stored login must not hide a parent's
1174
    /// good token (oxygen#112).
ff1f62fe Andy McCall ↶ 1175
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
1176
        if options.token.is_some() && options.ca.is_some() {
1177
            return;
1178
        }
68a92484 Andy McCall ↶ 1179
        let explicit =
1180
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
ff1f62fe Andy McCall ↶ 1181
        let stored = self.credentials().options_for(url);
1182
        options.token = options.token.take().or(stored.token);
1183
        options.ca = options.ca.take().or(stored.ca);
68a92484 Andy McCall ↶ 1184
        let enclosing = self.enclosing_credentials(url);
1185
        if options.token.is_none() {
1186
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
1187
        }
1188
        if options.ca.is_none() {
1189
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
1190
        }
1191
        if !explicit {
1192
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
1193
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
1194
                    options.fallback_tokens.push(t);
1195
                }
1196
            }
2b5ee371 Andy McCall ↶ 1197
        }
68a92484 Andy McCall ↶ 1198
    }
1199
1200
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1201
    /// checkouts, nearest first.
1202
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
1203
        let mut out = Vec::new();
ff1f62fe Andy McCall ↶ 1204
        let Some(hub) = crate::credentials::hub_of(url) else {
68a92484 Andy McCall ↶ 1205
            return out;
ff1f62fe Andy McCall ↶ 1206
        };
1207
        let mut at = self.root.parent();
1208
        while let Some(dir) = at {
1209
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
1210
                break;
1211
            };
1212
            for (key, remote_url) in &cfg {
1213
                let Some(name) = key
1214
                    .strip_prefix("remote.")
1215
                    .and_then(|k| k.strip_suffix(".url"))
1216
                else {
1217
                    continue;
1218
                };
1219
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
1220
                    continue;
1221
                }
68a92484 Andy McCall ↶ 1222
                out.push((
1223
                    cfg.get(&format!("remote.{name}.token")).cloned(),
1224
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
1225
                ));
ff1f62fe Andy McCall ↶ 1226
            }
1227
            at = dir.parent();
1228
        }
68a92484 Andy McCall ↶ 1229
        out
98286406 Andy McCall ↶ 1230
    }
1231
d82e4409 Andy McCall ↶ 1232
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1233
    /// no changes and no reference updates, which the receiver stores.
1234
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
1235
        let remote = self.open_named_remote(remote_name)?;
1236
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1237
        let mut bundle = Bundle::default();
1238
        for r in seals {
1239
            let attest = self.store.get_attest(r)?;
1240
            let sigs = self.store.signatures(r)?;
4213c41d Andy McCall ↶ 1241
            bundle
1242
                .attests
1243
                .push(crate::protocol::SignedAttest { attest, sigs });
d82e4409 Andy McCall ↶ 1244
        }
1245
        let results = remote.push(bundle, vec![], None, vec![])?;
1246
        if let Some(r) = results.iter().find(|r| !r.ok) {
1247
            return fail(format!("{}: {}", r.name, r.reason));
1248
        }
1249
        Ok(())
1250
    }
1251
1252
    /// The remote whose URL starts with `base` (a hub), if configured.
1253
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
1254
        let base = base.trim_end_matches('/');
4213c41d Andy McCall ↶ 1255
        self.config
1256
            .remotes
1257
            .iter()
1258
            .find(|(_, url)| url.trim_end_matches('/') == base)
1259
            .map(|(name, _)| name.clone())
d82e4409 Andy McCall ↶ 1260
    }
1261
1262
    /// Open a remote by name or, failing that, by URL with the default
ff1f62fe Andy McCall ↶ 1263
    /// credentials (see [`Repo::credentials_for`]).
d82e4409 Andy McCall ↶ 1264
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
1265
        if let Some(name) = self.remote_for_url(url) {
1266
            return Ok((name.clone(), self.open_named_remote(&name)?));
1267
        }
1268
        let options = RemoteOptions {
1269
            repo_id: self.id().ok(),
ff1f62fe Andy McCall ↶ 1270
            ..self.credentials_for(url)
d82e4409 Andy McCall ↶ 1271
        };
1272
        Ok((url.to_string(), open_remote(url, &options)?))
1273
    }
1274
1275
    /// Credentials for a URL: those of the configured remote with that
1276
    /// URL, else the environment's.
1277
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
1278
        match self.remote_for_url(url) {
1279
            Some(name) => self.remote_options(&name),
1280
            None => RemoteOptions {
1281
                repo_id: self.id().ok(),
ff1f62fe Andy McCall ↶ 1282
                ..self.credentials_for(url)
d82e4409 Andy McCall ↶ 1283
            },
1284
        }
1285
    }
1286
98286406 Andy McCall ↶ 1287
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
2b5ee371 Andy McCall ↶ 1288
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
98286406 Andy McCall ↶ 1289
    }
1290
1291
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
75167672 Andy McCall 1292
        self.oxy
1293
            .join("remotes")
1294
            .join(remote)
1295
            .join(format!("{bookmark}.serial"))
98286406 Andy McCall ↶ 1296
    }
1297
1298
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
75167672 Andy McCall 1299
        fs::read_to_string(self.serial_path(remote, bookmark))
1300
            .ok()
1301
            .and_then(|s| s.trim().parse().ok())
98286406 Andy McCall ↶ 1302
    }
1303
1304
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1305
        let p = self.serial_path(remote, bookmark);
1306
        fs::create_dir_all(p.parent().unwrap())?;
1307
        write_atomic(&p, serial.to_string().as_bytes())
1308
    }
1309
83e0677b Andy McCall ↶ 1310
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1311
        self.oxy.join("remotes").join(remote).join("policy.serial")
1312
    }
1313
1314
    /// The highest policy serial `remote` has ever presented.
1315
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
75167672 Andy McCall 1316
        fs::read_to_string(self.policy_serial_path(remote))
1317
            .ok()
1318
            .and_then(|s| s.trim().parse().ok())
83e0677b Andy McCall ↶ 1319
    }
1320
1321
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
1322
        let p = self.policy_serial_path(remote);
1323
        fs::create_dir_all(p.parent().unwrap())?;
1324
        write_atomic(&p, serial.to_string().as_bytes())
1325
    }
1326
b3c5a59a Andy McCall ↶ 1327
    fn lazy_dir(&self) -> PathBuf {
1328
        self.oxy.join("lazy")
1329
    }
1330
1331
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
1332
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
1333
        fs::create_dir_all(self.lazy_dir())?;
1334
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
1335
    }
1336
1337
    /// Which remote promised an absent blob, if any.
1338
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
75167672 Andy McCall 1339
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
1340
            .ok()
1341
            .map(|s| s.trim().to_string())
b3c5a59a Andy McCall ↶ 1342
    }
1343
1344
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
1345
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
1346
        let Some(remote_name) = self.lazy_remote(blob) else {
1347
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1348
        };
1349
        let remote = self.open_named_remote(&remote_name)?;
1350
        let objects = remote.objects(&[*blob])?;
1351
        for (ty, body) in objects {
1352
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
1353
                self.store.put(ty, &body)?;
1354
            }
1355
        }
1356
        if !self.store.has(blob) {
75167672 Andy McCall 1357
            return fail(format!(
1358
                "{remote_name} did not send blob {}",
1359
                blob.short(12)
1360
            ));
b3c5a59a Andy McCall ↶ 1361
        }
1362
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
1363
        Ok(())
1364
    }
1365
1366
    /// After importing from `remote`, record every blob the changes reference
1367
    /// that the store lacks as lazily available from that remote.
1368
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
1369
        let mut n = 0;
1370
        for h in changes {
1371
            let c = self.store.get_change(h)?;
1372
            for e in &c.edits {
1373
                if let Edit::Replace { old, new, .. } = e {
1374
                    for b in [old, new].into_iter().flatten() {
1375
                        if !self.store.has(b) {
1376
                            self.register_lazy(b, remote)?;
1377
                            n += 1;
1378
                        }
1379
                    }
1380
                }
1381
            }
1382
        }
1383
        Ok(n)
1384
    }
1385
98286406 Andy McCall ↶ 1386
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
d82e4409 Andy McCall ↶ 1387
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
98286406 Andy McCall ↶ 1388
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
75167672 Andy McCall 1389
        for st in view
1390
            .bookmarks
1391
            .values()
1392
            .chain(view.remotes.values().flat_map(|b| b.values()))
1393
        {
98286406 Andy McCall ↶ 1394
            if let Ok(s) = self.store.get_state(st) {
1395
                have.extend(s.heads);
1396
            }
1397
        }
1398
        have.extend(view.workspaces.values().copied());
1399
        Ok(have.into_iter().collect())
1400
    }
1401
1402
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
83e0677b Andy McCall ↶ 1403
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
98286406 Andy McCall ↶ 1404
        let remote = self.open_named_remote(remote_name)?;
75167672 Andy McCall 1405
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
83e0677b Andy McCall ↶ 1406
        let resp = remote.refs()?;
1407
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1408
        // and signed by roots we trust, or on first contact. A remote that
1409
        // once presented a policy may never present none or an older one:
1410
        // that is a downgrade. A remote that never presented one is
1411
        // unverified, and this fetch is checked only as far as possible.
1412
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1413
        let seen = self.remote_policy_serial(remote_name);
1414
        let mut unverified = false;
1415
        match &resp.policy {
1416
            Some(sp) => {
1417
                if seen.is_some_and(|s| sp.policy.serial < s) {
1418
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
1419
                }
1420
                match &local_policy {
1421
                    Some(l) if sp.policy.serial < l.serial => {}
1422
                    Some(l) if sp.policy.serial == l.serial => {
1423
                        if sp.policy.hash() != l.hash() {
75167672 Andy McCall 1424
                            return fail(format!(
1425
                                "{remote_name} presents a different policy with the same serial {}",
1426
                                l.serial
1427
                            ));
83e0677b Andy McCall ↶ 1428
                        }
1429
                    }
28fc23d7 Andy McCall ↶ 1430
                    _ => {
75167672 Andy McCall 1431
                        self.adopt_policy_chain(
1432
                            &resp.history,
1433
                            sp,
1434
                            &format!("oxy fetch {remote_name}"),
1435
                        )
1436
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
83e0677b Andy McCall ↶ 1437
                    }
1438
                }
1439
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1440
            }
1441
            None => {
1442
                if seen.is_some() {
1443
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1444
                }
1445
                unverified = true;
1446
            }
1447
        }
75167672 Andy McCall 1448
        let policy = if unverified {
1449
            None
1450
        } else {
1451
            self.current_policy()?.map(|(_, sp)| sp.policy)
1452
        };
98286406 Andy McCall ↶ 1453
        let (op_ref, op) = self.head_op()?;
1454
        let mut view = op.view.clone();
1455
        let have = self.known_heads(&view)?;
1456
        let mut report = Vec::new();
b3c5a59a Andy McCall ↶ 1457
        let max_blob = self.config.max_blob;
83e0677b Andy McCall ↶ 1458
        for r in resp.refs {
091fef80 Andy McCall ↶ 1459
            let needed = {
1460
                let _t = crate::timing::phase("fetch: negotiate");
1461
                remote.negotiate(&have, &r.heads)?
1462
            };
1463
            let bundle = {
1464
                let _t = crate::timing::phase("fetch: bundle");
1465
                remote.fetch(&needed, max_blob)?
1466
            };
83e0677b Andy McCall ↶ 1467
            // Changes are not individually re-verified here: the bookmark's
1468
            // attestation (checked below) binds its whole state, and the
1469
            // receiver of the push verified the added changes at that time.
091fef80 Andy McCall ↶ 1470
            let imported = {
1471
                let _t = crate::timing::phase("fetch: import");
1472
                self.import_bundle(&bundle, false)?
1473
            };
b3c5a59a Andy McCall ↶ 1474
            if max_blob.is_some() {
1475
                self.register_missing_blobs(&imported, remote_name)?;
1476
            }
98286406 Andy McCall ↶ 1477
            for h in &r.heads {
1478
                if !self.store.has(h) {
1479
                    return fail(format!("remote did not send head {}", h.short(12)));
1480
                }
1481
            }
1482
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1483
            if state != r.state {
75167672 Andy McCall 1484
                return fail(format!(
1485
                    "remote state {} does not match its heads",
1486
                    r.state.short(12)
1487
                ));
98286406 Andy McCall ↶ 1488
            }
83e0677b Andy McCall ↶ 1489
            if let Some(p) = &policy {
1490
                let Some(sa) = &r.attestation else {
75167672 Andy McCall 1491
                    return fail(format!(
1492
                        "{remote_name}/{} has no attestation, which its policy requires",
1493
                        r.name
1494
                    ));
83e0677b Andy McCall ↶ 1495
                };
75167672 Andy McCall 1496
                let signer = sa
1497
                    .sigs
1498
                    .first()
1499
                    .map(|s| s.key)
1500
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
f53cbe7a Andy McCall ↶ 1501
                // A certified signer is checked at the host's acceptance,
1502
                // when it countersigned one; else at the attestation's time.
1503
                let at = self.certified_time(&signer, sa, r.accepted.as_ref());
7ba155f2 Andy McCall ↶ 1504
                if !p.authorizes(&signer, &r.name)
1505
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
f53cbe7a Andy McCall ↶ 1506
                    && !self.certified_authorized(p, &signer, &r.name, Scope::REFS, at)
3526d339 Andy McCall ↶ 1507
                {
75167672 Andy McCall 1508
                    return fail(format!(
3e5772cc Andy McCall ↶ 1509
                        "{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 1510
                        r.name,
1511
                        signer.short(12)
1512
                    ));
83e0677b Andy McCall ↶ 1513
                }
1514
            }
98286406 Andy McCall ↶ 1515
            if let Some(sa) = &r.attestation {
75167672 Andy McCall 1516
                let AttestBody::Ref {
1517
                    old_state,
1518
                    new_state,
1519
                    ..
1520
                } = &sa.attest.body
1521
                else {
98286406 Andy McCall ↶ 1522
                    return fail("remote sent a non-ref attestation for a bookmark");
1523
                };
1524
                let (old_state, new_state) = (*old_state, *new_state);
1525
                let serial = self
75167672 Andy McCall 1526
                    .check_ref_attest(
1527
                        sa,
1528
                        &r.name,
1529
                        &old_state,
1530
                        &new_state,
1531
                        self.last_seen_serial(remote_name, &r.name),
1532
                        true,
1533
                    )
1534
                    .map_err(|e| {
1535
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
1536
                    })?;
98286406 Andy McCall ↶ 1537
                if new_state != r.state {
75167672 Andy McCall 1538
                    return fail(format!(
1539
                        "attestation for {}/{} does not cover its current state",
1540
                        remote_name, r.name
1541
                    ));
98286406 Andy McCall ↶ 1542
                }
1543
                let ar = self.store.put_attest(&sa.attest)?;
1544
                for sig in &sa.sigs {
1545
                    self.store.put_signature(&ar, sig)?;
1546
                }
1547
                self.record_serial(remote_name, &r.name, serial)?;
1548
            }
75167672 Andy McCall 1549
            view.remotes
1550
                .entry(remote_name.to_string())
1551
                .or_default()
1552
                .insert(r.name.clone(), state);
98286406 Andy McCall ↶ 1553
            report.push((r.name, r.heads, imported.len()));
1554
        }
132b884b Andy McCall ↶ 1555
        let mut new_tags = 0;
1556
        for t in &resp.tags {
1557
            if view.tags.contains_key(&t.name) {
1558
                continue;
1559
            }
1560
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
75167672 Andy McCall 1561
            let missing: Vec<ChangeHash> = t
1562
                .heads
1563
                .iter()
1564
                .filter(|h| !self.store.has(h))
1565
                .copied()
1566
                .collect();
132b884b Andy McCall ↶ 1567
            if !missing.is_empty() {
1568
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1569
                let bundle = remote.fetch(&needed, max_blob)?;
1570
                self.import_bundle(&bundle, false)?;
1571
            }
1572
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
75167672 Andy McCall 1573
            self.adopt_tag(&mut view, t, policy.as_ref())
1574
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
132b884b Andy McCall ↶ 1575
            new_tags += 1;
1576
        }
98286406 Andy McCall ↶ 1577
        if view != op.view {
1578
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1579
        }
6d3eefbc Andy McCall ↶ 1580
        let _ = self.run_hook(
1581
            "post-fetch",
1582
            &format!(
1583
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1584
                json_str(remote_name),
75167672 Andy McCall 1585
                json_array(report.iter().map(|(n, heads, _)| format!(
1586
                    "{{\"name\":{},\"heads\":{}}}",
1587
                    json_str(n),
1588
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1589
                )))
6d3eefbc Andy McCall ↶ 1590
            ),
1591
        );
75167672 Andy McCall 1592
        Ok(FetchReport {
1593
            refs: report,
1594
            unverified,
1595
            new_tags,
1596
        })
98286406 Andy McCall ↶ 1597
    }
1598
2863456a Andy McCall ↶ 1599
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1600
    /// the changes within `depth` steps of its heads, and the boundary below.
1601
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1602
        let remote = self.open_named_remote(remote_name)?;
75167672 Andy McCall 1603
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
2863456a Andy McCall ↶ 1604
        let resp = remote.refs()?;
1605
        let bookmark = self.config.bookmark.clone();
1606
        if let Some(sp) = &resp.policy {
75167672 Andy McCall 1607
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1608
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
2863456a Andy McCall ↶ 1609
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1610
        }
1611
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1612
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1613
        };
1614
        if r.heads.is_empty() {
1615
            return Ok(0);
1616
        }
1617
        // Base: the remote's checkpoint of exactly these heads.
1618
        let cp_bundle = remote.checkpoint(&r.heads)?;
1619
        let mut cp_ref = None;
1620
        for (ty, body) in &cp_bundle.objects {
1621
            let put = self.store.put(*ty, body)?;
1622
            if *ty == ObjectType::Checkpoint {
1623
                cp_ref = Some(put);
1624
            }
1625
        }
75167672 Andy McCall 1626
        let Some(cp_ref) = cp_ref else {
1627
            return fail(format!("{remote_name} sent no checkpoint"));
1628
        };
2863456a Andy McCall ↶ 1629
        self.install_checkpoint(&bookmark, &cp_ref)?;
1630
        // History window.
1631
        let wanted = remote.shallow(&r.heads, depth)?;
1632
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1633
        let imported = self.import_bundle_shallow(&bundle, false)?;
1634
        if self.config.max_blob.is_some() {
1635
            self.register_missing_blobs(&imported, remote_name)?;
1636
        }
1637
        self.refresh_boundary(&imported)?;
1638
        if let Some(sa) = &r.attestation {
1639
            let ar = self.store.put_attest(&sa.attest)?;
1640
            for sig in &sa.sigs {
1641
                self.store.put_signature(&ar, sig)?;
1642
            }
1643
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1644
                self.record_serial(remote_name, &r.name, serial)?;
1645
            }
1646
        }
1647
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1648
        let (op_ref, op) = self.head_op()?;
1649
        let mut view = op.view.clone();
75167672 Andy McCall 1650
        view.remotes
1651
            .entry(remote_name.to_string())
1652
            .or_default()
1653
            .insert(r.name.clone(), state);
1654
        self.record_op(
1655
            &[op_ref],
1656
            &format!("oxy fetch {remote_name} --depth {depth}"),
1657
            view,
1658
        )?;
2863456a Andy McCall ↶ 1659
        Ok(imported.len())
1660
    }
1661
98286406 Andy McCall ↶ 1662
    /// Fetch, then take the union of the local bookmark's state with the
1663
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1664
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
6caacfff Andy McCall ↶ 1665
        let _wc = self.lock_working_copy()?;
98286406 Andy McCall ↶ 1666
        self.fetch(remote_name)?;
1667
        let (op_ref, op) = self.head_op()?;
14edbaaf Andy McCall ↶ 1668
        let current = self.config.bookmark.clone();
1669
        let mut local_current = self.heads_of(&op.view, &current)?;
1670
        local_current.sort();
1671
        let mut view = op.view.clone();
1672
        let mut current_heads = local_current.clone();
1673
        let mut changed = false;
1674
        let mut others = Vec::new();
1675
        let tracked = op
75167672 Andy McCall 1676
            .view
1677
            .remotes
1678
            .get(remote_name)
14edbaaf Andy McCall ↶ 1679
            .cloned()
1680
            .unwrap_or_default();
1681
        for (name, remote_state) in tracked {
1682
            // Every local bookmark tracks the remote's of the same name;
1683
            // the current one may be new here.
1684
            let local_state = op.view.bookmarks.get(&name).copied();
1685
            if local_state.is_none() && name != current {
1686
                continue;
1687
            }
1688
            if local_state == Some(remote_state) {
1689
                continue;
1690
            }
1691
            let local = self.heads_of(&op.view, &name)?;
1692
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1693
            if remote_heads.iter().all(|h| local.contains(h)) {
1694
                continue;
1695
            }
1696
            let mut all = local.clone();
1697
            all.extend(remote_heads);
1698
            let st = self.load_state_history(&all)?;
1699
            let mut heads = st.maximal(&all);
1700
            heads.sort();
1701
            let mut sorted_local = local;
1702
            sorted_local.sort();
1703
            if heads == sorted_local {
1704
                continue;
1705
            }
1706
            view.bookmarks.insert(
1707
                name.clone(),
1708
                self.store.put_state(&StateObject::new(heads.clone()))?,
1709
            );
1710
            if name == current {
1711
                changed = true;
1712
                current_heads = heads;
1713
            } else {
1714
                others.push(name);
1715
            }
1716
        }
f6dccc45 Andy McCall ↶ 1717
        if changed || !others.is_empty() {
1718
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
98286406 Andy McCall ↶ 1719
        }
f6dccc45 Andy McCall ↶ 1720
        // The working copy follows its bookmark whenever nothing would be
1721
        // lost, also when this pull brought nothing new but it had been
1722
        // left behind (oxygen#89).
1723
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
75167672 Andy McCall 1724
        Ok(PullReport {
f6dccc45 Andy McCall ↶ 1725
            heads: if changed {
1726
                current_heads
1727
            } else {
1728
                local_current
1729
            },
14edbaaf Andy McCall ↶ 1730
            changed,
75167672 Andy McCall 1731
            checked_out,
14edbaaf Andy McCall ↶ 1732
            others,
75167672 Andy McCall 1733
        })
f6dccc45 Andy McCall ↶ 1734
    }
1735
1736
    /// How many changes the working copy's bookmark has that its base
1737
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1738
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1739
    /// the bookmark or holds changes the bookmark lacks. History is read
1740
    /// only when the base and the bookmark's heads differ (oxygen#89).
1741
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
1742
        let (_, wc) = self.working_copy()?;
1743
        let mut base = wc.deps.clone();
1744
        base.sort();
1745
        let mut heads = self.bookmark_heads()?;
1746
        heads.sort();
1747
        if base == heads || heads.is_empty() {
1748
            return Ok(None);
1749
        }
1750
        let state = self.load_state_history(&heads)?;
1751
        if !base.iter().all(|h| state.contains(h)) {
1752
            return Ok(None);
1753
        }
1754
        let had = if base.is_empty() {
1755
            0
1756
        } else {
1757
            self.load_state_history(&base)?.len()
1758
        };
1759
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
1760
    }
1761
1762
    /// Bring the working copy to `heads`, the state of its bookmark
1763
    /// `bookmark`, when nothing would be lost: its base is part of that
1764
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1765
    /// with uncommitted work, the work comes along when the new changes
1766
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1767
    /// it followed only from exactly the bookmark's old heads, so a working
1768
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1769
    /// or a pull from another workspace) never caught up, and nothing said
1770
    /// so (oxygen#74, #89). Returns whether it moved.
1771
    pub fn follow_bookmark(
1772
        &self,
1773
        heads: &[ChangeHash],
1774
        bookmark: &str,
1775
        command: &str,
1776
    ) -> Result<bool> {
1777
        let snap = self.snapshot(command)?;
1778
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1779
        let mut base = snap.base.maximal(&snap.wc.deps);
1780
        base.sort();
1781
        let mut target = heads.to_vec();
1782
        target.sort();
1783
        if base == target {
1784
            return Ok(false);
1785
        }
1786
        let state = self.load_state_history(heads)?;
1787
        if !base.iter().all(|h| state.contains(h)) {
1788
            // The working copy holds changes the bookmark lacks: not ours to move.
1789
            return Ok(false);
1790
        }
1791
        if clean {
1792
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
1793
            Ok(true)
1794
        } else {
1795
            Ok(self
1796
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
1797
                .is_ok())
1798
        }
98286406 Andy McCall ↶ 1799
    }
1800
1801
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1802
    /// changes and attesting the reference when a key is available.
f8c69576 Andy McCall ↶ 1803
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1804
    /// state, attested when we have an identity. The local bookmark, if
1805
    /// any, is kept; only the remote-tracking entry goes.
1806
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
1807
        let remote = self.open_named_remote(remote_name)?;
1808
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1809
        let resp = remote.refs()?;
1810
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
1811
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1812
        };
1813
        if resp.policy.is_some() && self.secret_key()?.is_none() {
1814
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
1815
        }
1816
        let attestation = match self.secret_key()? {
1817
            Some(_) => Some(self.sign_attest(&Attest {
1818
                repo: self.id()?,
1819
                hlc: Hlc::now(),
1820
                body: AttestBody::Ref {
1821
                    name: bookmark.to_string(),
1822
                    old_state: r.state,
1823
                    new_state: ObjectRef::ZERO,
1824
                    serial: r.last_serial.unwrap_or(0) + 1,
1825
                },
1826
            })?),
1827
            None => None,
1828
        };
1829
        let results = remote.push(
1830
            Bundle::default(),
1831
            vec![RefUpdate {
1832
                name: bookmark.to_string(),
1833
                old_state: r.state,
1834
                new_state: ObjectRef::ZERO,
1835
                force: true,
1836
                attestation,
1837
            }],
1838
            None,
1839
            vec![],
1840
        )?;
1841
        if results.iter().any(|x| x.ok && x.name == bookmark) {
1842
            let (op_ref, op) = self.head_op()?;
1843
            let mut view = op.view.clone();
1844
            if let Some(m) = view.remotes.get_mut(remote_name) {
1845
                m.remove(bookmark);
1846
            }
1847
            self.record_op(
1848
                &[op_ref],
1849
                &format!("oxy push {remote_name} --delete {bookmark}"),
1850
                view,
1851
            )?;
1852
        }
1853
        Ok(results)
1854
    }
1855
34fad4a9 Andy McCall ↶ 1856
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1857
    /// repository's config (its URL, token, CA and store settings), its
1858
    /// tracking bookmarks in the view, and a store remote's mirror under
1859
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
1860
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
1861
        if !self.config.remotes.contains_key(name) {
1862
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
1863
        }
1864
        let prefix = format!("remote.{name}.");
1865
        let keys: Vec<String> = self
1866
            .config
1867
            .repo_layer()
1868
            .keys()
1869
            .filter(|k| k.starts_with(&prefix))
1870
            .cloned()
1871
            .collect();
1872
        for k in keys {
1873
            self.config.set(&k, "")?;
1874
        }
1875
        self.config.remotes.remove(name);
1876
        self.save_config()?;
1877
        let (op_ref, op) = self.head_op()?;
1878
        if op.view.remotes.contains_key(name) {
1879
            let mut view = op.view.clone();
1880
            view.remotes.remove(name);
1881
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
1882
        }
1883
        let mirror = self.oxy.join("remotes").join(name);
1884
        if mirror.is_dir() {
1885
            fs::remove_dir_all(&mirror)?;
1886
        }
1887
        Ok(())
1888
    }
1889
cb8b8082 Andy McCall ↶ 1890
    /// `changes`, in dependency order, cut into batches of about
1891
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1892
    /// There is always one, perhaps empty.
1893
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1894
        let blob_len = |r: &ObjectRef| -> u64 {
1895
            self.store
1896
                .get_typed(r, ObjectType::Blob)
1897
                .ok()
1898
                .and_then(|b| Blob::decode(&b).ok())
1899
                .map_or(0, |b| b.length)
1900
        };
1901
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1902
        for h in changes {
1903
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1904
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1905
            let mut weight = raw.len() as u64;
1906
            for t in &texts {
1907
                if let crate::objects::TextRef::Blob(r, _, _) = t {
1908
                    weight += blob_len(r);
1909
                }
1910
            }
1911
            for e in &c.edits {
1912
                if let Edit::Replace { new: Some(b), .. } = e {
1913
                    weight += blob_len(b);
1914
                }
1915
            }
1916
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
1917
                out.push(std::mem::take(&mut batch));
1918
                bytes = 0;
1919
            }
1920
            batch.push(*h);
1921
            bytes += weight;
1922
        }
1923
        out.push(batch);
1924
        Ok(out)
1925
    }
1926
98286406 Andy McCall ↶ 1927
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
6d3eefbc Andy McCall ↶ 1928
        let bookmark = self.config.bookmark.clone();
7b9809e6 Andy McCall ↶ 1929
        self.push_bookmark(remote_name, &bookmark, force)
1930
    }
1931
1932
    /// `push` for a named bookmark (`oxy push -b NAME`).
75167672 Andy McCall 1933
    pub fn push_bookmark(
cb8b8082 Andy McCall ↶ 1934
        &self,
1935
        remote_name: &str,
1936
        bookmark: &str,
1937
        force: bool,
1938
    ) -> Result<Vec<RefResult>> {
1939
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1940
    }
1941
1942
    /// `push_bookmark`, saying how a long push is going: one line per
1943
    /// batch sent (oxygen#95).
1944
    pub fn push_bookmark_with(
75167672 Andy McCall 1945
        &self,
1946
        remote_name: &str,
1947
        bookmark: &str,
1948
        force: bool,
cb8b8082 Andy McCall ↶ 1949
        progress: crate::store::Progress,
75167672 Andy McCall 1950
    ) -> Result<Vec<RefResult>> {
7b9809e6 Andy McCall ↶ 1951
        let (op_ref, op) = self.head_op()?;
1952
        if !op.view.bookmarks.contains_key(bookmark) {
1953
            return fail(format!("no bookmark {bookmark}"));
1954
        }
1955
        let bookmark = bookmark.to_string();
6d3eefbc Andy McCall ↶ 1956
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1957
        // pre-push hook: may veto before the remote is contacted.
1958
        self.run_hook(
1959
            "pre-push",
75167672 Andy McCall 1960
            &format!(
1961
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1962
                json_str(remote_name),
1963
                json_str(&bookmark),
1964
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1965
            ),
6d3eefbc Andy McCall ↶ 1966
        )?;
98286406 Andy McCall ↶ 1967
        let remote = self.open_named_remote(remote_name)?;
75167672 Andy McCall 1968
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
83e0677b Andy McCall ↶ 1969
        let resp = remote.refs()?;
1970
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
28fc23d7 Andy McCall ↶ 1971
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
83e0677b Andy McCall ↶ 1972
        let policy_to_send = match (&local_policy, &resp.policy) {
1973
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1974
            (Some(l), None) => Some(l.clone()),
1975
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
75167672 Andy McCall 1976
                return fail(format!(
1977
                    "{remote_name} has a newer policy (serial {}); fetch first",
1978
                    r.policy.serial
1979
                ));
83e0677b Andy McCall ↶ 1980
            }
1981
            _ => None,
1982
        };
1983
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1984
        if remote_has_policy && self.secret_key()?.is_none() {
1985
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1986
        }
132b884b Andy McCall ↶ 1987
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
75167672 Andy McCall 1988
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1989
            .tag_refs()?
1990
            .into_iter()
1991
            .filter(|t| !remote_tags.contains(&t.name))
1992
            .collect();
83e0677b Andy McCall ↶ 1993
        let refs = resp.refs;
98286406 Andy McCall ↶ 1994
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
75167672 Andy McCall 1995
        let (remote_state, remote_heads, last_serial) =
1996
            match refs.iter().find(|r| r.name == bookmark) {
1997
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1998
                None => (empty, vec![], None),
1999
            };
2000
        let new_state = self
2001
            .store
2002
            .put_state(&StateObject::new(local_heads.clone()))?;
83e0677b Andy McCall ↶ 2003
        // A push that carries a policy re-attests the bookmark even when its
2004
        // state is unchanged, so the current attestation is always by a key
2005
        // the current policy authorizes (a revoked key's attestation would
2006
        // otherwise be refused by every later fetch).
132b884b Andy McCall ↶ 2007
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
75167672 Andy McCall 2008
            return Ok(vec![RefResult {
2009
                name: bookmark,
2010
                ok: true,
2011
                reason: "already up to date".into(),
2012
            }]);
98286406 Andy McCall ↶ 2013
        }
2014
        for h in &remote_heads {
2015
            if !self.store.has(h) {
75167672 Andy McCall 2016
                return fail(format!(
3e5772cc Andy McCall ↶ 2017
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
75167672 Andy McCall 2018
                    h.short(12)
2019
                ));
98286406 Andy McCall ↶ 2020
            }
2021
        }
2022
        if !force {
2023
            let closure = self.closure_in_store(&local_heads)?;
2024
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
2025
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2026
            }
2027
        }
2028
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2029
        let key = self.secret_key()?.map(|(k, _)| k);
2030
        if let Some(key) = key {
05e71ed6 Andy McCall ↶ 2031
            // Seal this author's changes that carry no valid authenticator,
cb8b8082 Andy McCall ↶ 2032
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2033
            // are stored, so each batch's bundle carries those it needs.
98286406 Andy McCall ↶ 2034
            let mut unsigned = Vec::new();
2035
            for h in &to_send {
cb8b8082 Andy McCall ↶ 2036
                let c = self.store.get_change_meta(h)?;
a2387d54 Andy McCall ↶ 2037
                if self.seals_for_author(&c.author, &key)
75167672 Andy McCall 2038
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
2039
                {
98286406 Andy McCall ↶ 2040
                    unsigned.push(*h);
2041
                }
2042
            }
2043
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
cb8b8082 Andy McCall ↶ 2044
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
98286406 Andy McCall ↶ 2045
            }
cb8b8082 Andy McCall ↶ 2046
        }
2047
        // A long history goes in batches, in dependency order, so neither
2048
        // side holds it whole and no request passes the remote's limit:
2049
        // all but the last carry objects alone; the last moves the bookmark
2050
        // (oxygen#95).
2051
        let batches = self.push_batches(&to_send)?;
2052
        let (last, earlier) = batches.split_last().expect("at least one batch");
2053
        for (i, batch) in earlier.iter().enumerate() {
2054
            progress(&format!(
2055
                "part {} of {}: {} changes",
2056
                i + 1,
2057
                batches.len(),
2058
                batch.len()
2059
            ));
2060
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
2061
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
2062
                Some(r) if r.ok => {}
2063
                Some(r) => {
2064
                    return fail(format!(
2065
                        "{remote_name} refused part {} of the push: {}",
2066
                        i + 1,
2067
                        r.reason
2068
                    ))
2069
                }
2070
                None => {
2071
                    return fail(format!(
2072
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2073
                    ))
2074
                }
2075
            }
2076
        }
2077
        if batches.len() > 1 {
2078
            progress(&format!(
2079
                "part {} of {}: {} changes",
2080
                batches.len(),
2081
                batches.len(),
2082
                last.len()
2083
            ));
98286406 Andy McCall ↶ 2084
        }
cb8b8082 Andy McCall ↶ 2085
        let mut bundle = self.bundle_for(last)?;
75167672 Andy McCall 2086
        bundle.objects.push((
2087
            ObjectType::State,
2088
            StateObject::new(local_heads.clone()).encode(),
2089
        ));
98286406 Andy McCall ↶ 2090
        let attestation = match key {
2091
            Some(_) => Some(self.sign_attest(&Attest {
2092
                repo: self.id()?,
2093
                hlc: Hlc::now(),
75167672 Andy McCall 2094
                body: AttestBody::Ref {
2095
                    name: bookmark.clone(),
2096
                    old_state: remote_state,
2097
                    new_state,
f8c69576 Andy McCall ↶ 2098
                    serial: next_serial(last_serial),
75167672 Andy McCall 2099
                },
98286406 Andy McCall ↶ 2100
            })?),
2101
            None => None,
2102
        };
68a92484 Andy McCall ↶ 2103
        // Whoever signed the move, and whom a delegate acts for, travel with
2104
        // it: a receiver that has never seen a change by this delegate could
2105
        // not otherwise check its signature (oxygenhub#129).
2106
        if attestation.is_some() {
2107
            for k in [self.signing_key(), self.config.author_key]
2108
                .into_iter()
2109
                .flatten()
2110
            {
2111
                if let Ok(id) = self.identity(&k) {
2112
                    let body = id.encode();
2113
                    if !bundle
2114
                        .objects
2115
                        .iter()
2116
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
2117
                    {
2118
                        bundle.objects.push((ObjectType::Identity, body));
2119
                    }
2120
                }
2121
            }
f0a517d2 Andy McCall ↶ 2122
            // A short-lived signing key's certificate goes with it (§14.7).
2123
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
2124
            self.attach_certificates_for(&mut bundle, &signers)?;
68a92484 Andy McCall ↶ 2125
        }
98286406 Andy McCall ↶ 2126
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
2127
            AttestBody::Ref { serial, .. } => Some(serial),
2128
            _ => None,
2129
        });
83e0677b Andy McCall ↶ 2130
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
132b884b Andy McCall ↶ 2131
        // Tag states must be present on the remote: bundle their changes too.
2132
        for t in &tags_to_send {
2133
            let extra = self.negotiate(&remote_heads, &t.heads)?;
75167672 Andy McCall 2134
            let extra: Vec<ChangeHash> =
2135
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
132b884b Andy McCall ↶ 2136
            if !extra.is_empty() {
2137
                let more = self.bundle_for(&extra)?;
2138
                bundle.changes.extend(more.changes);
2c75672f Andy McCall ↶ 2139
                bundle.hashes.extend(more.hashes);
132b884b Andy McCall ↶ 2140
                bundle.attests.extend(more.attests);
2141
                bundle.objects.extend(more.objects);
2142
            }
75167672 Andy McCall 2143
            bundle.objects.push((
2144
                ObjectType::State,
2145
                StateObject::new(t.heads.clone()).encode(),
2146
            ));
132b884b Andy McCall ↶ 2147
        }
28fc23d7 Andy McCall ↶ 2148
        if let Some(l) = &policy_to_send {
2149
            let remote_serial = resp_policy_serial;
75167672 Andy McCall 2150
            bundle.policies = self
2151
                .policy_history()?
2152
                .into_iter()
2153
                .filter(|sp| {
2154
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
2155
                        && sp.policy.serial < l.policy.serial
2156
                })
2157
                .collect();
28fc23d7 Andy McCall ↶ 2158
        }
75167672 Andy McCall 2159
        let results = remote.push(
2160
            bundle,
2161
            vec![RefUpdate {
2162
                name: bookmark.clone(),
2163
                old_state: remote_state,
2164
                new_state,
2165
                force,
2166
                attestation,
2167
            }],
2168
            policy_to_send,
2169
            tags_to_send,
2170
        )?;
2171
        if let (Some(serial), true) = (
2172
            sent_serial,
2173
            results.iter().any(|r| r.ok && r.name == "policy"),
2174
        ) {
83e0677b Andy McCall ↶ 2175
            self.record_policy_serial(remote_name, serial)?;
2176
        }
2177
        if results.iter().any(|r| r.ok && r.name == bookmark) {
98286406 Andy McCall ↶ 2178
            let mut view = op.view.clone();
75167672 Andy McCall 2179
            view.remotes
2180
                .entry(remote_name.to_string())
2181
                .or_default()
2182
                .insert(bookmark.clone(), new_state);
98286406 Andy McCall ↶ 2183
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2184
            if let Some(s) = serial {
2185
                self.record_serial(remote_name, &bookmark, s)?;
2186
            }
2187
        }
2188
        Ok(results)
2189
    }
2190
2191
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2192
    /// bookmark set to the remote's, working copy checked out.
2193
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
7421309f Andy McCall ↶ 2194
        Self::clone_with(url, dest, None, &[])
b3c5a59a Andy McCall ↶ 2195
    }
2196
7421309f Andy McCall ↶ 2197
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2198
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2199
    /// unless a size is given, so out-of-scope binaries are never fetched).
75167672 Andy McCall 2200
    pub fn clone_with(
2201
        url: &str,
2202
        dest: &Path,
2203
        max_blob: Option<u64>,
2204
        sparse: &[String],
2205
    ) -> Result<Repo> {
2863456a Andy McCall ↶ 2206
        Self::clone_full(url, dest, max_blob, sparse, None)
2207
    }
2208
2209
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2210
    /// changes within `depth` steps of them; the rest is the boundary.
75167672 Andy McCall 2211
    pub fn clone_shallow(
2212
        url: &str,
2213
        dest: &Path,
2214
        depth: u32,
2215
        max_blob: Option<u64>,
2216
        sparse: &[String],
2217
    ) -> Result<Repo> {
2863456a Andy McCall ↶ 2218
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
2219
    }
2220
75167672 Andy McCall 2221
    fn clone_full(
2222
        url: &str,
2223
        dest: &Path,
2224
        max_blob: Option<u64>,
2225
        sparse: &[String],
2226
        depth: Option<u32>,
2227
    ) -> Result<Repo> {
ff1f62fe Andy McCall ↶ 2228
        let options = crate::credentials::Credentials::user().options_for(url);
2229
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
a07f60a3 Andy McCall ↶ 2230
    }
2231
ff1f62fe Andy McCall ↶ 2232
    /// Clone a subrepo with the credentials the parent would use for its
2233
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2234
    /// subrepo: it finds the same ones again through its parent.
a07f60a3 Andy McCall ↶ 2235
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
2236
        let options = self.credentials_for(url);
ff1f62fe Andy McCall ↶ 2237
        Self::clone_using(url, dest, None, &[], None, &options)
a07f60a3 Andy McCall ↶ 2238
    }
2239
2240
    /// The name of a remote of this repository on the same hub (scheme,
2241
    /// host and port) as `url`.
2242
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
2243
        let origin = |u: &str| -> Option<String> {
2244
            let (scheme, rest) = u.split_once("://")?;
9f9e72b9 Andy McCall ↶ 2245
            if !matches!(scheme, "http" | "https") {
2246
                return None;
2247
            }
a07f60a3 Andy McCall ↶ 2248
            let host = rest.split('/').next()?;
2249
            Some(format!(
2250
                "{}://{}",
2251
                scheme.to_ascii_lowercase(),
2252
                host.to_ascii_lowercase()
2253
            ))
2254
        };
2255
        let want = origin(url)?;
2256
        self.config
2257
            .remotes
2258
            .iter()
2259
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
2260
            .map(|(name, _)| name.clone())
2261
    }
2262
2263
    /// The token and CA to reach `url` with: those of a remote of this
2264
    /// repository on the same hub (scheme, host and port), else the
ff1f62fe Andy McCall ↶ 2265
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2266
    /// and enclosing checkouts', as a clone would use them.
a07f60a3 Andy McCall ↶ 2267
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
2268
        match self.remote_on_same_hub(url) {
2269
            Some(name) => RemoteOptions {
2270
                repo_id: None,
9f9e72b9 Andy McCall ↶ 2271
                cache_dir: None,
a07f60a3 Andy McCall ↶ 2272
                ..self.remote_options(&name)
2273
            },
ff1f62fe Andy McCall ↶ 2274
            None => {
2275
                let mut options = RemoteOptions::default();
2276
                self.fill_credentials(url, &mut options);
2277
                options
2278
            }
a07f60a3 Andy McCall ↶ 2279
        }
2280
    }
2281
2282
    fn clone_using(
2283
        url: &str,
2284
        dest: &Path,
2285
        max_blob: Option<u64>,
2286
        sparse: &[String],
2287
        depth: Option<u32>,
2288
        options: &RemoteOptions,
2289
    ) -> Result<Repo> {
2290
        let remote = open_remote(url, options)?;
98286406 Andy McCall ↶ 2291
        let id = remote.repo_id()?;
75167672 Andy McCall 2292
        if id == crate::protocol::UNBOUND_ID {
05e71ed6 Andy McCall ↶ 2293
            return fail(format!(
2294
                "{url} is empty and unbound: push a repository to it first"
2295
            ));
75167672 Andy McCall 2296
        }
98286406 Andy McCall ↶ 2297
        let mut repo = Repo::init_with_id(dest, id)?;
827281ee Andy McCall ↶ 2298
        repo.config
2299
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
b3c5a59a Andy McCall ↶ 2300
        if let Some(m) = max_blob {
2301
            repo.config.set("filter.max-blob", &m.to_string())?;
7421309f Andy McCall ↶ 2302
        } else if !sparse.is_empty() {
2303
            repo.config.set("filter.max-blob", "0")?;
2304
        }
2305
        if !sparse.is_empty() {
2306
            repo.config.set("filter.paths", &sparse.join(","))?;
b3c5a59a Andy McCall ↶ 2307
        }
98286406 Andy McCall ↶ 2308
        repo.save_config()?;
2863456a Andy McCall ↶ 2309
        if let Some(depth) = depth {
2310
            repo.fetch_shallow("origin", depth)?;
2311
        } else {
2312
            repo.fetch("origin")?;
2313
        }
98286406 Andy McCall ↶ 2314
        let (op_ref, op) = repo.head_op()?;
14edbaaf Andy McCall ↶ 2315
        // The remote's default bookmark, else ours (main), else its only one.
2316
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
9f9e72b9 Andy McCall ↶ 2317
        // Asked of the remote as now configured, so a store-backed one
2318
        // answers from the mirror the fetch just filled.
2319
        let advertised = repo
2320
            .open_named_remote("origin")
2321
            .ok()
2322
            .and_then(|r| r.refs().ok())
2323
            .and_then(|r| r.default_bookmark);
14edbaaf Andy McCall ↶ 2324
        let bookmark = advertised
2325
            .filter(|b| theirs.contains_key(b))
2326
            .or_else(|| {
2327
                theirs
2328
                    .contains_key(&repo.config.bookmark)
2329
                    .then(|| repo.config.bookmark.clone())
2330
            })
2331
            .or_else(|| {
2332
                (theirs.len() == 1)
2333
                    .then(|| theirs.keys().next().cloned())
2334
                    .flatten()
2335
            })
2336
            .unwrap_or_else(|| repo.config.bookmark.clone());
2337
        let initial = repo.config.bookmark.clone();
2338
        if bookmark != repo.config.bookmark {
2339
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
2340
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
2341
            repo.config.bookmark = bookmark.clone();
2342
        }
2343
        if let Some(state) = theirs.get(&bookmark).copied() {
98286406 Andy McCall ↶ 2344
            let heads = repo.store.get_state(&state)?.heads;
2345
            let mut view = op.view.clone();
14edbaaf Andy McCall ↶ 2346
            // The empty bookmark `init` made goes when another is checked out.
2347
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
2348
                view.bookmarks.remove(&initial);
2349
            }
98286406 Andy McCall ↶ 2350
            view.bookmarks.insert(bookmark, state);
2351
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2352
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
2353
        }
2354
        Ok(repo)
f8c69576 Andy McCall ↶ 2355
    }
2356
}
2357
2358
/// The serial of a reference's next attestation: one more than the last the
2359
/// remote reports, or, for a bookmark the remote does not have, the clock in
2360
/// milliseconds, so a bookmark created again after a deletion goes past the
2361
/// deletion's serial the remote keeps.
2362
fn next_serial(last: Option<u64>) -> u64 {
2363
    match last {
2364
        Some(l) => l + 1,
2365
        None => Hlc::now().wall_ms.max(1),
98286406 Andy McCall ↶ 2366
    }
2367
}