OXYGENHUB
# 098227d48b1a oxygen / crates / oxy-core / src / repo / hosted.rs
26.1 KiB · Rust · last changed Scoped, expiring delegates, and revocation by the delegator 1 month ago source blame history raw
1
//! What a host (a hub) does to a repository without a workspace (hub spec
2
//! §6.9, §7.6): build a change from an edit set on any state, sign a
3
//! reference update with a key it holds, and apply both through the same
4
//! validation a received push gets. Nothing here bypasses policy.
5
6
use super::*;
7
use crate::identity::SecretKey;
8
9
/// One file of an edit set: new content, or `None` to remove the path.
10
#[derive(Clone, Debug, PartialEq, Eq)]
11
pub struct FileEdit {
12
    pub path: String,
13
    pub content: Option<Vec<u8>>,
14
}
15
16
impl Repo {
17
    /// Build (but do not store or sign) a change that turns the state with
18
    /// `heads` into that state with `edits` applied, authored by `author`.
19
    /// Files the edits do not name keep their content, conflict markers
20
    /// included, so an edit that removes a file's markers resolves that
21
    /// file's conflict (a resolution change, spec §9.6).
22
    pub fn build_change(
23
        &self,
24
        heads: &[ChangeHash],
25
        edits: &[FileEdit],
26
        message: &str,
27
        author: KeyId,
28
    ) -> Result<Change> {
29
        if message.trim().is_empty() {
30
            return fail("a change message is required");
31
        }
32
        if edits.is_empty() {
33
            return fail("nothing to change");
34
        }
35
        let base = self.load_state(heads)?;
36
        let base_snapshot = base.materialize();
37
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
38
        for (path, f) in &base_snapshot.files {
39
            let entry = match (&f.kind, &f.content) {
40
                (NodeKind::Dir, _) | (_, FileContent::Dir) => continue,
41
                (kind, FileContent::Text { bytes, .. }) => {
42
                    FsEntry::new(*kind, f.mode.exec, bytes.clone())
43
                }
44
                (kind, FileContent::Opaque { blobs }) => FsEntry {
45
                    blob: blobs.first().copied(),
46
                    ..FsEntry::new(*kind, f.mode.exec, vec![])
47
                },
48
            };
49
            entries.insert(path.clone(), entry);
50
        }
51
        for e in edits {
52
            let path = e.path.trim_matches('/');
53
            if path.is_empty()
54
                || path
55
                    .split('/')
56
                    .any(|c| c.is_empty() || c == "." || c == ".." || c == OXY_DIR)
57
            {
58
                return fail(format!("{:?} is not a valid path", e.path));
59
            }
60
            match &e.content {
61
                Some(bytes) => {
62
                    let exec = entries.get(path).map(|x| x.exec).unwrap_or(false);
63
                    // A file cannot sit where a directory is, or inside a file.
64
                    if base_snapshot
65
                        .files
66
                        .get(path)
67
                        .is_some_and(|f| f.kind == NodeKind::Dir)
68
                    {
69
                        return fail(format!("{path} is a directory"));
70
                    }
71
                    let mut parent = path;
72
                    while let Some((p, _)) = parent.rsplit_once('/') {
73
                        if base_snapshot
74
                            .files
75
                            .get(p)
76
                            .is_some_and(|f| f.kind != NodeKind::Dir)
77
                        {
78
                            return fail(format!("{p} is a file, not a directory"));
79
                        }
80
                        parent = p;
81
                    }
82
                    entries.insert(
83
                        path.to_string(),
84
                        FsEntry::new(NodeKind::File, exec, bytes.clone()),
85
                    );
86
                }
87
                None => {
88
                    if entries.remove(path).is_none() {
89
                        // Removing a directory removes everything below it.
90
                        let prefix = format!("{path}/");
91
                        let before = entries.len();
92
                        entries.retain(|p, _| !p.starts_with(&prefix));
93
                        if entries.len() == before {
94
                            return fail(format!("{path} does not exist"));
95
                        }
96
                    }
97
                }
98
            }
99
        }
100
        // A path the user writes settles its replace conflict, if any: they
101
        // chose that content (spec §9.3).
102
        let written: std::collections::HashSet<String> = edits
103
            .iter()
104
            .filter(|e| e.content.is_some())
105
            .map(|e| e.path.trim_matches('/').to_string())
106
            .collect();
107
        let built = self.build_from_entries_resolving(
108
            &base,
109
            &base_snapshot,
110
            HashMap::new(),
111
            &entries,
112
            &written,
113
        )?;
114
        if let Some(s) = built
115
            .statuses
116
            .iter()
117
            .find(|s| s.status == ChangeStatus::ConflictEdited)
118
        {
119
            return fail(format!("{} still contains conflict markers", s.path));
120
        }
121
        if built.tree_ops.is_empty() && built.edits.is_empty() {
122
            return fail("the edits change nothing");
123
        }
124
        let mut change = Change {
125
            change_id: ChangeId::random(),
126
            deps: vec![],
127
            author,
128
            hlc: Hlc::now(),
129
            message: message.trim_end().to_string(),
130
            tree_ops: built.tree_ops,
131
            edits: built.edits,
132
            kind: if built.resolves {
133
                ChangeKind::Resolution
134
            } else {
135
                ChangeKind::Normal
136
            },
137
        };
138
        let mut deps: BTreeSet<ChangeHash> = referenced_changes(&change, &base);
139
        deps.extend(built.contributors.iter().copied());
140
        change.deps = deps.into_iter().collect();
141
        change.normalize();
142
        Ok(change)
143
    }
144
145
    /// A reference update of `bookmark` to `heads`, attested by `signer`
146
    /// when given (the attestation a push would carry, spec §14.4).
147
    pub fn host_ref_update(
148
        &self,
149
        bookmark: &str,
150
        heads: &[ChangeHash],
151
        signer: Option<(&KeyId, &SecretKey)>,
152
    ) -> Result<RefUpdate> {
153
        let view = self.view()?;
154
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
155
        let old_state = view.bookmarks.get(bookmark).copied().unwrap_or(empty);
156
        let new_state = self.store.put_state(&StateObject::new(heads.to_vec()))?;
157
        let attestation = match signer {
158
            Some((key, sk)) => {
159
                let serial = self
160
                    .latest_ref_attest(bookmark)?
161
                    .and_then(|(_, a)| match a.attest.body {
162
                        AttestBody::Ref { serial, .. } => Some(serial),
163
                        _ => None,
164
                    })
165
                    .map(|s| s + 1)
166
                    .unwrap_or(1);
167
                let attest = Attest {
168
                    repo: self.id()?,
169
                    hlc: Hlc::now(),
170
                    body: AttestBody::Ref {
171
                        name: bookmark.to_string(),
172
                        old_state,
173
                        new_state,
174
                        serial,
175
                    },
176
                };
177
                let r = attest.hash();
178
                let sig = sk.sign(Domain::Attest, key, &r);
179
                Some(SignedAttest {
180
                    attest,
181
                    sigs: vec![sig],
182
                })
183
            }
184
            None => None,
185
        };
186
        Ok(RefUpdate {
187
            name: bookmark.to_string(),
188
            old_state,
189
            new_state,
190
            force: false,
191
            attestation,
192
        })
193
    }
194
195
    /// Apply a host-made update as if it had been pushed: the new change
196
    /// (with its signatures) if any, the identities it needs, and the
197
    /// reference update, all through `receive_push_report`, so the same
198
    /// authentication, compare-and-swap and policy checks apply.
199
    pub fn apply_hosted(
200
        &self,
201
        change: Option<(Change, Vec<Signature>)>,
202
        identities: &[Identity],
203
        update: RefUpdate,
204
    ) -> Result<PushReport> {
205
        let mut bundle = Bundle::default();
206
        for id in identities {
207
            bundle.objects.push((ObjectType::Identity, id.encode()));
208
        }
209
        if let Ok(st) = self.store.get_state(&update.new_state) {
210
            bundle.objects.push((ObjectType::State, st.encode()));
211
        }
212
        if let Some((c, sigs)) = change {
213
            bundle.changes.push((c, sigs));
214
        }
215
        self.receive_push_report(bundle, vec![update], None, vec![])
216
    }
217
}
218
219
#[cfg(test)]
220
mod tests {
221
    use super::*;
222
    use crate::identity::SecretKey;
223
224
    fn hermetic() {
225
        static ONCE: std::sync::Once = std::sync::Once::new();
226
        static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
227
        ONCE.call_once(|| {
228
            let d = tempfile::tempdir().unwrap();
229
            std::env::set_var("OXY_HOME", d.path());
230
            DIR.set(d).ok();
231
        });
232
    }
233
234
    fn write(root: &Path, rel: &str, content: &[u8]) {
235
        let p = root.join(rel);
236
        fs::create_dir_all(p.parent().unwrap()).unwrap();
237
        fs::write(p, content).unwrap();
238
    }
239
240
    /// A user repository pushed to a bare host, and a hub key the user
241
    /// has delegated to. Returns (host, user, hub key, hub secret).
242
    fn setup(
243
        root: &Path,
244
        with_policy: bool,
245
        delegate: bool,
246
    ) -> (Repo, Repo, KeyId, SecretKey, Identity) {
247
        hermetic();
248
        let host_dir = root.join("host");
249
        Repo::init_bare_unbound(&host_dir).unwrap();
250
        let work = root.join("work");
251
        let mut user = Repo::init(&work).unwrap();
252
        user.create_identity("Andy", "[email protected]", IdentityScope::Repo)
253
            .unwrap();
254
        user.config.set("core.sign", "change").unwrap();
255
        user.config
256
            .set("remote.origin.url", host_dir.to_str().unwrap())
257
            .unwrap();
258
        user.save_config().unwrap();
259
        let hub_sk = SecretKey::generate();
260
        let hub_id = hub_sk.identity("Hub", "hub@example", 1);
261
        let hub_key = hub_id.hash();
262
        if with_policy {
263
            user.policy_init().unwrap();
264
        }
265
        if delegate {
266
            user.delegate_add(hub_id.clone(), Scope::CHANGES | Scope::REFS, None)
267
                .unwrap();
268
        }
269
        write(&work, "a.txt", b"one\ntwo\n");
270
        user.snapshot("t").unwrap();
271
        user.commit("first", &[]).unwrap();
272
        let r = user.push("origin", false).unwrap();
273
        assert!(r.iter().all(|x| x.ok), "{r:?}");
274
        (
275
            Repo::open(&host_dir).unwrap(),
276
            user,
277
            hub_key,
278
            hub_sk,
279
            hub_id,
280
        )
281
    }
282
283
    #[test]
284
    fn a_host_edit_signed_by_a_delegate_lands() {
285
        let dir = tempfile::tempdir().unwrap();
286
        let (host, user, hub_key, hub_sk, hub_id) = setup(dir.path(), false, true);
287
        let author = user.config.author_key.unwrap();
288
        let heads = host.bookmark_heads().unwrap();
289
        let change = host
290
            .build_change(
291
                &heads,
292
                &[
293
                    FileEdit {
294
                        path: "a.txt".into(),
295
                        content: Some(b"one\ntwo\nthree\n".to_vec()),
296
                    },
297
                    FileEdit {
298
                        path: "docs/new.md".into(),
299
                        content: Some(b"# New\n".to_vec()),
300
                    },
301
                ],
302
                "Edit on the web",
303
                author,
304
            )
305
            .unwrap();
306
        assert_eq!(change.author, author);
307
        assert_eq!(change.kind, ChangeKind::Normal);
308
        let hash = change.hash();
309
        let sig = hub_sk.sign(Domain::Change, &hub_key, &hash);
310
        let mut new_heads = heads.clone();
311
        new_heads.push(hash);
312
        let update = host
313
            .host_ref_update("main", &[hash], Some((&hub_key, &hub_sk)))
314
            .unwrap();
315
        let ids = vec![hub_id, user.identity(&author).unwrap()];
316
        let report = host
317
            .apply_hosted(Some((change, vec![sig])), &ids, update)
318
            .unwrap();
319
        assert!(report.results.iter().all(|r| r.ok), "{:?}", report.results);
320
        assert_eq!(host.bookmark_heads().unwrap(), vec![hash]);
321
        assert_eq!(
322
            host.file_at("a.txt", Some(&[hash])).unwrap(),
323
            b"one\ntwo\nthree\n"
324
        );
325
        assert_eq!(
326
            host.file_at("docs/new.md", Some(&[hash])).unwrap(),
327
            b"# New\n"
328
        );
329
        // Authored by the user, authenticated by the hub key as delegate.
330
        assert!(
331
            matches!(host.authenticate_change(&hash).unwrap(), SignatureStatus::Valid { key, name, .. } if key == hub_key && name == "Hub")
332
        );
333
        let _ = new_heads;
334
        // Bad paths and empty edits are refused.
335
        assert!(host
336
            .build_change(
337
                &[hash],
338
                &[FileEdit {
339
                    path: "../x".into(),
340
                    content: Some(vec![])
341
                }],
342
                "m",
343
                author
344
            )
345
            .is_err());
346
        assert!(
347
            host.build_change(
348
                &[hash],
349
                &[FileEdit {
350
                    path: "a.txt".into(),
351
                    content: Some(b"one\ntwo\nthree\n".to_vec())
352
                }],
353
                "m",
354
                author
355
            )
356
            .is_err(),
357
            "no-op edits are refused"
358
        );
359
        assert!(
360
            host.build_change(
361
                &[hash],
362
                &[FileEdit {
363
                    path: "a.txt/b".into(),
364
                    content: Some(vec![])
365
                }],
366
                "m",
367
                author
368
            )
369
            .is_err(),
370
            "a file inside a file"
371
        );
372
        let rm = host
373
            .build_change(
374
                &[hash],
375
                &[FileEdit {
376
                    path: "docs".into(),
377
                    content: None,
378
                }],
379
                "Remove docs",
380
                author,
381
            )
382
            .unwrap();
383
        assert!(!rm.tree_ops.is_empty());
384
    }
385
386
    #[test]
387
    fn a_host_edit_by_a_key_that_is_not_a_delegate_is_refused() {
388
        let dir = tempfile::tempdir().unwrap();
389
        let (host, user, hub_key, hub_sk, hub_id) = setup(dir.path(), false, false);
390
        let author = user.config.author_key.unwrap();
391
        let heads = host.bookmark_heads().unwrap();
392
        let change = host
393
            .build_change(
394
                &heads,
395
                &[FileEdit {
396
                    path: "a.txt".into(),
397
                    content: Some(b"x\n".to_vec()),
398
                }],
399
                "Edit",
400
                author,
401
            )
402
            .unwrap();
403
        let hash = change.hash();
404
        let sig = hub_sk.sign(Domain::Change, &hub_key, &hash);
405
        let update = host
406
            .host_ref_update("main", &[hash], Some((&hub_key, &hub_sk)))
407
            .unwrap();
408
        let report = host
409
            .apply_hosted(
410
                Some((change, vec![sig])),
411
                &[hub_id, user.identity(&author).unwrap()],
412
                update,
413
            )
414
            .unwrap();
415
        // Without a policy the host accepts unauthenticated changes, but the
416
        // signature does not verify as the author's: it stays unauthenticated.
417
        assert!(report.results.iter().all(|r| r.ok));
418
        assert!(
419
            matches!(host.authenticate_change(&hash).unwrap(), SignatureStatus::Invalid(why) if why.contains("neither the author"))
420
        );
421
    }
422
423
    #[test]
424
    fn under_a_policy_a_delegate_may_update_the_reference_and_a_stranger_may_not() {
425
        let dir = tempfile::tempdir().unwrap();
426
        let (host, user, hub_key, hub_sk, hub_id) = setup(dir.path(), true, true);
427
        assert!(host.current_policy().unwrap().is_some());
428
        let author = user.config.author_key.unwrap();
429
        let heads = host.bookmark_heads().unwrap();
430
        let change = host
431
            .build_change(
432
                &heads,
433
                &[FileEdit {
434
                    path: "a.txt".into(),
435
                    content: Some(b"one\n".to_vec()),
436
                }],
437
                "Trim",
438
                author,
439
            )
440
            .unwrap();
441
        let hash = change.hash();
442
        let sig = hub_sk.sign(Domain::Change, &hub_key, &hash);
443
        let ids = vec![hub_id.clone(), user.identity(&author).unwrap()];
444
        let update = host
445
            .host_ref_update("main", &[hash], Some((&hub_key, &hub_sk)))
446
            .unwrap();
447
        let report = host
448
            .apply_hosted(Some((change, vec![sig])), &ids, update)
449
            .unwrap();
450
        assert!(report.results.iter().all(|r| r.ok), "{:?}", report.results);
451
        assert_eq!(host.bookmark_heads().unwrap(), vec![hash]);
452
453
        // A stranger's key cannot move the reference, even with the user as author.
454
        let stranger = SecretKey::generate();
455
        let sid = stranger.identity("Mallory", "m@example", 1);
456
        let skey = sid.hash();
457
        let change2 = host
458
            .build_change(
459
                &[hash],
460
                &[FileEdit {
461
                    path: "a.txt".into(),
462
                    content: Some(b"evil\n".to_vec()),
463
                }],
464
                "Evil",
465
                author,
466
            )
467
            .unwrap();
468
        let h2 = change2.hash();
469
        let sig2 = stranger.sign(Domain::Change, &skey, &h2);
470
        let update = host
471
            .host_ref_update("main", &[h2], Some((&skey, &stranger)))
472
            .unwrap();
473
        let report = host
474
            .apply_hosted(Some((change2, vec![sig2])), &[sid], update)
475
            .unwrap();
476
        assert!(report.results.iter().all(|r| !r.ok), "{:?}", report.results);
477
        assert_eq!(
478
            host.bookmark_heads().unwrap(),
479
            vec![hash],
480
            "the reference did not move"
481
        );
482
        // An unsigned update is refused under a policy too.
483
        let update = host.host_ref_update("main", &[hash], None).unwrap();
484
        let report = host.apply_hosted(None, &[], update).unwrap();
485
        assert!(report.results.iter().all(|r| !r.ok));
486
    }
487
488
    /// Agent doc §2: an agent's key signs changes for its owner and nothing
489
    /// more. Its reference attestation is refused even though its owner's
490
    /// would pass, and a seal it makes authenticates nothing.
491
    #[test]
492
    fn a_changes_only_delegate_signs_changes_but_cannot_seal_or_move_a_reference() {
493
        let dir = tempfile::tempdir().unwrap();
494
        let (host, mut user, _, _, _) = setup(dir.path(), true, false);
495
        let agent_sk = SecretKey::generate();
496
        let agent_id = agent_sk.identity("aider on a laptop", "agent@example", 1);
497
        let agent = agent_id.hash();
498
        user.delegate_add(agent_id.clone(), Scope::CHANGES, None)
499
            .unwrap();
500
        // The successor identity reaches the host with the rotated policy.
501
        assert!(user.push("origin", false).unwrap().iter().all(|x| x.ok));
502
        let author = user.config.author_key.unwrap();
503
        let ids = vec![agent_id.clone(), user.identity(&author).unwrap()];
504
        let heads = host.bookmark_heads().unwrap();
505
        let change = host
506
            .build_change(
507
                &heads,
508
                &[FileEdit {
509
                    path: "a.txt".into(),
510
                    content: Some(b"by the agent\n".to_vec()),
511
                }],
512
                "Agent edit",
513
                author,
514
            )
515
            .unwrap();
516
        let hash = change.hash();
517
        let sig = agent_sk.sign(Domain::Change, &agent, &hash);
518
        // Attested by the agent: refused, the reference stays.
519
        let update = host
520
            .host_ref_update("main", &[hash], Some((&agent, &agent_sk)))
521
            .unwrap();
522
        let report = host
523
            .apply_hosted(Some((change.clone(), vec![sig.clone()])), &ids, update)
524
            .unwrap();
525
        assert!(report.results.iter().all(|r| !r.ok), "{:?}", report.results);
526
        assert_eq!(host.bookmark_heads().unwrap(), heads);
527
        // Attested by the owner: the agent-signed change lands.
528
        let (owner, owner_sk) = user.secret_key().unwrap().unwrap();
529
        let update = host
530
            .host_ref_update("main", &[hash], Some((&owner, &owner_sk)))
531
            .unwrap();
532
        let report = host
533
            .apply_hosted(Some((change, vec![sig])), &ids, update)
534
            .unwrap();
535
        assert!(report.results.iter().all(|r| r.ok), "{:?}", report.results);
536
        assert_eq!(host.bookmark_heads().unwrap(), vec![hash]);
537
        assert!(matches!(
538
            host.authenticate_change(&hash).unwrap(),
539
            SignatureStatus::Valid { key, sealed: false, .. } if key == agent
540
        ));
541
        // A seal by the agent is outside its scope.
542
        let change2 = host
543
            .build_change(
544
                &[hash],
545
                &[FileEdit {
546
                    path: "a.txt".into(),
547
                    content: Some(b"sealed by the agent\n".to_vec()),
548
                }],
549
                "Sealed",
550
                author,
551
            )
552
            .unwrap();
553
        let h2 = host.store().put_change(&change2).unwrap();
554
        let seal = host
555
            .store()
556
            .put_attest(&Attest::seal(host.id().unwrap(), vec![h2]))
557
            .unwrap();
558
        host.store()
559
            .put_signature(&seal, &agent_sk.sign(Domain::Attest, &agent, &seal))
560
            .unwrap();
561
        host.store().index_seal(&h2, &seal).unwrap();
562
        assert!(matches!(
563
            host.authenticate_change(&h2).unwrap(),
564
            SignatureStatus::Invalid(e) if e.contains("may not seal")
565
        ));
566
    }
567
568
    /// A delegation past its expiry authenticates nothing made after it,
569
    /// and the delegator may revoke the key; a stranger's key, they may not.
570
    #[test]
571
    fn an_expired_delegation_is_refused_and_the_delegator_may_revoke() {
572
        let dir = tempfile::tempdir().unwrap();
573
        let (_, mut user, _, _, _) = setup(dir.path(), false, false);
574
        let agent_sk = SecretKey::generate();
575
        let agent_id = agent_sk.identity("agent", "agent@example", 1);
576
        let agent = agent_id.hash();
577
        let yesterday = Hlc::now().wall_ms - 24 * 3600 * 1000;
578
        user.delegate_add(agent_id, Scope::CHANGES, Some(yesterday))
579
            .unwrap();
580
        user.config.set("core.sign", "seal").unwrap();
581
        user.save_config().unwrap();
582
        write(&dir.path().join("work"), "a.txt", b"later\n");
583
        user.snapshot("t").unwrap();
584
        let h = user.commit("after the delegation ended", &[]).unwrap();
585
        user.store()
586
            .put_signature(&h, &agent_sk.sign(Domain::Change, &agent, &h))
587
            .unwrap();
588
        let status = user.verify_change(&h).unwrap();
589
        assert!(
590
            matches!(&status, SignatureStatus::Invalid(e) if e.contains("expired")),
591
            "{status:?}"
592
        );
593
        // No policy here, so the user is no root: only delegation lets them revoke.
594
        let stranger = SecretKey::generate().identity("x", "x@example", 1).hash();
595
        assert!(user.revoke_identity(&stranger, "").is_err());
596
        assert!(user.revoke_identity(&agent, "session over").is_ok());
597
        assert!(user.is_revoked(&agent).unwrap());
598
        let r = user.delegate_remove(&agent).unwrap();
599
        assert!(user.identity(&r.new).unwrap().delegates.is_empty());
600
    }
601
602
    #[test]
603
    fn a_host_edit_that_removes_markers_resolves_the_conflict() {
604
        let dir = tempfile::tempdir().unwrap();
605
        let (host, mut user, hub_key, hub_sk, hub_id) = setup(dir.path(), false, true);
606
        let author = user.config.author_key.unwrap();
607
        let base = host.bookmark_heads().unwrap();
608
        // Two independent edits of the same line: a conflict in the union.
609
        let a = host
610
            .build_change(
611
                &base,
612
                &[FileEdit {
613
                    path: "a.txt".into(),
614
                    content: Some(b"ONE\ntwo\n".to_vec()),
615
                }],
616
                "A",
617
                author,
618
            )
619
            .unwrap();
620
        let b = host
621
            .build_change(
622
                &base,
623
                &[FileEdit {
624
                    path: "a.txt".into(),
625
                    content: Some(b"uno\ntwo\n".to_vec()),
626
                }],
627
                "B",
628
                author,
629
            )
630
            .unwrap();
631
        let (ha, hb) = (a.hash(), b.hash());
632
        let ids = vec![hub_id.clone(), user.identity(&author).unwrap()];
633
        for (c, h) in [(a, ha), (b, hb)] {
634
            let sig = hub_sk.sign(Domain::Change, &hub_key, &h);
635
            let mut heads = host.bookmark_heads().unwrap();
636
            heads.retain(|x| !base.contains(x));
637
            heads.push(h);
638
            let update = host
639
                .host_ref_update("main", &heads, Some((&hub_key, &hub_sk)))
640
                .unwrap();
641
            let r = host
642
                .apply_hosted(Some((c, vec![sig])), &ids, update)
643
                .unwrap();
644
            assert!(r.results.iter().all(|x| x.ok), "{:?}", r.results);
645
        }
646
        let heads = host.bookmark_heads().unwrap();
647
        assert_eq!(heads.len(), 2);
648
        let marked = String::from_utf8(host.file_at("a.txt", Some(&heads)).unwrap()).unwrap();
649
        assert!(marked.contains("<<<<<<< oxy conflict"), "{marked}");
650
        // Saving with markers left in is refused; saving without them resolves.
651
        assert!(host
652
            .build_change(
653
                &heads,
654
                &[FileEdit {
655
                    path: "a.txt".into(),
656
                    content: Some(format!("{marked}x\n").into_bytes())
657
                }],
658
                "half",
659
                author
660
            )
661
            .is_err());
662
        let res = host
663
            .build_change(
664
                &heads,
665
                &[FileEdit {
666
                    path: "a.txt".into(),
667
                    content: Some(b"One\ntwo\n".to_vec()),
668
                }],
669
                "Resolve",
670
                author,
671
            )
672
            .unwrap();
673
        assert_eq!(res.kind, ChangeKind::Resolution);
674
        assert!(
675
            res.deps.contains(&ha) && res.deps.contains(&hb),
676
            "a resolution depends on both sides"
677
        );
678
        let hr = res.hash();
679
        let sig = hub_sk.sign(Domain::Change, &hub_key, &hr);
680
        let update = host
681
            .host_ref_update("main", &[hr], Some((&hub_key, &hub_sk)))
682
            .unwrap();
683
        let r = host
684
            .apply_hosted(Some((res, vec![sig])), &ids, update)
685
            .unwrap();
686
        assert!(r.results.iter().all(|x| x.ok), "{:?}", r.results);
687
        assert_eq!(host.file_at("a.txt", Some(&[hr])).unwrap(), b"One\ntwo\n");
688
        assert!(!host
689
            .load_state(&[hr])
690
            .unwrap()
691
            .materialize()
692
            .is_conflicted());
693
        let _ = &mut user;
694
    }
695
}