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 / revision.rs

1015 lines · 37767 bytes Raw Blame History
1//! Changeset envelope v2, change identity, authorship attestations, admission witnesses, and
2//! obsolescence markers (ADR 0003 sections 5.1, 5.3 and 5.8, section 9 step B1).
3//!
4//! * A **revision** is one immutable version of a change. Its [`RevisionContent`] is what its
5//! v2 `ChangesetId` covers: the `ChangeId`, the native base `TreeDigest`, parent revisions,
6//! path mutations, and the intent summary. Who submitted it and when are excluded, so a
7//! rewrite (new content, same `ChangeId`) gets a new `ChangesetId` while identical content
8//! from two agents is one revision.
9//! * An [`AuthorshipAttestation`] is an agent's signed statement that it produced a revision
10//! at a time, bound to the repository and the submission's `IdempotencyKey`. A
11//! [`ChangesetEnvelopeV2`] is content plus one attestation.
12//! * An [`AdmissionWitness`] is what the server records, once and never changed, when it admits
13//! an envelope: repository, revision, signer, idempotency key, admission `WalSeq`, server
14//! time, and the [`ChainPath`] the request was authorized under. The witness of the first
15//! admission under a `ChangeId` fixes that change's **creating chain**.
16//! * An [`ObsolescenceMarker`] says that one revision was replaced by zero (pruned), one
17//! (rewritten), or several (split) successors.
18//!
19//! Envelope v1 (`ChangesetEnvelope`) is unchanged: its encoding, signature, and `ChangesetId`
20//! stay exactly as they were, and v1 identities never collide with v2 ones (distinct domain
21//! tags).
22//!
23//! Every signed and persisted form here is the fixed-width, little-endian, length-prefixed
24//! binary encoding of `docs/B1_CHANGE_IDENTITY.md` (ADR 0003 principle P5, the A1 codec style):
25//! one encoding per value, every length checked against the bytes that remain before anything
26//! is allocated, and any other byte sequence refused with `EnvelopeMalformed` (or
27//! `EnvelopeVersionUnsupported` for an unknown content version). There is no serde form.
28
29use crate::{
30 encode_did_key_ed25519, validate_intent_summary, validate_mutations,
31 validate_parent_changesets, ChangeId, ChangesetId, FileMode, IdempotencyKey, MutationOp,
32 PathMutation, RefusalCode, RepoId, SynapseError, SynapseResult, TreeDigest, WalSeq,
33 MAX_INTENT_SUMMARY_BYTES,
34};
35use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
36use sha2::{Digest, Sha256};
37
38/// Content format version of envelope v2 (the first field of [`RevisionContent::encode`]).
39pub const ENVELOPE_V2_VERSION: u16 = 2;
40/// Domain tag of a v2 `ChangesetId` (v1 uses `SYNAPSE_CHANGESET_V1\0`).
41pub const DOMAIN_CHANGESET_ID_V2: &[u8] = b"SYNAPSE_CHANGESET_V2\0";
42/// Domain tag of the Ed25519 signature of an [`AuthorshipAttestation`].
43pub const DOMAIN_AUTHORSHIP_SIGN_V2: &[u8] = b"SYNAPSE_AUTHORSHIP_SIGN_V2\0";
44/// Domain tag of the Ed25519 signature of an [`ObsolescenceMarker`].
45pub const DOMAIN_OBSOLESCENCE_SIGN_V1: &[u8] = b"SYNAPSE_OBSOLESCENCE_SIGN_V1\0";
46/// Domain tag of [`AdmissionWitness::digest`].
47pub const DOMAIN_ADMISSION_WITNESS_V1: &[u8] = b"SYNAPSE_ADMISSION_WITNESS_V1\0";
48/// Most links in a [`ChainPath`] (the F1 `MAX_CHAIN_DEPTH`).
49pub const MAX_CHAIN_PATH_DEPTH: usize = 16;
50/// Most successors of one obsolescence marker.
51pub const MAX_OBSOLESCENCE_SUCCESSORS: usize = 256;
52
53const MAX_PATH_BYTES: usize = 2048;
54const MAX_REPO_ID_BYTES: usize = 128;
55/// Encoded size of the smallest mutation (`u32` empty path and a delete tag).
56const MIN_MUTATION_BYTES: usize = 4 + 1;
57/// Witness signer tag of an agent admission.
58const SIGNER_TAG_AGENT: u8 = 1;
59/// Witness signer tag of a server-derived admission (step B5).
60const SIGNER_TAG_SERVER: u8 = 2;
61const OP_TAG_UPSERT: u8 = 1;
62const OP_TAG_DELETE: u8 = 2;
63
64pub(crate) fn malformed(msg: impl Into<String>) -> SynapseError {
65 SynapseError::new(RefusalCode::EnvelopeMalformed, msg)
66}
67
68pub(crate) fn put_str(buf: &mut Vec<u8>, s: &str) {
69 buf.extend_from_slice(&(s.len() as u32).to_le_bytes());
70 buf.extend_from_slice(s.as_bytes());
71}
72
73pub(crate) fn verify_ed25519(
74 key: &[u8; 32],
75 msg: &[u8],
76 sig: &[u8; 64],
77 what: &str,
78) -> SynapseResult<()> {
79 let vk = VerifyingKey::from_bytes(key).map_err(|_| {
80 SynapseError::new(
81 RefusalCode::DidKeyInvalid,
82 format!("{what}: invalid Ed25519 public key"),
83 )
84 })?;
85 vk.verify_strict(msg, &Signature::from_bytes(sig))
86 .map_err(|_| {
87 SynapseError::new(
88 RefusalCode::AuthSignatureInvalid,
89 format!("{what}: Ed25519 signature verification failed"),
90 )
91 })
92}
93
94// ---------------------------------------------------------------------------------------
95// Revision content and the v2 ChangesetId
96// ---------------------------------------------------------------------------------------
97
98/// What a v2 `ChangesetId` covers: the content of one revision, never who submitted it or
99/// when. `IntentRecord` (step B3) and conflict terms (step D2) extend it under a later content
100/// version.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct RevisionContent {
103 /// The unit of intended work this revision belongs to.
104 pub change_id: ChangeId,
105 /// Native base: the `TreeDigest` the mutations apply to (envelope v1's `base_git_oid`).
106 pub base_tree: TreeDigest,
107 /// Revisions this one depends on, strictly ascending.
108 pub parents: Vec<ChangesetId>,
109 /// Path mutations, strictly ascending by path, at least one.
110 pub mutations: Vec<PathMutation>,
111 /// Free-text intent, 1..=4096 bytes (replaced by `IntentRecord` in step B3).
112 pub intent_summary: String,
113}
114
115impl RevisionContent {
116 /// Parents strictly ascending, mutations non-empty on valid sorted unique paths, intent
117 /// summary 1..=4096 bytes (the same rules and refusal codes as envelope v1).
118 pub fn validate(&self) -> SynapseResult<()> {
119 validate_intent_summary(&self.intent_summary)?;
120 validate_parent_changesets(&self.parents)?;
121 validate_mutations(&self.mutations)
122 }
123
124 /// `version u16 (2) | change_id [16] | base_tree [32] | u32 count | parent [32]* |
125 /// u32 count | (path str | op)* | intent_summary str`, where `op` is `1 | mode u8 |
126 /// blob_digest [32] | size u64` (upsert) or `2` (delete) and `str` is `u32 len | UTF-8`.
127 pub fn encode(&self) -> Vec<u8> {
128 let mut buf = Vec::with_capacity(128 + 96 * self.mutations.len());
129 buf.extend_from_slice(&ENVELOPE_V2_VERSION.to_le_bytes());
130 buf.extend_from_slice(&self.change_id.0);
131 buf.extend_from_slice(&self.base_tree.0);
132 buf.extend_from_slice(&(self.parents.len() as u32).to_le_bytes());
133 for p in &self.parents {
134 buf.extend_from_slice(&p.0);
135 }
136 buf.extend_from_slice(&(self.mutations.len() as u32).to_le_bytes());
137 for m in &self.mutations {
138 put_str(&mut buf, &m.path);
139 match &m.op {
140 MutationOp::Upsert {
141 mode,
142 blob_digest,
143 size_bytes,
144 } => {
145 buf.push(OP_TAG_UPSERT);
146 buf.push(mode.tag_byte());
147 buf.extend_from_slice(&blob_digest.0);
148 buf.extend_from_slice(&size_bytes.to_le_bytes());
149 }
150 MutationOp::Delete => buf.push(OP_TAG_DELETE),
151 }
152 }
153 put_str(&mut buf, &self.intent_summary);
154 buf
155 }
156
157 /// Decode exactly one canonical content encoding (structure only; see [`Self::validate`]).
158 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
159 let mut r = Reader::new(bytes);
160 let content = Self::decode_from(&mut r)?;
161 r.finish()?;
162 Ok(content)
163 }
164
165 pub(crate) fn decode_from(r: &mut Reader) -> SynapseResult<Self> {
166 let version = r.u16()?;
167 if version != ENVELOPE_V2_VERSION {
168 return Err(SynapseError::new(
169 RefusalCode::EnvelopeVersionUnsupported,
170 format!("unsupported revision content version {version}"),
171 ));
172 }
173 let change_id = ChangeId(r.array()?);
174 let base_tree = TreeDigest(r.array()?);
175 let n = r.count(usize::MAX, 32)?;
176 let mut parents = Vec::with_capacity(n);
177 for _ in 0..n {
178 parents.push(ChangesetId(r.array()?));
179 }
180 let n = r.count(usize::MAX, MIN_MUTATION_BYTES)?;
181 let mut mutations = Vec::with_capacity(n);
182 for _ in 0..n {
183 let path = r.string(MAX_PATH_BYTES)?;
184 let op = match r.u8()? {
185 OP_TAG_UPSERT => {
186 let tag = r.u8()?;
187 let mode = FileMode::from_tag_byte(tag)
188 .ok_or_else(|| malformed(format!("unknown file mode tag {tag}")))?;
189 MutationOp::Upsert {
190 mode,
191 blob_digest: crate::BlobDigest(r.array()?),
192 size_bytes: r.u64()?,
193 }
194 }
195 OP_TAG_DELETE => MutationOp::Delete,
196 tag => return Err(malformed(format!("unknown mutation tag {tag}"))),
197 };
198 mutations.push(PathMutation { path, op });
199 }
200 let intent_summary = r.string(MAX_INTENT_SUMMARY_BYTES)?;
201 Ok(Self {
202 change_id,
203 base_tree,
204 parents,
205 mutations,
206 intent_summary,
207 })
208 }
209
210 /// `SHA-256(DOMAIN_CHANGESET_ID_V2 || u64 len || encode())`: content only.
211 pub fn changeset_id(&self) -> ChangesetId {
212 let bytes = self.encode();
213 let mut h = Sha256::new();
214 h.update(DOMAIN_CHANGESET_ID_V2);
215 h.update((bytes.len() as u64).to_le_bytes());
216 h.update(&bytes);
217 ChangesetId(h.finalize().into())
218 }
219}
220
221// ---------------------------------------------------------------------------------------
222// Authorship attestation and envelope v2
223// ---------------------------------------------------------------------------------------
224
225/// An agent's signed statement that it produced revision `changeset_id` of repository
226/// `repo_id` at `attested_at_ms` (the agent's clock, never used for ordering or retention),
227/// submitted under `idempotency_key`. An attestation added later never revokes a receipt
228/// already accepted (ADR 0003 section 5.1).
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct AuthorshipAttestation {
231 pub repo_id: RepoId,
232 pub changeset_id: ChangesetId,
233 pub author_key: [u8; 32],
234 pub idempotency_key: IdempotencyKey,
235 pub attested_at_ms: u64,
236 pub signature: [u8; 64],
237}
238
239impl AuthorshipAttestation {
240 /// Sign an attestation with `author`.
241 pub fn sign(
242 author: &SigningKey,
243 repo_id: RepoId,
244 changeset_id: ChangesetId,
245 idempotency_key: IdempotencyKey,
246 attested_at_ms: u64,
247 ) -> Self {
248 let mut att = Self {
249 repo_id,
250 changeset_id,
251 author_key: author.verifying_key().to_bytes(),
252 idempotency_key,
253 attested_at_ms,
254 signature: [0u8; 64],
255 };
256 att.signature = author.sign(&att.signable_bytes()).to_bytes();
257 att
258 }
259
260 /// The author's `did:key`.
261 pub fn author_did(&self) -> String {
262 encode_did_key_ed25519(&self.author_key)
263 }
264
265 fn encode_body(&self, buf: &mut Vec<u8>) {
266 put_str(buf, self.repo_id.as_str());
267 buf.extend_from_slice(&self.changeset_id.0);
268 buf.extend_from_slice(&self.author_key);
269 buf.extend_from_slice(&self.idempotency_key.0);
270 buf.extend_from_slice(&self.attested_at_ms.to_le_bytes());
271 }
272
273 /// `DOMAIN_AUTHORSHIP_SIGN_V2 || repo_id str || changeset_id || author_key ||
274 /// idempotency_key || attested_at_ms u64`.
275 pub fn signable_bytes(&self) -> Vec<u8> {
276 let mut buf = Vec::with_capacity(192);
277 buf.extend_from_slice(DOMAIN_AUTHORSHIP_SIGN_V2);
278 self.encode_body(&mut buf);
279 buf
280 }
281
282 /// Strict Ed25519 verification of the author's signature.
283 pub fn verify(&self) -> SynapseResult<()> {
284 verify_ed25519(
285 &self.author_key,
286 &self.signable_bytes(),
287 &self.signature,
288 "authorship attestation",
289 )
290 }
291
292 /// Body (as signed, without the domain tag) then the 64-byte signature.
293 pub fn encode(&self) -> Vec<u8> {
294 let mut buf = Vec::with_capacity(192);
295 self.encode_into(&mut buf);
296 buf
297 }
298
299 fn encode_into(&self, buf: &mut Vec<u8>) {
300 self.encode_body(buf);
301 buf.extend_from_slice(&self.signature);
302 }
303
304 /// Decode exactly one canonical attestation (structure only; see [`Self::verify`]).
305 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
306 let mut r = Reader::new(bytes);
307 let att = Self::decode_from(&mut r)?;
308 r.finish()?;
309 Ok(att)
310 }
311
312 fn decode_from(r: &mut Reader) -> SynapseResult<Self> {
313 Ok(Self {
314 repo_id: r.repo()?,
315 changeset_id: ChangesetId(r.array()?),
316 author_key: r.array()?,
317 idempotency_key: IdempotencyKey(r.array()?),
318 attested_at_ms: r.u64()?,
319 signature: r.array()?,
320 })
321 }
322}
323
324/// Signed changeset envelope v2: one revision's content plus one authorship attestation over
325/// its content-only `ChangesetId`.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub struct ChangesetEnvelopeV2 {
328 pub content: RevisionContent,
329 pub attestation: AuthorshipAttestation,
330}
331
332impl ChangesetEnvelopeV2 {
333 /// Build and sign an envelope: the attestation names `content.changeset_id()`.
334 pub fn sign_new(
335 author: &SigningKey,
336 repo_id: RepoId,
337 content: RevisionContent,
338 idempotency_key: IdempotencyKey,
339 attested_at_ms: u64,
340 ) -> Self {
341 let id = content.changeset_id();
342 let attestation =
343 AuthorshipAttestation::sign(author, repo_id, id, idempotency_key, attested_at_ms);
344 Self {
345 content,
346 attestation,
347 }
348 }
349
350 /// The content-only v2 `ChangesetId`.
351 pub fn changeset_id(&self) -> ChangesetId {
352 self.content.changeset_id()
353 }
354
355 /// Validate the content, check that the attestation names this content, and verify its
356 /// signature. Returns the v2 `ChangesetId`.
357 pub fn validate(&self) -> SynapseResult<ChangesetId> {
358 self.content.validate()?;
359 let id = self.content.changeset_id();
360 if self.attestation.changeset_id != id {
361 return Err(SynapseError::new(
362 RefusalCode::AuthSignatureInvalid,
363 format!(
364 "attestation names revision {} but the content is revision {id}",
365 self.attestation.changeset_id
366 ),
367 ));
368 }
369 self.attestation.verify()?;
370 Ok(id)
371 }
372
373 /// `u32 content_len | content | attestation`.
374 pub fn encode(&self) -> Vec<u8> {
375 let content = self.content.encode();
376 let mut buf = Vec::with_capacity(content.len() + 196);
377 buf.extend_from_slice(&(content.len() as u32).to_le_bytes());
378 buf.extend_from_slice(&content);
379 self.attestation.encode_into(&mut buf);
380 buf
381 }
382
383 /// Decode exactly one canonical envelope (structure only; see [`Self::validate`]).
384 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
385 let mut r = Reader::new(bytes);
386 let len = r.u32()? as usize;
387 let mut inner = Reader::new(r.take(len)?);
388 let content = RevisionContent::decode_from(&mut inner)?;
389 inner.finish()?;
390 let attestation = AuthorshipAttestation::decode_from(&mut r)?;
391 r.finish()?;
392 Ok(Self {
393 content,
394 attestation,
395 })
396 }
397}
398
399// ---------------------------------------------------------------------------------------
400// Chains, witnesses, markers
401// ---------------------------------------------------------------------------------------
402
403/// A delegation chain as the digests of its capability links, root first (each digest is a
404/// `synapse_auth::LinkDigest`). Chains are compared by their link digests: chain `A`
405/// **dominates** chain `B` when `A` is `B` or one of its ancestors (a prefix of it), and `B`
406/// then **descends from** `A`.
407#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
408pub struct ChainPath(Vec<[u8; 32]>);
409
410impl ChainPath {
411 /// A chain of 1..=`MAX_CHAIN_PATH_DEPTH` link digests, root first.
412 pub fn new(links: Vec<[u8; 32]>) -> SynapseResult<Self> {
413 if links.is_empty() || links.len() > MAX_CHAIN_PATH_DEPTH {
414 return Err(SynapseError::new(
415 RefusalCode::AuthChainBroken,
416 format!(
417 "chain path length {} outside 1..={MAX_CHAIN_PATH_DEPTH}",
418 links.len()
419 ),
420 ));
421 }
422 Ok(Self(links))
423 }
424
425 /// Link digests, root first.
426 pub fn links(&self) -> &[[u8; 32]] {
427 &self.0
428 }
429
430 /// True when `self` is `other` or an ancestor of it (a prefix of its links).
431 pub fn dominates(&self, other: &ChainPath) -> bool {
432 other.0.starts_with(&self.0)
433 }
434
435 /// True when `self` is `ancestor` or descends from it.
436 pub fn descends_from(&self, ancestor: &ChainPath) -> bool {
437 ancestor.dominates(self)
438 }
439
440 /// `count u8 | digest [32]*`.
441 pub fn encode_into(&self, buf: &mut Vec<u8>) {
442 buf.push(self.0.len() as u8);
443 for d in &self.0 {
444 buf.extend_from_slice(d);
445 }
446 }
447
448 /// Decode exactly one canonical chain path.
449 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
450 let mut r = Reader::new(bytes);
451 let c = Self::decode_from(&mut r)?;
452 r.finish()?;
453 Ok(c)
454 }
455
456 fn decode_from(r: &mut Reader) -> SynapseResult<Self> {
457 let n = r.u8()? as usize;
458 if n == 0 || n > MAX_CHAIN_PATH_DEPTH {
459 return Err(malformed(format!(
460 "chain path length {n} outside 1..={MAX_CHAIN_PATH_DEPTH}"
461 )));
462 }
463 let mut links = Vec::with_capacity(n);
464 for _ in 0..n {
465 links.push(r.array()?);
466 }
467 Ok(Self(links))
468 }
469}
470
471/// Who signed an admitted revision: an agent (tag 1, step B1) or, for a server-derived
472/// revision, the server's machine key with its `DerivationAttestation` (tag 2, step B5).
473#[derive(Debug, Clone, PartialEq, Eq)]
474pub enum WitnessSigner {
475 /// An agent's key and its signature over the envelope (its authorship attestation).
476 Agent {
477 author_key: [u8; 32],
478 signature: [u8; 64],
479 },
480 /// The server's machine key, its signature over the revision's
481 /// [`crate::DerivationAttestation`], and that attestation's digest. A server-derived
482 /// revision never carries an agent signature (ADR 0003 sections 5.1 and 5.6).
483 Server {
484 server_key: [u8; 32],
485 signature: [u8; 64],
486 attestation_digest: [u8; 32],
487 },
488}
489
490/// The immutable record of one admission of a revision (ADR 0003 section 5.1). Idempotency
491/// is keyed on (`repo_id`, signer DID, `idempotency_key`); replay order is `admission_seq`;
492/// retention follows the server's clock (`admitted_at_ms`), never a client clock. `chain` is
493/// the delegation chain the admission was authorized under; the first admission's chain is
494/// the change's creating chain.
495#[derive(Debug, Clone, PartialEq, Eq)]
496pub struct AdmissionWitness {
497 pub repo_id: RepoId,
498 pub changeset_id: ChangesetId,
499 pub signer: WitnessSigner,
500 pub idempotency_key: IdempotencyKey,
501 pub admission_seq: WalSeq,
502 pub admitted_at_ms: u64,
503 pub chain: ChainPath,
504}
505
506impl AdmissionWitness {
507 /// The witness of admitting `attestation` at `admission_seq` under `chain`.
508 pub fn of_attestation(
509 attestation: &AuthorshipAttestation,
510 chain: ChainPath,
511 admission_seq: WalSeq,
512 admitted_at_ms: u64,
513 ) -> Self {
514 Self {
515 repo_id: attestation.repo_id.clone(),
516 changeset_id: attestation.changeset_id,
517 signer: WitnessSigner::Agent {
518 author_key: attestation.author_key,
519 signature: attestation.signature,
520 },
521 idempotency_key: attestation.idempotency_key,
522 admission_seq,
523 admitted_at_ms,
524 chain,
525 }
526 }
527
528 /// The signer's `did:key`.
529 pub fn signer_did(&self) -> String {
530 match &self.signer {
531 WitnessSigner::Agent { author_key, .. } => encode_did_key_ed25519(author_key),
532 WitnessSigner::Server { server_key, .. } => encode_did_key_ed25519(server_key),
533 }
534 }
535
536 /// `repo_id str | changeset_id [32] | signer | idempotency_key [32] | admission_seq u64 |
537 /// admitted_at_ms u64 | chain`, with `signer` = `1 | author_key [32] | signature [64]`
538 /// (agent) or `2 | server_key [32] | signature [64] | attestation_digest [32]` (server).
539 pub fn encode(&self) -> Vec<u8> {
540 let mut buf = Vec::with_capacity(256);
541 put_str(&mut buf, self.repo_id.as_str());
542 buf.extend_from_slice(&self.changeset_id.0);
543 match &self.signer {
544 WitnessSigner::Agent {
545 author_key,
546 signature,
547 } => {
548 buf.push(SIGNER_TAG_AGENT);
549 buf.extend_from_slice(author_key);
550 buf.extend_from_slice(signature);
551 }
552 WitnessSigner::Server {
553 server_key,
554 signature,
555 attestation_digest,
556 } => {
557 buf.push(SIGNER_TAG_SERVER);
558 buf.extend_from_slice(server_key);
559 buf.extend_from_slice(signature);
560 buf.extend_from_slice(attestation_digest);
561 }
562 }
563 buf.extend_from_slice(&self.idempotency_key.0);
564 buf.extend_from_slice(&self.admission_seq.0.to_le_bytes());
565 buf.extend_from_slice(&self.admitted_at_ms.to_le_bytes());
566 self.chain.encode_into(&mut buf);
567 buf
568 }
569
570 /// Decode exactly one canonical witness.
571 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
572 let mut r = Reader::new(bytes);
573 let repo_id = r.repo()?;
574 let changeset_id = ChangesetId(r.array()?);
575 let signer = match r.u8()? {
576 SIGNER_TAG_AGENT => WitnessSigner::Agent {
577 author_key: r.array()?,
578 signature: r.array()?,
579 },
580 SIGNER_TAG_SERVER => WitnessSigner::Server {
581 server_key: r.array()?,
582 signature: r.array()?,
583 attestation_digest: r.array()?,
584 },
585 tag => return Err(malformed(format!("unknown witness signer tag {tag}"))),
586 };
587 let w = Self {
588 repo_id,
589 changeset_id,
590 signer,
591 idempotency_key: IdempotencyKey(r.array()?),
592 admission_seq: WalSeq(r.u64()?),
593 admitted_at_ms: r.u64()?,
594 chain: ChainPath::decode_from(&mut r)?,
595 };
596 r.finish()?;
597 Ok(w)
598 }
599
600 /// `SHA-256(DOMAIN_ADMISSION_WITNESS_V1 || encode())`: the admission witness digest that
601 /// promotion signatures cover (ADR 0003 section 5.5).
602 pub fn digest(&self) -> [u8; 32] {
603 let mut h = Sha256::new();
604 h.update(DOMAIN_ADMISSION_WITNESS_V1);
605 h.update(self.encode());
606 h.finalize().into()
607 }
608}
609
610/// How many successors replace the obsolete revision.
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub enum ObsolescenceKind {
613 /// Zero successors: the attempt is discarded.
614 Pruned,
615 /// One successor.
616 Rewritten,
617 /// Several successors.
618 Split,
619}
620
621/// A signed record that revision `predecessor` of change `change_id` was replaced by
622/// `successors` (strictly ascending, never containing `predecessor`): zero for a prune, one
623/// for a rewrite, several for a split (ADR 0003 sections 5.1 and 5.3).
624#[derive(Debug, Clone, PartialEq, Eq)]
625pub struct ObsolescenceMarker {
626 pub repo_id: RepoId,
627 pub change_id: ChangeId,
628 pub predecessor: ChangesetId,
629 pub successors: Vec<ChangesetId>,
630 pub signer_key: [u8; 32],
631 pub signed_at_ms: u64,
632 pub signature: [u8; 64],
633}
634
635impl ObsolescenceMarker {
636 /// Build and sign a marker; `successors` are sorted and deduplicated.
637 pub fn sign_new(
638 signer: &SigningKey,
639 repo_id: RepoId,
640 change_id: ChangeId,
641 predecessor: ChangesetId,
642 mut successors: Vec<ChangesetId>,
643 signed_at_ms: u64,
644 ) -> Self {
645 successors.sort();
646 successors.dedup();
647 let mut m = Self {
648 repo_id,
649 change_id,
650 predecessor,
651 successors,
652 signer_key: signer.verifying_key().to_bytes(),
653 signed_at_ms,
654 signature: [0u8; 64],
655 };
656 m.signature = signer.sign(&m.signable_bytes()).to_bytes();
657 m
658 }
659
660 /// Pruned, rewritten, or split, by successor count.
661 pub fn kind(&self) -> ObsolescenceKind {
662 match self.successors.len() {
663 0 => ObsolescenceKind::Pruned,
664 1 => ObsolescenceKind::Rewritten,
665 _ => ObsolescenceKind::Split,
666 }
667 }
668
669 /// The signer's `did:key`.
670 pub fn signer_did(&self) -> String {
671 encode_did_key_ed25519(&self.signer_key)
672 }
673
674 fn encode_body(&self, buf: &mut Vec<u8>) {
675 put_str(buf, self.repo_id.as_str());
676 buf.extend_from_slice(&self.change_id.0);
677 buf.extend_from_slice(&self.predecessor.0);
678 buf.extend_from_slice(&(self.successors.len() as u32).to_le_bytes());
679 for s in &self.successors {
680 buf.extend_from_slice(&s.0);
681 }
682 buf.extend_from_slice(&self.signer_key);
683 buf.extend_from_slice(&self.signed_at_ms.to_le_bytes());
684 }
685
686 /// `DOMAIN_OBSOLESCENCE_SIGN_V1 || repo_id str || change_id [16] || predecessor [32] ||
687 /// u32 count || successor [32]* || signer_key [32] || signed_at_ms u64`.
688 pub fn signable_bytes(&self) -> Vec<u8> {
689 let mut buf = Vec::with_capacity(160 + 32 * self.successors.len());
690 buf.extend_from_slice(DOMAIN_OBSOLESCENCE_SIGN_V1);
691 self.encode_body(&mut buf);
692 buf
693 }
694
695 /// Successors strictly ascending, at most `MAX_OBSOLESCENCE_SUCCESSORS`, never the
696 /// predecessor; signature verifies strictly.
697 pub fn validate(&self) -> SynapseResult<()> {
698 if self.successors.len() > MAX_OBSOLESCENCE_SUCCESSORS {
699 return Err(SynapseError::new(
700 RefusalCode::ObsolescenceMarkerInvalid,
701 format!("more than {MAX_OBSOLESCENCE_SUCCESSORS} successors"),
702 ));
703 }
704 if self.successors.windows(2).any(|w| w[0] >= w[1]) {
705 return Err(SynapseError::new(
706 RefusalCode::ObsolescenceMarkerInvalid,
707 "successors must be strictly ascending",
708 ));
709 }
710 if self.successors.contains(&self.predecessor) {
711 return Err(SynapseError::new(
712 RefusalCode::ObsolescenceMarkerInvalid,
713 "a revision cannot be its own successor",
714 ));
715 }
716 verify_ed25519(
717 &self.signer_key,
718 &self.signable_bytes(),
719 &self.signature,
720 "obsolescence marker",
721 )
722 }
723
724 /// Body (as signed, without the domain tag) then the 64-byte signature.
725 pub fn encode(&self) -> Vec<u8> {
726 let mut buf = Vec::with_capacity(160 + 32 * self.successors.len());
727 self.encode_body(&mut buf);
728 buf.extend_from_slice(&self.signature);
729 buf
730 }
731
732 /// Decode exactly one canonical marker (structure only; see [`Self::validate`]).
733 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
734 let mut r = Reader::new(bytes);
735 let repo_id = r.repo()?;
736 let change_id = ChangeId(r.array()?);
737 let predecessor = ChangesetId(r.array()?);
738 let n = r.count(MAX_OBSOLESCENCE_SUCCESSORS, 32)?;
739 let mut successors = Vec::with_capacity(n);
740 for _ in 0..n {
741 successors.push(ChangesetId(r.array()?));
742 }
743 let m = Self {
744 repo_id,
745 change_id,
746 predecessor,
747 successors,
748 signer_key: r.array()?,
749 signed_at_ms: r.u64()?,
750 signature: r.array()?,
751 };
752 r.finish()?;
753 Ok(m)
754 }
755
756 /// `SHA-256(DOMAIN_OBSOLESCENCE_SIGN_V1 || encode())`: identity of one signed marker.
757 pub fn digest(&self) -> [u8; 32] {
758 let mut h = Sha256::new();
759 h.update(DOMAIN_OBSOLESCENCE_SIGN_V1);
760 h.update(self.encode());
761 h.finalize().into()
762 }
763}
764
765// ---------------------------------------------------------------------------------------
766// Bounded reader
767// ---------------------------------------------------------------------------------------
768
769/// Bounds-checked little-endian reader; every failure is `EnvelopeMalformed`.
770pub(crate) struct Reader<'a> {
771 buf: &'a [u8],
772 pos: usize,
773}
774
775impl<'a> Reader<'a> {
776 pub(crate) fn new(buf: &'a [u8]) -> Self {
777 Self { buf, pos: 0 }
778 }
779
780 pub(crate) fn remaining(&self) -> usize {
781 self.buf.len() - self.pos
782 }
783
784 pub(crate) fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> {
785 if n > self.remaining() {
786 return Err(malformed(format!(
787 "truncated: need {n} bytes at offset {}, {} remain",
788 self.pos,
789 self.remaining()
790 )));
791 }
792 let out = &self.buf[self.pos..self.pos + n];
793 self.pos += n;
794 Ok(out)
795 }
796
797 pub(crate) fn array<const N: usize>(&mut self) -> SynapseResult<[u8; N]> {
798 Ok(self.take(N)?.try_into().expect("N bytes"))
799 }
800
801 pub(crate) fn u8(&mut self) -> SynapseResult<u8> {
802 Ok(self.take(1)?[0])
803 }
804
805 pub(crate) fn u16(&mut self) -> SynapseResult<u16> {
806 Ok(u16::from_le_bytes(self.array()?))
807 }
808
809 pub(crate) fn u32(&mut self) -> SynapseResult<u32> {
810 Ok(u32::from_le_bytes(self.array()?))
811 }
812
813 pub(crate) fn u64(&mut self) -> SynapseResult<u64> {
814 Ok(u64::from_le_bytes(self.array()?))
815 }
816
817 /// A `u32` count, refused above `cap` or above what `min_item_bytes` per item could fit
818 /// in the bytes that remain (so nothing is reserved beyond the input).
819 pub(crate) fn count(&mut self, cap: usize, min_item_bytes: usize) -> SynapseResult<usize> {
820 let n = self.u32()? as usize;
821 if n > cap || n.saturating_mul(min_item_bytes) > self.remaining() {
822 return Err(malformed(format!(
823 "count {n} above cap {cap} or the {} bytes that remain",
824 self.remaining()
825 )));
826 }
827 Ok(n)
828 }
829
830 pub(crate) fn string(&mut self, cap: usize) -> SynapseResult<String> {
831 let len = self.u32()? as usize;
832 if len > cap {
833 return Err(malformed(format!("string length {len} above cap {cap}")));
834 }
835 let bytes = self.take(len)?;
836 String::from_utf8(bytes.to_vec()).map_err(|_| malformed("string is not UTF-8"))
837 }
838
839 pub(crate) fn repo(&mut self) -> SynapseResult<RepoId> {
840 let s = self.string(MAX_REPO_ID_BYTES)?;
841 RepoId::new(s).map_err(|e| malformed(format!("repository id: {}", e.message)))
842 }
843
844 pub(crate) fn finish(&self) -> SynapseResult<()> {
845 if self.pos != self.buf.len() {
846 return Err(malformed(format!("{} trailing bytes", self.remaining())));
847 }
848 Ok(())
849 }
850}
851
852#[cfg(test)]
853mod tests {
854 use super::*;
855 use crate::BlobDigest;
856
857 fn repo() -> RepoId {
858 RepoId::new("aien-spark/synapse").unwrap()
859 }
860
861 fn content(change: u8, body: &[u8]) -> RevisionContent {
862 RevisionContent {
863 change_id: ChangeId([change; 16]),
864 base_tree: TreeDigest([0x5A; 32]),
865 parents: vec![],
866 mutations: vec![PathMutation {
867 path: "src/lib.rs".into(),
868 op: MutationOp::Upsert {
869 mode: FileMode::Regular644,
870 blob_digest: BlobDigest::compute(body),
871 size_bytes: body.len() as u64,
872 },
873 }],
874 intent_summary: "add lib".into(),
875 }
876 }
877
878 #[test]
879 fn b1_v2_changeset_id_covers_content_only_not_author_or_time() {
880 let a = SigningKey::from_bytes(&[1; 32]);
881 let b = SigningKey::from_bytes(&[2; 32]);
882 let c = content(7, b"x");
883 let ea = ChangesetEnvelopeV2::sign_new(&a, repo(), c.clone(), IdempotencyKey([1; 32]), 10);
884 let eb = ChangesetEnvelopeV2::sign_new(&b, repo(), c.clone(), IdempotencyKey([2; 32]), 99);
885 assert_eq!(ea.validate().unwrap(), eb.validate().unwrap());
886 assert_ne!(ea.attestation, eb.attestation);
887 let mut rewritten = c.clone();
888 rewritten.intent_summary = "add lib, rewritten".into();
889 assert_ne!(rewritten.changeset_id(), c.changeset_id());
890 assert_eq!(rewritten.change_id, c.change_id);
891 }
892
893 #[test]
894 fn b1_envelope_v2_round_trips_and_refuses_malformed_bytes() {
895 let a = SigningKey::from_bytes(&[1; 32]);
896 let mut c = content(7, b"x");
897 c.parents = vec![ChangesetId([1; 32]), ChangesetId([2; 32])];
898 c.mutations.push(PathMutation {
899 path: "src/old.rs".into(),
900 op: MutationOp::Delete,
901 });
902 let env = ChangesetEnvelopeV2::sign_new(&a, repo(), c, IdempotencyKey([1; 32]), 10);
903 let bytes = env.encode();
904 assert_eq!(ChangesetEnvelopeV2::decode(&bytes).unwrap(), env);
905 assert_eq!(ChangesetEnvelopeV2::decode(&bytes).unwrap().encode(), bytes);
906 for cut in 0..bytes.len() {
907 assert!(
908 ChangesetEnvelopeV2::decode(&bytes[..cut]).is_err(),
909 "cut {cut}"
910 );
911 }
912 let mut trailing = bytes.clone();
913 trailing.push(0);
914 assert_eq!(
915 ChangesetEnvelopeV2::decode(&trailing).unwrap_err().code,
916 RefusalCode::EnvelopeMalformed
917 );
918 let mut huge = bytes.clone();
919 huge[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
920 assert_eq!(
921 ChangesetEnvelopeV2::decode(&huge).unwrap_err().code,
922 RefusalCode::EnvelopeMalformed
923 );
924 let mut version = bytes.clone();
925 version[4] = 3;
926 assert_eq!(
927 ChangesetEnvelopeV2::decode(&version).unwrap_err().code,
928 RefusalCode::EnvelopeVersionUnsupported
929 );
930 }
931
932 #[test]
933 fn b1_envelope_v2_signature_binds_repo_key_and_time() {
934 let a = SigningKey::from_bytes(&[1; 32]);
935 let env = ChangesetEnvelopeV2::sign_new(
936 &a,
937 repo(),
938 content(7, b"x"),
939 IdempotencyKey([1; 32]),
940 10,
941 );
942 let mut t = env.clone();
943 t.attestation.attested_at_ms = 11;
944 assert_eq!(
945 t.validate().unwrap_err().code,
946 RefusalCode::AuthSignatureInvalid
947 );
948 let mut t = env.clone();
949 t.attestation.repo_id = RepoId::new("aien-spark/other").unwrap();
950 assert_eq!(
951 t.validate().unwrap_err().code,
952 RefusalCode::AuthSignatureInvalid
953 );
954 let mut t = env.clone();
955 t.content.intent_summary = "changed".into();
956 assert_eq!(
957 t.validate().unwrap_err().code,
958 RefusalCode::AuthSignatureInvalid
959 );
960 }
961
962 #[test]
963 fn b1_chain_path_dominance_is_prefix_order() {
964 let r = ChainPath::new(vec![[1; 32]]).unwrap();
965 let o = ChainPath::new(vec![[1; 32], [2; 32]]).unwrap();
966 let w = ChainPath::new(vec![[1; 32], [2; 32], [3; 32]]).unwrap();
967 let x = ChainPath::new(vec![[1; 32], [9; 32]]).unwrap();
968 assert!(r.dominates(&o) && o.dominates(&w) && r.dominates(&w) && o.dominates(&o));
969 assert!(!w.dominates(&o) && !x.dominates(&w) && !o.dominates(&x));
970 assert!(w.descends_from(&o) && !x.descends_from(&o));
971 assert!(ChainPath::new(vec![]).is_err());
972 assert!(ChainPath::new(vec![[0; 32]; MAX_CHAIN_PATH_DEPTH + 1]).is_err());
973 }
974
975 #[test]
976 fn b1_witness_and_marker_round_trip() {
977 let a = SigningKey::from_bytes(&[1; 32]);
978 let env = ChangesetEnvelopeV2::sign_new(
979 &a,
980 repo(),
981 content(7, b"x"),
982 IdempotencyKey([1; 32]),
983 10,
984 );
985 let chain = ChainPath::new(vec![[1; 32], [2; 32]]).unwrap();
986 let w = AdmissionWitness::of_attestation(&env.attestation, chain, WalSeq(4), 77);
987 assert_eq!(AdmissionWitness::decode(&w.encode()).unwrap(), w);
988 assert_eq!(w.signer_did(), env.attestation.author_did());
989 let m = ObsolescenceMarker::sign_new(
990 &a,
991 repo(),
992 ChangeId([7; 16]),
993 ChangesetId([3; 32]),
994 vec![
995 ChangesetId([5; 32]),
996 ChangesetId([4; 32]),
997 ChangesetId([5; 32]),
998 ],
999 12,
1000 );
1001 assert_eq!(
1002 m.successors,
1003 vec![ChangesetId([4; 32]), ChangesetId([5; 32])]
1004 );
1005 assert_eq!(m.kind(), ObsolescenceKind::Split);
1006 m.validate().unwrap();
1007 assert_eq!(ObsolescenceMarker::decode(&m.encode()).unwrap(), m);
1008 let mut own = m.clone();
1009 own.successors = vec![m.predecessor];
1010 assert_eq!(
1011 own.validate().unwrap_err().code,
1012 RefusalCode::ObsolescenceMarkerInvalid
1013 );
1014 }
1015}