interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-core / src / derivation.rs

910 lines · 36518 bytes Raw Blame History
1//! Server-derived revisions and their `DerivationAttestation` (ADR 0003 sections 5.1, 5.3, 5.6
2//! and 5.8, section 9 step B5). See `docs/B5_DERIVATION_ATTESTATION.md`.
3//!
4//! * A **derived revision** is one the server produced rather than an agent: a rebase of an
5//! admitted revision onto another tree, or a merge of admitted revisions. It carries no agent
6//! signature. A [`DerivedRevision`] is its content plus one [`DerivationAttestation`].
7//! * A [`DerivationAttestation`] is signed by the server's machine key (the `server_key` of the
8//! repository identity document, step E0). It names the inputs (revisions and trees), the
9//! deterministic [`DerivationRule`], and the output `ChangesetId` and `TreeDigest`.
10//! * [`derive_revision_output`] is the one definition of every rule. The server uses it to
11//! produce a derived revision and every replica uses it to recompute one; an attestation whose
12//! recomputation differs is refused.
13//!
14//! The encodings follow `docs/B1_CHANGE_IDENTITY.md` section 3 (principle P5): little-endian,
15//! length-prefixed, every count bounded before allocation, trailing bytes refused, and every
16//! decode refusal `EnvelopeMalformed`.
17
18use crate::revision::{malformed, put_str, Reader};
19use crate::{
20 encode_did_key_ed25519, AdmissionWitness, BlobDigest, ChainPath, ChangeId, ChangesetId,
21 FileMode, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent,
22 SynapseError, SynapseResult, TreeDigest, WalSeq, WitnessSigner,
23};
24use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
25use sha2::{Digest, Sha256};
26
27/// Domain tag of the server's Ed25519 signature over a [`DerivationAttestation`].
28pub const DOMAIN_DERIVATION_SIGN_V1: &[u8] = b"SYNAPSE_DERIVATION_SIGN_V1\0";
29/// Domain tag of [`DerivationAttestation::digest`].
30pub const DOMAIN_DERIVATION_ATTESTATION_V1: &[u8] = b"SYNAPSE_DERIVATION_ATTESTATION_V1\0";
31/// Domain tag of the `ChangeId` of a merge output (a merge starts a new unit of work whose
32/// identity must be recomputable from its inputs).
33pub const DOMAIN_DERIVED_MERGE_CHANGE_V1: &[u8] = b"SYNAPSE_DERIVED_MERGE_CHANGE_V1\0";
34/// Most inputs one attestation names.
35pub const MAX_DERIVATION_INPUTS: usize = 256;
36
37const RULE_TAG_REBASE: u8 = 1;
38const RULE_TAG_MERGE: u8 = 2;
39// Tag 3 is reserved for the derived-file action (the `ActionDigest` of the declared action,
40// ADR 0003 section 5.3); it needs registered executors and is not decodable yet.
41const TIER_TAG_T0: u8 = 0;
42const TIER_TAG_T1: u8 = 1;
43const INPUT_TAG_REVISION: u8 = 1;
44const INPUT_TAG_TREE: u8 = 2;
45/// Encoded size of the smallest input (tag and a 32-byte digest).
46const MIN_INPUT_BYTES: usize = 1 + 32;
47
48fn input_mismatch(msg: impl Into<String>) -> SynapseError {
49 SynapseError::new(RefusalCode::DerivationInputMismatch, msg)
50}
51
52fn recompute_mismatch(msg: impl Into<String>) -> SynapseError {
53 SynapseError::new(RefusalCode::DerivationRecomputeMismatch, msg)
54}
55
56// ---------------------------------------------------------------------------------------
57// Rules and inputs
58// ---------------------------------------------------------------------------------------
59
60/// The level a merge works at (`MergeTier` in `CONTEXT.md`).
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub enum MergeTier {
63 /// Path level: the merged revisions touch disjoint paths (no path of one equals, contains,
64 /// or lies inside a path of another).
65 T0Path,
66 /// Region level (step D1): the T0 rule, except that revisions may write the same file
67 /// when its versions merge line by line ([`crate::merge::region_merge`]: every changed
68 /// region separated from every other revision's by an unchanged base line). Identical
69 /// mutations of one path are taken once.
70 T1Region,
71}
72
73/// The deterministic rule a derivation applied.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub enum DerivationRule {
76 /// Rebase one admitted revision onto another tree, at path level. Inputs: exactly
77 /// `[Revision(r), Tree(onto)]`. The output keeps `r`'s `ChangeId`, parents, mutations and
78 /// intent and takes `onto` as its base. Refused when `onto` is already `r`'s base, or when
79 /// a path `r` mutates collides with a path that differs between `r`'s base and `onto`
80 /// (that is a conflict, recorded by later steps as a conflict term, never overwritten).
81 Rebase,
82 /// Merge admitted revisions that share one base. Inputs: `[Tree(base), Revision(a1), ...,
83 /// Revision(an)]` with `n >= 2` and the revisions in the canonical merge order (strictly
84 /// ascending `ChangesetId`). The output's base is `base`, its parents are the merged
85 /// revisions, its mutations are their union (paths must be disjoint at tier T0), its
86 /// `ChangeId` is the first 16 bytes of `SHA-256(DOMAIN_DERIVED_MERGE_CHANGE_V1 || base ||
87 /// u32 n || id*)`, and its intent summary is `merge tier T0 of <n> revisions`.
88 Merge { tier: MergeTier },
89}
90
91impl DerivationRule {
92 fn encode_into(&self, buf: &mut Vec<u8>) {
93 match self {
94 DerivationRule::Rebase => buf.push(RULE_TAG_REBASE),
95 DerivationRule::Merge { tier } => {
96 buf.push(RULE_TAG_MERGE);
97 buf.push(match tier {
98 MergeTier::T0Path => TIER_TAG_T0,
99 MergeTier::T1Region => TIER_TAG_T1,
100 });
101 }
102 }
103 }
104
105 fn decode_from(r: &mut Reader) -> SynapseResult<Self> {
106 match r.u8()? {
107 RULE_TAG_REBASE => Ok(DerivationRule::Rebase),
108 RULE_TAG_MERGE => match r.u8()? {
109 TIER_TAG_T0 => Ok(DerivationRule::Merge {
110 tier: MergeTier::T0Path,
111 }),
112 TIER_TAG_T1 => Ok(DerivationRule::Merge {
113 tier: MergeTier::T1Region,
114 }),
115 tag => Err(malformed(format!("unknown merge tier tag {tag}"))),
116 },
117 tag => Err(malformed(format!("unknown derivation rule tag {tag}"))),
118 }
119 }
120}
121
122/// One input a derivation names: an admitted revision or a tree.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
124pub enum DerivationInput {
125 Revision(ChangesetId),
126 Tree(TreeDigest),
127}
128
129impl DerivationInput {
130 fn encode_into(&self, buf: &mut Vec<u8>) {
131 match self {
132 DerivationInput::Revision(id) => {
133 buf.push(INPUT_TAG_REVISION);
134 buf.extend_from_slice(&id.0);
135 }
136 DerivationInput::Tree(t) => {
137 buf.push(INPUT_TAG_TREE);
138 buf.extend_from_slice(&t.0);
139 }
140 }
141 }
142
143 fn decode_from(r: &mut Reader) -> SynapseResult<Self> {
144 match r.u8()? {
145 INPUT_TAG_REVISION => Ok(DerivationInput::Revision(ChangesetId(r.array()?))),
146 INPUT_TAG_TREE => Ok(DerivationInput::Tree(TreeDigest(r.array()?))),
147 tag => Err(malformed(format!("unknown derivation input tag {tag}"))),
148 }
149 }
150}
151
152// ---------------------------------------------------------------------------------------
153// Attestation and derived revision
154// ---------------------------------------------------------------------------------------
155
156/// The server's signed statement that revision `output_changeset`, whose tree is
157/// `output_tree`, is what `rule` gives on `inputs` in repository `repo_id` (ADR 0003 section
158/// 5.1). Deterministic: the same derivation always gives the same attestation bytes, so a
159/// second presentation of one derivation is a replay.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct DerivationAttestation {
162 pub repo_id: RepoId,
163 pub rule: DerivationRule,
164 pub inputs: Vec<DerivationInput>,
165 pub output_changeset: ChangesetId,
166 pub output_tree: TreeDigest,
167 /// The server machine key that signed (must be the identity document's `server_key` in
168 /// effect at the admission `WalSeq`).
169 pub server_key: [u8; 32],
170 pub signature: [u8; 64],
171}
172
173impl DerivationAttestation {
174 /// Sign an attestation with the server's machine key.
175 pub fn sign(
176 server: &SigningKey,
177 repo_id: RepoId,
178 rule: DerivationRule,
179 inputs: Vec<DerivationInput>,
180 output_changeset: ChangesetId,
181 output_tree: TreeDigest,
182 ) -> Self {
183 let mut att = Self {
184 repo_id,
185 rule,
186 inputs,
187 output_changeset,
188 output_tree,
189 server_key: server.verifying_key().to_bytes(),
190 signature: [0u8; 64],
191 };
192 att.signature = server.sign(&att.signable_bytes()).to_bytes();
193 att
194 }
195
196 /// The server key's `did:key`.
197 pub fn server_did(&self) -> String {
198 encode_did_key_ed25519(&self.server_key)
199 }
200
201 fn encode_body(&self, buf: &mut Vec<u8>) {
202 put_str(buf, self.repo_id.as_str());
203 self.rule.encode_into(buf);
204 buf.extend_from_slice(&(self.inputs.len() as u32).to_le_bytes());
205 for i in &self.inputs {
206 i.encode_into(buf);
207 }
208 buf.extend_from_slice(&self.output_changeset.0);
209 buf.extend_from_slice(&self.output_tree.0);
210 buf.extend_from_slice(&self.server_key);
211 }
212
213 /// `DOMAIN_DERIVATION_SIGN_V1 || repo_id str || rule || u32 count || input* ||
214 /// output_changeset [32] || output_tree [32] || server_key [32]`.
215 pub fn signable_bytes(&self) -> Vec<u8> {
216 let mut buf = Vec::with_capacity(192 + 33 * self.inputs.len());
217 buf.extend_from_slice(DOMAIN_DERIVATION_SIGN_V1);
218 self.encode_body(&mut buf);
219 buf
220 }
221
222 /// 1..=`MAX_DERIVATION_INPUTS` inputs and a strict Ed25519 signature by `server_key`.
223 /// Both a key that is not an Ed25519 point and a signature that does not verify are
224 /// `DerivationSignatureInvalid`.
225 pub fn verify(&self) -> SynapseResult<()> {
226 if self.inputs.is_empty() || self.inputs.len() > MAX_DERIVATION_INPUTS {
227 return Err(input_mismatch(format!(
228 "derivation names {} inputs, outside 1..={MAX_DERIVATION_INPUTS}",
229 self.inputs.len()
230 )));
231 }
232 let invalid = |what: &str| {
233 SynapseError::new(
234 RefusalCode::DerivationSignatureInvalid,
235 format!("derivation attestation: {what}"),
236 )
237 };
238 let vk = VerifyingKey::from_bytes(&self.server_key)
239 .map_err(|_| invalid("server key is not an Ed25519 public key"))?;
240 vk.verify_strict(
241 &self.signable_bytes(),
242 &Signature::from_bytes(&self.signature),
243 )
244 .map_err(|_| invalid("signature does not verify under the named server key"))
245 }
246
247 /// Body (as signed, without the domain tag) then the 64-byte signature.
248 pub fn encode(&self) -> Vec<u8> {
249 let mut buf = Vec::with_capacity(256 + 33 * self.inputs.len());
250 self.encode_into(&mut buf);
251 buf
252 }
253
254 fn encode_into(&self, buf: &mut Vec<u8>) {
255 self.encode_body(buf);
256 buf.extend_from_slice(&self.signature);
257 }
258
259 /// Decode exactly one canonical attestation (structure only; see [`Self::verify`]).
260 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
261 let mut r = Reader::new(bytes);
262 let att = Self::decode_from(&mut r)?;
263 r.finish()?;
264 Ok(att)
265 }
266
267 fn decode_from(r: &mut Reader) -> SynapseResult<Self> {
268 let repo_id = r.repo()?;
269 let rule = DerivationRule::decode_from(r)?;
270 let n = r.count(MAX_DERIVATION_INPUTS, MIN_INPUT_BYTES)?;
271 if n == 0 {
272 return Err(malformed("derivation names no inputs"));
273 }
274 let mut inputs = Vec::with_capacity(n);
275 for _ in 0..n {
276 inputs.push(DerivationInput::decode_from(r)?);
277 }
278 Ok(Self {
279 repo_id,
280 rule,
281 inputs,
282 output_changeset: ChangesetId(r.array()?),
283 output_tree: TreeDigest(r.array()?),
284 server_key: r.array()?,
285 signature: r.array()?,
286 })
287 }
288
289 /// `SHA-256(DOMAIN_DERIVATION_ATTESTATION_V1 || encode())`: the identity of one signed
290 /// attestation, recorded in the admission witness and used to refuse replays.
291 pub fn digest(&self) -> [u8; 32] {
292 let mut h = Sha256::new();
293 h.update(DOMAIN_DERIVATION_ATTESTATION_V1);
294 h.update(self.encode());
295 h.finalize().into()
296 }
297}
298
299/// A server-derived revision: its content and the attestation over it. It has no agent
300/// signature and never claims one.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub struct DerivedRevision {
303 pub content: RevisionContent,
304 pub attestation: DerivationAttestation,
305}
306
307impl DerivedRevision {
308 /// Produce a derived revision: recompute `rule` on `inputs` (the same function every
309 /// replica runs) and sign the attestation with the server's machine key.
310 pub fn derive(
311 server: &SigningKey,
312 repo_id: RepoId,
313 rule: DerivationRule,
314 inputs: Vec<DerivationInput>,
315 revision: &dyn Fn(ChangesetId) -> Option<RevisionContent>,
316 trees: &mut dyn DerivationTrees,
317 ) -> SynapseResult<Self> {
318 let (content, tree) = derive_revision_output(rule, &inputs, revision, trees)?;
319 let attestation = DerivationAttestation::sign(
320 server,
321 repo_id,
322 rule,
323 inputs,
324 content.changeset_id(),
325 tree,
326 );
327 Ok(Self {
328 content,
329 attestation,
330 })
331 }
332
333 /// The content-only v2 `ChangesetId`.
334 pub fn changeset_id(&self) -> ChangesetId {
335 self.content.changeset_id()
336 }
337
338 /// Validate the content (the B1 rules), check that the attestation names this content
339 /// (`DerivationSignatureInvalid` otherwise), and verify the attestation. This needs no
340 /// state; registration of the server key, replay, and recomputation are checked against
341 /// the ledger, the identity document, and the tree store.
342 pub fn validate(&self) -> SynapseResult<ChangesetId> {
343 self.content.validate()?;
344 let id = self.content.changeset_id();
345 if self.attestation.output_changeset != id {
346 return Err(SynapseError::new(
347 RefusalCode::DerivationSignatureInvalid,
348 format!(
349 "derivation attestation names revision {} but the content is revision {id}",
350 self.attestation.output_changeset
351 ),
352 ));
353 }
354 self.attestation.verify()?;
355 Ok(id)
356 }
357
358 /// `u32 content_len | content | attestation`.
359 pub fn encode(&self) -> Vec<u8> {
360 let content = self.content.encode();
361 let mut buf = Vec::with_capacity(content.len() + 256);
362 buf.extend_from_slice(&(content.len() as u32).to_le_bytes());
363 buf.extend_from_slice(&content);
364 self.attestation.encode_into(&mut buf);
365 buf
366 }
367
368 /// Decode exactly one canonical derived revision (structure only; see [`Self::validate`]).
369 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
370 let mut r = Reader::new(bytes);
371 let len = r.u32()? as usize;
372 let mut inner = Reader::new(r.take(len)?);
373 let content = RevisionContent::decode_from(&mut inner)?;
374 inner.finish()?;
375 let attestation = DerivationAttestation::decode_from(&mut r)?;
376 r.finish()?;
377 Ok(Self {
378 content,
379 attestation,
380 })
381 }
382}
383
384impl AdmissionWitness {
385 /// The witness of admitting `derived` at `admission_seq` under `chain`: the server key,
386 /// its signature, and the attestation digest instead of an agent signature. The
387 /// idempotency key is the attestation digest (a derivation has no client key; a second
388 /// presentation of one attestation is refused as a replay).
389 pub fn of_derivation(
390 derived: &DerivedRevision,
391 chain: ChainPath,
392 admission_seq: WalSeq,
393 admitted_at_ms: u64,
394 ) -> Self {
395 let att = &derived.attestation;
396 let digest = att.digest();
397 Self {
398 repo_id: att.repo_id.clone(),
399 changeset_id: att.output_changeset,
400 signer: WitnessSigner::Server {
401 server_key: att.server_key,
402 signature: att.signature,
403 attestation_digest: digest,
404 },
405 idempotency_key: IdempotencyKey(digest),
406 admission_seq,
407 admitted_at_ms,
408 chain,
409 }
410 }
411}
412
413// ---------------------------------------------------------------------------------------
414// What a replica needs to check and recompute
415// ---------------------------------------------------------------------------------------
416
417/// What a [`ServerKeyRegistry`] answers for one repository at one `WalSeq`.
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub enum ServerKeyLookup {
420 /// The `server_key` of the repository's identity document in effect at the sequence.
421 Registered([u8; 32]),
422 /// No identity document of the repository is in effect at the sequence (before genesis).
423 NoDocument,
424 /// The registry holds the identity documents of another repository (named here), so it
425 /// says nothing about the one asked for.
426 OtherRepository(RepoId),
427}
428
429/// Which server machine key a repository identity document registered at a `WalSeq`
430/// (`synapse_radicle::IdentityLog` implements it from the E0 document chain). The repository
431/// is part of the question, so one repository's documents can never vouch for another's
432/// derivations, even when both register the same server machine key.
433pub trait ServerKeyRegistry {
434 /// The `server_key` of `repo`'s document in effect at `at`.
435 fn registered_server_key(&self, repo: &RepoId, at: WalSeq) -> ServerKeyLookup;
436}
437
438/// The tree operations a derivation rule needs (the C1 tree store implements them).
439pub trait DerivationTrees {
440 /// Whether the tree `tree` can be read (its root node is held).
441 fn holds_tree(&mut self, tree: TreeDigest) -> bool;
442 /// The root of `base` with `mutations` applied in order.
443 fn apply_mutations(
444 &mut self,
445 base: TreeDigest,
446 mutations: &[PathMutation],
447 ) -> SynapseResult<TreeDigest>;
448 /// Every file path whose entry differs between `from` and `to`.
449 fn changed_paths(&mut self, from: TreeDigest, to: TreeDigest) -> SynapseResult<Vec<String>>;
450 /// The file at `path` of `tree` (mode and blob), `None` when there is none (tier T1).
451 fn file_at(
452 &mut self,
453 tree: TreeDigest,
454 path: &str,
455 ) -> SynapseResult<Option<(FileMode, BlobDigest)>>;
456 /// The bytes of a stored blob (`BlobNotFound` when this replica cannot read it; tier T1).
457 fn blob_bytes(&mut self, digest: BlobDigest) -> SynapseResult<Vec<u8>>;
458 /// Hold the bytes of a blob a derivation produced (a tier T1 merged file) so that later
459 /// mutations can name it and the store can write it with the derived revision; returns
460 /// its digest.
461 fn put_blob(&mut self, bytes: Vec<u8>) -> SynapseResult<BlobDigest>;
462 /// The bytes of a blob produced by [`DerivationTrees::put_blob`], if any.
463 fn produced_blob(&self, digest: BlobDigest) -> Option<&[u8]>;
464}
465
466/// `true` when `inner` lies strictly below directory `dir`.
467fn is_below(inner: &str, dir: &str) -> bool {
468 inner.len() > dir.len() && inner.starts_with(dir) && inner.as_bytes()[dir.len()] == b'/'
469}
470
471/// Two paths collide at path level when they are equal or one lies below the other.
472fn paths_collide(a: &str, b: &str) -> bool {
473 a == b || is_below(a, b) || is_below(b, a)
474}
475
476/// Any pair of paths, one from each sorted list, that collides.
477fn first_collision<'a>(a: &'a [&'a str], b: &'a [&'a str]) -> Option<(&'a str, &'a str)> {
478 for x in a {
479 for y in b {
480 if paths_collide(x, y) {
481 return Some((x, y));
482 }
483 }
484 }
485 None
486}
487
488/// Tier T0 mutations of a merge: the union of every source's mutations, refused when a path
489/// of one source collides (equal, or one below the other) with a path of another.
490fn t0_mutations(sources: &[RevisionContent]) -> SynapseResult<Vec<PathMutation>> {
491 for i in 0..sources.len() {
492 let a: Vec<&str> = sources[i]
493 .mutations
494 .iter()
495 .map(|m| m.path.as_str())
496 .collect();
497 for s in &sources[i + 1..] {
498 let b: Vec<&str> = s.mutations.iter().map(|m| m.path.as_str()).collect();
499 if let Some((x, y)) = first_collision(&a, &b) {
500 return Err(recompute_mismatch(format!(
501 "tier T0 merge conflicts: {x} collides with {y}"
502 )));
503 }
504 }
505 }
506 let mut mutations: Vec<PathMutation> = sources
507 .iter()
508 .flat_map(|s| s.mutations.iter().cloned())
509 .collect();
510 mutations.sort_by(|a, b| a.path.cmp(&b.path));
511 Ok(mutations)
512}
513
514/// Tier T1 mutations of a merge on `base` (step D1). Paths written by one source are taken
515/// as they are; byte-identical mutations of one path are taken once; a file several sources
516/// upsert differently with the base's mode is merged line by line
517/// ([`crate::merge::region_merge`]) and the merged bytes are held through
518/// [`DerivationTrees::put_blob`]. Refused (`DerivationRecomputeMismatch`): a path of one
519/// source lying below a path of another, a path deleted by one source and changed by
520/// another, a mode change, a file added by several sources with different content, and any
521/// region conflict.
522fn t1_mutations(
523 base: TreeDigest,
524 sources: &[RevisionContent],
525 trees: &mut dyn DerivationTrees,
526) -> SynapseResult<Vec<PathMutation>> {
527 let mut by_path: std::collections::BTreeMap<&str, Vec<(usize, &PathMutation)>> =
528 std::collections::BTreeMap::new();
529 for (i, s) in sources.iter().enumerate() {
530 for m in &s.mutations {
531 by_path.entry(m.path.as_str()).or_default().push((i, m));
532 }
533 }
534 let paths: Vec<(&str, Vec<usize>)> = by_path
535 .iter()
536 .map(|(p, v)| (*p, v.iter().map(|(i, _)| *i).collect()))
537 .collect();
538 for (x, xs) in &paths {
539 for (y, ys) in &paths {
540 if is_below(y, x) && xs.iter().any(|i| ys.iter().any(|j| i != j)) {
541 return Err(recompute_mismatch(format!(
542 "tier T1 merge conflicts: {y} lies below {x}, written by another revision"
543 )));
544 }
545 }
546 }
547 let mut out = Vec::with_capacity(by_path.len());
548 for (path, muts) in by_path {
549 let mut distinct: Vec<&PathMutation> = Vec::new();
550 for (_, m) in &muts {
551 if !distinct.contains(m) {
552 distinct.push(m);
553 }
554 }
555 if let [only] = distinct.as_slice() {
556 out.push((*only).clone());
557 continue;
558 }
559 let conflict =
560 |why: String| recompute_mismatch(format!("tier T1 merge conflicts on {path}: {why}"));
561 let mut versions = Vec::with_capacity(distinct.len());
562 for m in &distinct {
563 match &m.op {
564 MutationOp::Upsert {
565 mode, blob_digest, ..
566 } => versions.push((*mode, *blob_digest)),
567 MutationOp::Delete => {
568 return Err(conflict(
569 "deleted by one revision and changed by another".into(),
570 ))
571 }
572 }
573 }
574 let Some((base_mode, base_blob)) = trees.file_at(base, path)? else {
575 return Err(conflict(
576 "added by several revisions with different content".into(),
577 ));
578 };
579 // Every version keeps the base mode (a mode change is not merged line by line).
580 if versions.iter().any(|(mode, _)| *mode != base_mode) {
581 return Err(conflict("a revision changes the file's mode".into()));
582 }
583 let base_bytes = trees.blob_bytes(base_blob)?;
584 let mut bytes = Vec::with_capacity(versions.len());
585 for (_, v) in &versions {
586 bytes.push(trees.blob_bytes(*v)?);
587 }
588 let refs: Vec<&[u8]> = bytes.iter().map(Vec::as_slice).collect();
589 let merged =
590 crate::merge::region_merge(&base_bytes, &refs).map_err(|c| conflict(c.to_string()))?;
591 let size_bytes = merged.len() as u64;
592 let blob_digest = trees.put_blob(merged)?;
593 out.push(PathMutation {
594 path: path.to_string(),
595 op: MutationOp::Upsert {
596 mode: base_mode,
597 blob_digest,
598 size_bytes,
599 },
600 });
601 }
602 Ok(out)
603}
604
605fn require_tree(trees: &mut dyn DerivationTrees, t: TreeDigest, what: &str) -> SynapseResult<()> {
606 if trees.holds_tree(t) {
607 Ok(())
608 } else {
609 Err(input_mismatch(format!(
610 "{what} {t} is not held by this replica"
611 )))
612 }
613}
614
615/// The `ChangeId` of a merge (any tier) of `ids` (canonical order) on `base`.
616fn merge_change_id(base: TreeDigest, ids: &[ChangesetId]) -> ChangeId {
617 let mut h = Sha256::new();
618 h.update(DOMAIN_DERIVED_MERGE_CHANGE_V1);
619 h.update(base.0);
620 h.update((ids.len() as u32).to_le_bytes());
621 for id in ids {
622 h.update(id.0);
623 }
624 let d: [u8; 32] = h.finalize().into();
625 let mut out = [0u8; 16];
626 out.copy_from_slice(&d[..16]);
627 ChangeId(out)
628}
629
630/// The output content and tree of `rule` on `inputs`: the one definition of every rule, run
631/// by the server to derive and by every replica to recompute. `revision` resolves an admitted
632/// revision of the attestation's repository (admitted before the derivation).
633///
634/// Refusals: inputs that do not fit the rule (kind, count, order, duplicates) or that are not
635/// held (`revision` returns `None`, or the tree is not held) are `DerivationInputMismatch`; a
636/// rule that does not apply to the inputs (a rebase onto its own base or with a path conflict,
637/// a merge of revisions on another base or with colliding paths) is
638/// `DerivationRecomputeMismatch`. Tree store failures propagate unchanged.
639pub fn derive_revision_output(
640 rule: DerivationRule,
641 inputs: &[DerivationInput],
642 revision: &dyn Fn(ChangesetId) -> Option<RevisionContent>,
643 trees: &mut dyn DerivationTrees,
644) -> SynapseResult<(RevisionContent, TreeDigest)> {
645 if inputs.is_empty() || inputs.len() > MAX_DERIVATION_INPUTS {
646 return Err(input_mismatch(format!(
647 "derivation names {} inputs, outside 1..={MAX_DERIVATION_INPUTS}",
648 inputs.len()
649 )));
650 }
651 let resolve = |id: ChangesetId| {
652 revision(id).ok_or_else(|| {
653 input_mismatch(format!(
654 "input revision {id} is not an admitted revision of this repository"
655 ))
656 })
657 };
658 match rule {
659 DerivationRule::Rebase => {
660 let [DerivationInput::Revision(r), DerivationInput::Tree(onto)] = inputs else {
661 return Err(input_mismatch(
662 "a rebase names exactly [Revision(r), Tree(onto)]",
663 ));
664 };
665 let source = resolve(*r)?;
666 require_tree(trees, *onto, "rebase target tree")?;
667 require_tree(trees, source.base_tree, "base tree of the rebased revision")?;
668 if source.base_tree == *onto {
669 return Err(recompute_mismatch(format!(
670 "revision {r} is already based on {onto}: nothing to rebase"
671 )));
672 }
673 let changed = trees.changed_paths(source.base_tree, *onto)?;
674 let changed: Vec<&str> = changed.iter().map(String::as_str).collect();
675 let mutated: Vec<&str> = source.mutations.iter().map(|m| m.path.as_str()).collect();
676 if let Some((m, c)) = first_collision(&mutated, &changed) {
677 return Err(recompute_mismatch(format!(
678 "path-level rebase of {r} conflicts: {m} collides with {c}, which differs between its base and {onto}"
679 )));
680 }
681 let content = RevisionContent {
682 base_tree: *onto,
683 ..source
684 };
685 content.validate()?;
686 let tree = trees.apply_mutations(*onto, &content.mutations)?;
687 Ok((content, tree))
688 }
689 DerivationRule::Merge { tier } => {
690 let Some((DerivationInput::Tree(base), rest)) = inputs.split_first() else {
691 return Err(input_mismatch(
692 "a merge names [Tree(base), Revision(a1), ..., Revision(an)]",
693 ));
694 };
695 let mut ids = Vec::with_capacity(rest.len());
696 for i in rest {
697 match i {
698 DerivationInput::Revision(id) => ids.push(*id),
699 DerivationInput::Tree(_) => {
700 return Err(input_mismatch("a merge names exactly one tree, first"))
701 }
702 }
703 }
704 if ids.len() < 2 {
705 return Err(input_mismatch("a merge names at least two revisions"));
706 }
707 if ids.windows(2).any(|w| w[0] >= w[1]) {
708 return Err(input_mismatch(
709 "merge revisions must be in the canonical merge order (strictly ascending ChangesetId)",
710 ));
711 }
712 require_tree(trees, *base, "merge base tree")?;
713 let mut sources = Vec::with_capacity(ids.len());
714 for id in &ids {
715 sources.push(resolve(*id)?);
716 }
717 for (id, s) in ids.iter().zip(&sources) {
718 if s.base_tree != *base {
719 return Err(recompute_mismatch(format!(
720 "revision {id} is based on {}, not on the merge base {base}",
721 s.base_tree
722 )));
723 }
724 }
725 let mutations = match tier {
726 MergeTier::T0Path => t0_mutations(&sources)?,
727 MergeTier::T1Region => t1_mutations(*base, &sources, trees)?,
728 };
729 let content = RevisionContent {
730 change_id: merge_change_id(*base, &ids),
731 base_tree: *base,
732 parents: ids.clone(),
733 mutations,
734 intent_summary: format!(
735 "merge tier {} of {} revisions",
736 match tier {
737 MergeTier::T0Path => "T0",
738 MergeTier::T1Region => "T1",
739 },
740 ids.len()
741 ),
742 };
743 content.validate()?;
744 let tree = trees.apply_mutations(*base, &content.mutations)?;
745 Ok((content, tree))
746 }
747 }
748}
749
750#[cfg(test)]
751mod tests {
752 use super::*;
753 use crate::{BlobDigest, FileMode, MutationOp};
754
755 fn repo() -> RepoId {
756 RepoId::new("aien-spark/synapse").unwrap()
757 }
758
759 fn server() -> SigningKey {
760 let seed: [u8; 32] = Sha256::digest(b"b5 unit server key").into();
761 SigningKey::from_bytes(&seed)
762 }
763
764 fn attestation() -> DerivationAttestation {
765 DerivationAttestation::sign(
766 &server(),
767 repo(),
768 DerivationRule::Merge {
769 tier: MergeTier::T0Path,
770 },
771 vec![
772 DerivationInput::Tree(TreeDigest([0x5A; 32])),
773 DerivationInput::Revision(ChangesetId([1; 32])),
774 DerivationInput::Revision(ChangesetId([2; 32])),
775 ],
776 ChangesetId([3; 32]),
777 TreeDigest([4; 32]),
778 )
779 }
780
781 #[test]
782 fn b5_attestation_round_trips_and_refuses_malformed_bytes() {
783 let att = attestation();
784 att.verify().unwrap();
785 let bytes = att.encode();
786 assert_eq!(DerivationAttestation::decode(&bytes).unwrap(), att);
787 for cut in 0..bytes.len() {
788 assert_eq!(
789 DerivationAttestation::decode(&bytes[..cut])
790 .unwrap_err()
791 .code,
792 RefusalCode::EnvelopeMalformed,
793 "cut {cut}"
794 );
795 }
796 let mut trailing = bytes.clone();
797 trailing.push(0);
798 assert!(DerivationAttestation::decode(&trailing).is_err());
799 // The rule tag follows `u32 len | repo`; tag 3 (derived-file action) is reserved.
800 let rule_at = 4 + repo().as_str().len();
801 let mut reserved = bytes.clone();
802 reserved[rule_at] = 3;
803 assert_eq!(
804 DerivationAttestation::decode(&reserved).unwrap_err().code,
805 RefusalCode::EnvelopeMalformed
806 );
807 let mut tier = bytes.clone();
808 tier[rule_at + 1] = 2;
809 assert!(DerivationAttestation::decode(&tier).is_err());
810 // Tier tag 1 is T1 (step D1): it decodes, to a different attestation whose
811 // signature no longer verifies.
812 tier[rule_at + 1] = 1;
813 let t1 = DerivationAttestation::decode(&tier).unwrap();
814 assert_eq!(
815 t1.rule,
816 DerivationRule::Merge {
817 tier: MergeTier::T1Region
818 }
819 );
820 assert!(t1.verify().is_err());
821 let mut zero = bytes.clone();
822 zero[rule_at + 2..rule_at + 6].copy_from_slice(&0u32.to_le_bytes());
823 assert!(DerivationAttestation::decode(&zero).is_err());
824 let mut huge = bytes;
825 huge[rule_at + 2..rule_at + 6].copy_from_slice(&u32::MAX.to_le_bytes());
826 assert!(DerivationAttestation::decode(&huge).is_err());
827 }
828
829 #[test]
830 fn b5_attestation_signature_binds_every_field() {
831 let att = attestation();
832 let mut t = att.clone();
833 t.output_tree = TreeDigest([9; 32]);
834 assert_eq!(
835 t.verify().unwrap_err().code,
836 RefusalCode::DerivationSignatureInvalid
837 );
838 let mut t = att.clone();
839 t.rule = DerivationRule::Rebase;
840 assert_eq!(
841 t.verify().unwrap_err().code,
842 RefusalCode::DerivationSignatureInvalid
843 );
844 let mut t = att.clone();
845 t.inputs.pop();
846 assert_eq!(
847 t.verify().unwrap_err().code,
848 RefusalCode::DerivationSignatureInvalid
849 );
850 let mut t = att.clone();
851 t.repo_id = RepoId::new("aien-spark/other").unwrap();
852 assert_eq!(
853 t.verify().unwrap_err().code,
854 RefusalCode::DerivationSignatureInvalid
855 );
856 assert_ne!(att.digest(), t.digest());
857 }
858
859 #[test]
860 fn b5_server_witness_round_trips_and_is_not_an_agent() {
861 let content = RevisionContent {
862 change_id: ChangeId([7; 16]),
863 base_tree: TreeDigest([0x5A; 32]),
864 parents: vec![],
865 mutations: vec![PathMutation {
866 path: "src/lib.rs".into(),
867 op: MutationOp::Upsert {
868 mode: FileMode::Regular644,
869 blob_digest: BlobDigest::compute(b"x"),
870 size_bytes: 1,
871 },
872 }],
873 intent_summary: "derived".into(),
874 };
875 let attestation = DerivationAttestation::sign(
876 &server(),
877 repo(),
878 DerivationRule::Rebase,
879 vec![
880 DerivationInput::Revision(ChangesetId([1; 32])),
881 DerivationInput::Tree(TreeDigest([0x5A; 32])),
882 ],
883 content.changeset_id(),
884 TreeDigest([4; 32]),
885 );
886 let derived = DerivedRevision {
887 content,
888 attestation,
889 };
890 derived.validate().unwrap();
891 assert_eq!(DerivedRevision::decode(&derived.encode()).unwrap(), derived);
892 let chain = ChainPath::new(vec![[1; 32]]).unwrap();
893 let w = AdmissionWitness::of_derivation(&derived, chain, WalSeq(3), 9);
894 assert_eq!(AdmissionWitness::decode(&w.encode()).unwrap(), w);
895 assert_eq!(w.signer_did(), derived.attestation.server_did());
896 assert!(
897 matches!(w.signer, WitnessSigner::Server { attestation_digest, .. }
898 if attestation_digest == derived.attestation.digest())
899 );
900 }
901
902 #[test]
903 fn b5_path_collision_is_equal_or_below() {
904 assert!(paths_collide("a", "a"));
905 assert!(paths_collide("a", "a/b"));
906 assert!(paths_collide("a/b/c", "a/b"));
907 assert!(!paths_collide("a", "ab"));
908 assert!(!paths_collide("a/b", "a/c"));
909 }
910}