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

1037 lines · 38519 bytes Raw Blame History
1//! Core domain identities, canonical changeset envelopes v1 and v2 (v2 since ADR 0003 step B1,
2//! [`ChangesetEnvelopeV2`]), `did:key` Ed25519 codec, and deterministic refusal taxonomy for
3//! Synapse (ADR 0001).
4
5use ed25519_dalek::{Signature, Signer, SigningKey, Verifier};
6use serde::{Deserialize, Serialize};
7use sha1::Sha1;
8use sha2::{Digest, Sha256};
9use std::fmt;
10
11mod derivation;
12mod key_cache;
13pub mod merge;
14mod revision;
15mod revision_state;
16mod tree;
17pub use derivation::{
18 derive_revision_output, DerivationAttestation, DerivationInput, DerivationRule,
19 DerivationTrees, DerivedRevision, MergeTier, ServerKeyLookup, ServerKeyRegistry,
20 DOMAIN_DERIVATION_ATTESTATION_V1, DOMAIN_DERIVATION_SIGN_V1, DOMAIN_DERIVED_MERGE_CHANGE_V1,
21 MAX_DERIVATION_INPUTS,
22};
23pub use key_cache::{cached_verifying_key, key_cache_stats, KEY_CACHE_CAPACITY};
24pub use revision::{
25 AdmissionWitness, AuthorshipAttestation, ChainPath, ChangesetEnvelopeV2, ObsolescenceKind,
26 ObsolescenceMarker, RevisionContent, WitnessSigner, DOMAIN_ADMISSION_WITNESS_V1,
27 DOMAIN_AUTHORSHIP_SIGN_V2, DOMAIN_CHANGESET_ID_V2, DOMAIN_OBSOLESCENCE_SIGN_V1,
28 ENVELOPE_V2_VERSION, MAX_CHAIN_PATH_DEPTH, MAX_OBSOLESCENCE_SUCCESSORS,
29};
30pub use revision_state::RevisionState;
31pub use tree::{
32 decode_tree_node, tree_entry_order, validate_tree_entry_name, TreeDigest, TreeNodeEncoder,
33 TreeNodeEntry, TreeNodeEntryKind, DOMAIN_TREE_V1, MAX_TREE_ENTRY_NAME_BYTES,
34 TREE_TAG_DIRECTORY,
35};
36
37/// Current canonical changeset envelope schema version.
38pub const SYNAPSE_ENVELOPE_VERSION: u16 = 1;
39
40/// Domain tag for `BlobDigest` SHA-256 computation.
41pub const DOMAIN_BLOB_V1: &[u8] = b"SYNAPSE_BLOB_V1\0";
42
43/// Domain tag for `ChangesetEnvelope` Ed25519 signing.
44pub const DOMAIN_CHANGESET_SIGN_V1: &[u8] = b"SYNAPSE_CHANGESET_SIGN_V1\0";
45
46/// Domain tag for `ChangesetId` SHA-256 computation.
47pub const DOMAIN_CHANGESET_ID_V1: &[u8] = b"SYNAPSE_CHANGESET_V1\0";
48
49/// Deterministic refusal codes across all Synapse boundaries.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
51pub enum RefusalCode {
52 // Storage and integrity refusals
53 BlobDigestMismatch,
54 BlobImmutableConflict,
55 BlobNotFound,
56 WalMagicInvalid,
57 WalVersionUnsupported,
58 WalFlagsNonZero,
59 WalCrcMismatch,
60 WalChainMismatch,
61 WalSequenceGap,
62 WalTornFrame,
63 /// A WAL record payload passed its checksums but does not decode (binary codec v2).
64 WalRecordMalformed,
65 /// A binary wire frame is not in its one canonical encoding: bad magic, version, flags,
66 /// kind, length over the negotiated cap, truncated, or a malformed body (step G1).
67 WireFrameMalformed,
68 /// A well-formed wire frame arrived out of protocol order: no hello first, a want that is
69 /// not a subset of the have, an unsolicited or repeated chunk, or a submit before every
70 /// wanted chunk arrived (step G1).
71 WireProtocolViolation,
72 /// The peer broke the shared-memory ring protocol: an index out of range, moved back or
73 /// misaligned, a record length over the cap or past the published bytes, or a wrong
74 /// record sequence number (step G3).
75 WireRingViolation,
76 CheckpointCorrupt,
77 IoFailure,
78
79 // Capacity and backpressure refusals
80 BackpressureOverCapacity,
81 QuotaPayloadTooLarge,
82 QuotaTooManyPaths,
83 QuotaRateLimitExceeded,
84 PaginationLimitExceeded,
85 /// The children of one capability link would together exceed the parent's rate, storage, or
86 /// footprint quota (ADR 0003 section 5.8, step F1).
87 QuotaPartitionExceeded,
88
89 // Schema, path, and consistency refusals
90 EnvelopeVersionUnsupported,
91 /// A changeset envelope v2, authorship attestation, admission witness, obsolescence
92 /// marker, derivation attestation, or derived revision is not in its one canonical binary
93 /// encoding (ADR 0003 section 5.1, steps B1 and B5).
94 EnvelopeMalformed,
95 RepoIdInvalid,
96 PathInvalid,
97 PathDuplicate,
98 MutationsUnsorted,
99 BaseTreeNotFound,
100 /// A native tree node is not canonical: a bad entry name, a duplicate name, entries out of
101 /// canonical order, or a wrong entry count (ADR 0003 section 5.1, step C1).
102 TreeNodeMalformed,
103 /// A native tree node is not in the bounded tree store (evicted or never built); the tree is
104 /// rebuilt from its source (step C1).
105 TreeNodeNotFound,
106 ParentChangesetNotFound,
107 ChangesetNotFound,
108 VisibilitySeqAhead,
109 IdempotencyKeyConflict,
110 CursorInvalid,
111
112 // Authentication and capability refusals
113 DidKeyInvalid,
114 AuthSignatureInvalid,
115 AuthGrantSignatureInvalid,
116 AuthGrantExpired,
117 AuthCapabilityDenied,
118 AuthCrossRepoDenied,
119 AuthReplayDetected,
120 AuthSelfReviewRefused,
121 AuditChainCorrupt,
122 /// A capability chain does not link up: empty or too deep, a root that is not a trusted
123 /// repository authority, a parent digest that does not match the previous link (stripped or
124 /// reordered chain), or a link the server never granted (ADR 0003 section 5.8, step F1).
125 AuthChainBroken,
126 /// A capability link or chain is not in its one canonical binary encoding (step F1).
127 AuthChainMalformed,
128 /// A link is bound to another audience: its issuer is not its parent's audience, or the
129 /// request is presented by a key that is not the leaf link's audience (step F1).
130 AuthAudienceMismatch,
131 /// A derived link is wider than its parent in operations, paths, references, change scope,
132 /// quotas, or validity window (step F1).
133 AuthScopeEscalation,
134 /// A link of the chain was revoked at or before the request's `WalSeq` (step F1).
135 AuthGrantRevoked,
136 /// A request touches a path outside the chain's path scope (step F1).
137 AuthPathOutOfScope,
138 /// A request touches a reference kind outside the chain's reference scope (step F1).
139 AuthReferenceOutOfScope,
140 /// A request joins a `ChangeId` outside the chain's change scope (step F1), or adds a
141 /// revision under a `ChangeId` whose creating chain the key does not descend from while its
142 /// change scope does not name that `ChangeId` (ADR 0003 section 5.1, step B1).
143 AuthChangeOutOfScope,
144 /// An obsolescence marker is recorded by a chain that neither is nor dominates the chain
145 /// it needs: the change's creating chain for a prune, or for a rewrite or split either the
146 /// creating chain or the chain that first admitted the replaced revision (step B1).
147 AuthChainNotDominant,
148 /// An obsolescence marker names an unknown revision, a revision of another change, itself
149 /// as its own successor, or would close a cycle of markers (step B1).
150 ObsolescenceMarkerInvalid,
151 /// A revision state move that is not an edge of the state machine: backwards, in place,
152 /// skipping a state, or to `Verified` without its claims and required actions discharged
153 /// (ADR 0003 section 5.3, step B4).
154 RevisionStateMoveInvalid,
155 /// A move of a revision to `Canonical` that does not come from the promotion queue
156 /// (ADR 0003 sections 5.3 and 5.5, step B4).
157 CanonicalOutsidePromotionQueue,
158 /// Strict recovery found a WAL kind 9 state move whose mover signature does not verify
159 /// or whose mover key is not the audience of its chain's leaf link: the log was written
160 /// without the mover's private key (ADR 0003 sections 5.3 and 5.4, step B4, issue #89).
161 RevisionStateMoveUnverified,
162 /// Strict recovery of a store opened with a revision seal key found a revision record
163 /// (kind 7, 8, 9, 10, or 11) whose server seal is missing or does not verify against the
164 /// seal chain so far: it was written, changed, reordered, or followed by a removed record
165 /// without the server's key (issue #101).
166 RevisionRecordUnsealed,
167 /// A `DerivationAttestation` does not name the revision it is presented with, or its
168 /// signature does not verify under the server key it names (ADR 0003 section 5.1, step B5).
169 DerivationSignatureInvalid,
170 /// The server key a `DerivationAttestation` names is not the server key of the repository
171 /// identity document in effect at the admission `WalSeq`, or no document is in effect
172 /// (step B5).
173 DerivationServerKeyUnregistered,
174 /// The identity documents a derivation is checked against belong to another repository
175 /// than the one its `DerivationAttestation` names, so their `server_key` says nothing
176 /// about this derivation (step B5).
177 DerivationIdentityRepoMismatch,
178 /// A `DerivationAttestation` names inputs that do not fit its rule (kind, count, order,
179 /// duplicates) or that the replica does not hold: a revision not admitted in this
180 /// repository before the derivation, or a tree not in the tree store (step B5).
181 DerivationInputMismatch,
182 /// Recomputing the rule a `DerivationAttestation` names from the inputs it names fails, or
183 /// gives a `ChangesetId` or `TreeDigest` other than the ones it attests (step B5).
184 DerivationRecomputeMismatch,
185 /// A `DerivationAttestation` already admitted (the same attestation digest) is presented
186 /// again (step B5).
187 DerivationAttestationReplayed,
188
189 // Git and Radicle canonicality refusals
190 GitObjectCorrupt,
191 GitRefNonFastForward,
192 RadicleIdentityInvalid,
193 RadicleSignatureInvalid,
194 RadicleQuorumInsufficient,
195 StaleBaseHead,
196 SplitBrainDivergence,
197 /// A Git object the native model cannot hold without loss, so it could not be exported
198 /// with its original object ID (ADR 0003 step H1): a gitlink or empty subtree, an entry
199 /// name that is not a valid path segment, a mode other than the canonical `100644`,
200 /// `100755`, `120000` and `40000`, or a commit or tag whose links are not written in
201 /// Git's canonical layout.
202 GitObjectNotRepresentable,
203
204 // Content admission refusals
205 /// An admitted blob matches a rule of the versioned secret-scanning rule set (a private key
206 /// block, a provider token format, or a high-entropy value assigned to a secret-like name).
207 /// The refusal names the rule and byte offset only, never the matched bytes (ADR 0003
208 /// section 5.13, step M1).
209 SecretDetected,
210}
211
212/// Structured error pairing a deterministic `RefusalCode` with diagnostic context.
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct SynapseError {
215 pub code: RefusalCode,
216 pub message: String,
217}
218
219impl SynapseError {
220 pub fn new(code: RefusalCode, message: impl Into<String>) -> Self {
221 Self {
222 code,
223 message: message.into(),
224 }
225 }
226}
227
228impl fmt::Display for SynapseError {
229 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230 write!(f, "{:?}: {}", self.code, self.message)
231 }
232}
233
234impl std::error::Error for SynapseError {}
235
236/// Result alias for Synapse operations.
237pub type SynapseResult<T> = Result<T, SynapseError>;
238
239/// Validated repository identifier (e.g. `"aien-spark/aien-sovereign-core"`).
240#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
241pub struct RepoId(String);
242
243impl RepoId {
244 pub fn new(raw: impl Into<String>) -> SynapseResult<Self> {
245 let s = raw.into();
246 if s.is_empty() || s.len() > 128 {
247 return Err(SynapseError::new(
248 RefusalCode::RepoIdInvalid,
249 "repository id must be 1..=128 ASCII characters",
250 ));
251 }
252 if !s
253 .bytes()
254 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'/'))
255 || s.starts_with('/')
256 || s.ends_with('/')
257 || s.contains("//")
258 || s.contains("..")
259 {
260 return Err(SynapseError::new(
261 RefusalCode::RepoIdInvalid,
262 format!("invalid repository id: {s}"),
263 ));
264 }
265 Ok(Self(s))
266 }
267
268 pub fn as_str(&self) -> &str {
269 &self.0
270 }
271}
272
273impl fmt::Display for RepoId {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.write_str(&self.0)
276 }
277}
278
279/// Monotonic 64-bit sequence number in the single-writer WAL.
280/// Defines local ingest and replay order; never confers canonical branch authority.
281#[derive(
282 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
283)]
284pub struct WalSeq(pub u64);
285
286impl WalSeq {
287 pub const ZERO: Self = Self(0);
288
289 pub fn next(self) -> Self {
290 Self(self.0.saturating_add(1))
291 }
292}
293
294impl fmt::Display for WalSeq {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 write!(f, "wal:{}", self.0)
297 }
298}
299
300/// 32-byte domain-separated SHA-256 digest of a canonical `ChangesetEnvelope`.
301/// Distinct from `GitOid`, `BlobDigest`, `WorldId`, and `SemanticId`.
302#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
303pub struct ChangesetId(pub [u8; 32]);
304
305impl ChangesetId {
306 pub fn to_hex(self) -> String {
307 hex::encode(self.0)
308 }
309
310 pub fn from_hex(s: &str) -> SynapseResult<Self> {
311 let bytes = hex::decode(s).map_err(|_| {
312 SynapseError::new(
313 RefusalCode::ChangesetNotFound,
314 "invalid hex for ChangesetId",
315 )
316 })?;
317 let arr: [u8; 32] = bytes.try_into().map_err(|_| {
318 SynapseError::new(
319 RefusalCode::ChangesetNotFound,
320 "ChangesetId must be 32 bytes (64 hex chars)",
321 )
322 })?;
323 Ok(Self(arr))
324 }
325}
326
327impl fmt::Debug for ChangesetId {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 write!(f, "ChangesetId({})", self.to_hex())
330 }
331}
332
333impl fmt::Display for ChangesetId {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.write_str(&self.to_hex())
336 }
337}
338
339/// 32-byte domain-separated SHA-256 digest of immutable blob content stored in Synapse.
340#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
341pub struct BlobDigest(pub [u8; 32]);
342
343impl BlobDigest {
344 pub fn compute(data: &[u8]) -> Self {
345 let mut hasher = Sha256::new();
346 hasher.update(DOMAIN_BLOB_V1);
347 hasher.update((data.len() as u64).to_le_bytes());
348 hasher.update(data);
349 Self(hasher.finalize().into())
350 }
351
352 pub fn to_hex(self) -> String {
353 hex::encode(self.0)
354 }
355
356 pub fn from_hex(s: &str) -> SynapseResult<Self> {
357 let bytes = hex::decode(s).map_err(|_| {
358 SynapseError::new(
359 RefusalCode::BlobDigestMismatch,
360 "invalid hex for BlobDigest",
361 )
362 })?;
363 let arr: [u8; 32] = bytes.try_into().map_err(|_| {
364 SynapseError::new(
365 RefusalCode::BlobDigestMismatch,
366 "BlobDigest must be 32 bytes (64 hex chars)",
367 )
368 })?;
369 Ok(Self(arr))
370 }
371}
372
373impl fmt::Debug for BlobDigest {
374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 write!(f, "BlobDigest({})", self.to_hex())
376 }
377}
378
379impl fmt::Display for BlobDigest {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 f.write_str(&self.to_hex())
382 }
383}
384
385/// The Git tree payload a canonical tree node (C1, version 1) stands for: per entry, in the
386/// node's order (which is Git's tree order), `{mode} {name}\0{oid}`, where a file's mode is
387/// [`FileMode::git_octal_str`] and a directory's is `40000`. `blob_oid` and `tree_oid` give
388/// the Git ID of each entry. Both the Git bridge's export and the store's check of a mapped
389/// tree's Git ID use this one function.
390pub fn git_tree_payload_of_node(
391 node: &[u8],
392 blob_oid: &mut dyn FnMut(BlobDigest) -> SynapseResult<GitOid>,
393 tree_oid: &mut dyn FnMut(TreeDigest) -> SynapseResult<GitOid>,
394) -> SynapseResult<Vec<u8>> {
395 let mut out = Vec::with_capacity(node.len());
396 for e in decode_tree_node(node)? {
397 let (mode, oid) = match e.kind {
398 TreeNodeEntryKind::File { mode, blob, .. } => (mode.git_octal_str(), blob_oid(blob)?),
399 TreeNodeEntryKind::Dir(child) => ("40000", tree_oid(child)?),
400 };
401 out.extend_from_slice(mode.as_bytes());
402 out.push(b' ');
403 out.extend_from_slice(e.name.as_bytes());
404 out.push(0);
405 out.extend_from_slice(&oid.0);
406 }
407 Ok(out)
408}
409
410/// 20-byte standard Git SHA-1 object identifier (`blob`, `tree`, or `commit`).
411/// Distinct from `ChangesetId` and `BlobDigest`.
412#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
413pub struct GitOid(pub [u8; 20]);
414
415impl GitOid {
416 pub const ZERO: Self = Self([0u8; 20]);
417
418 pub fn compute_git_object(kind: &str, payload: &[u8]) -> Self {
419 let mut hasher = Sha1::new();
420 let header = format!("{kind} {}\0", payload.len());
421 hasher.update(header.as_bytes());
422 hasher.update(payload);
423 Self(hasher.finalize().into())
424 }
425
426 pub fn compute_blob(payload: &[u8]) -> Self {
427 Self::compute_git_object("blob", payload)
428 }
429
430 pub fn to_hex(self) -> String {
431 hex::encode(self.0)
432 }
433
434 pub fn from_hex(s: &str) -> SynapseResult<Self> {
435 let bytes = hex::decode(s).map_err(|_| {
436 SynapseError::new(RefusalCode::GitObjectCorrupt, "invalid hex for GitOid")
437 })?;
438 let arr: [u8; 20] = bytes.try_into().map_err(|_| {
439 SynapseError::new(
440 RefusalCode::GitObjectCorrupt,
441 "GitOid must be 20 bytes (40 hex chars)",
442 )
443 })?;
444 Ok(Self(arr))
445 }
446}
447
448impl fmt::Debug for GitOid {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450 write!(f, "GitOid({})", self.to_hex())
451 }
452}
453
454impl fmt::Display for GitOid {
455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456 f.write_str(&self.to_hex())
457 }
458}
459
460/// 32-byte client-supplied idempotency key for deduplicating changeset submissions.
461#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
462pub struct IdempotencyKey(pub [u8; 32]);
463
464impl IdempotencyKey {
465 pub fn from_label(label: &str) -> Self {
466 let mut hasher = Sha256::new();
467 hasher.update(b"SYNAPSE_IDEMPOTENCY_V1\0");
468 hasher.update(label.as_bytes());
469 Self(hasher.finalize().into())
470 }
471
472 pub fn to_hex(self) -> String {
473 hex::encode(self.0)
474 }
475}
476
477impl fmt::Debug for IdempotencyKey {
478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479 write!(f, "IdempotencyKey({})", self.to_hex())
480 }
481}
482
483/// One unit of intended work across all its rewrites and retries (ADR 0003 section 5.1):
484/// 16 random bytes, not content-derived (content changes on rewrite). A capability link's
485/// change scope names the `ChangeId`s its holder may join (step F1); the first admission under
486/// a `ChangeId` binds it to its creating chain (step B1, [`ChainPath`]).
487#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
488pub struct ChangeId(pub [u8; 16]);
489
490impl ChangeId {
491 pub fn to_hex(self) -> String {
492 hex::encode(self.0)
493 }
494
495 pub fn from_hex(s: &str) -> SynapseResult<Self> {
496 hex::decode(s)
497 .ok()
498 .and_then(|b| <[u8; 16]>::try_from(b).ok())
499 .map(Self)
500 .ok_or_else(|| {
501 SynapseError::new(
502 RefusalCode::EnvelopeMalformed,
503 "ChangeId must be 16 bytes (32 hex chars)",
504 )
505 })
506 }
507}
508
509impl fmt::Debug for ChangeId {
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 write!(f, "ChangeId({})", self.to_hex())
512 }
513}
514
515impl fmt::Display for ChangeId {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 f.write_str(&self.to_hex())
518 }
519}
520
521/// Human-facing GitHub Pull Request projection record.
522/// Merging a GitHub PR never by itself confers a `RadicleCanonicalHead`.
523#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
524pub struct GitHubPullRequestProjection {
525 pub repo_id: RepoId,
526 pub pr_number: u64,
527 pub changeset_id: ChangesetId,
528 pub head_git_oid: GitOid,
529 pub base_git_oid: GitOid,
530 pub pr_branch_ref: String,
531 pub title: String,
532 pub body_markdown: String,
533 pub evidence_summary_digest: [u8; 32],
534 pub github_merged: bool,
535}
536
537/// Cryptographically verified Radicle canonical head receipt.
538/// Produced only after verifying `refs/rad/id` and at least `threshold` delegate
539/// Ed25519 signatures over `refs/namespaces/<nid>/refs/rad/sigrefs`.
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541pub struct RadicleCanonicalHead {
542 pub repo_id: RepoId,
543 pub default_branch: String,
544 pub canonical_git_oid: GitOid,
545 pub promoted_changeset_id: Option<ChangesetId>,
546 pub rad_id_commit_oid: GitOid,
547 pub threshold: usize,
548 pub verified_delegates: Vec<String>,
549 pub verified_at_ms: u64,
550}
551
552/// Supported file modes in a repository tree.
553#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
554pub enum FileMode {
555 Regular644,
556 Executable755,
557 Symlink120000,
558}
559
560impl FileMode {
561 pub fn git_octal_str(self) -> &'static str {
562 match self {
563 Self::Regular644 => "100644",
564 Self::Executable755 => "100755",
565 Self::Symlink120000 => "120000",
566 }
567 }
568
569 pub fn tag_byte(self) -> u8 {
570 match self {
571 Self::Regular644 => 1,
572 Self::Executable755 => 2,
573 Self::Symlink120000 => 3,
574 }
575 }
576
577 /// The mode with tag byte `tag` (1, 2 or 3), if any.
578 pub fn from_tag_byte(tag: u8) -> Option<Self> {
579 match tag {
580 1 => Some(Self::Regular644),
581 2 => Some(Self::Executable755),
582 3 => Some(Self::Symlink120000),
583 _ => None,
584 }
585 }
586}
587
588/// Atomic mutation operation on a single normalized repository path.
589#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
590pub enum MutationOp {
591 Upsert {
592 mode: FileMode,
593 blob_digest: BlobDigest,
594 size_bytes: u64,
595 },
596 Delete,
597}
598
599/// A path-level mutation within a `ChangesetEnvelope`.
600#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
601pub struct PathMutation {
602 pub path: String,
603 pub op: MutationOp,
604}
605
606/// Bounded machine evidence receipt attached to a changeset (full logs stay in Synapse).
607#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
608pub struct EvidenceAttachment {
609 pub gate_name: String,
610 pub passed: bool,
611 pub artifact_digest: [u8; 32],
612 pub summary: String,
613}
614
615/// Signed, immutable changeset proposal envelope (`SYNAPSE_ENVELOPE_VERSION = 1`).
616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
617pub struct ChangesetEnvelope {
618 pub version: u16,
619 pub repo_id: RepoId,
620 pub base_git_oid: GitOid,
621 pub parent_changesets: Vec<ChangesetId>,
622 pub author_did: String,
623 pub idempotency_key: IdempotencyKey,
624 pub created_at_ms: u64,
625 pub intent_summary: String,
626 pub mutations: Vec<PathMutation>,
627 pub evidence_receipts: Vec<EvidenceAttachment>,
628 pub signature: Vec<u8>,
629}
630
631impl ChangesetEnvelope {
632 /// Validate envelope version, path normalization, sort order, and Ed25519 signature.
633 pub fn validate(&self) -> SynapseResult<ChangesetId> {
634 if self.version != SYNAPSE_ENVELOPE_VERSION {
635 return Err(SynapseError::new(
636 RefusalCode::EnvelopeVersionUnsupported,
637 format!("unsupported envelope version {}", self.version),
638 ));
639 }
640 validate_intent_summary(&self.intent_summary)?;
641 validate_parent_changesets(&self.parent_changesets)?;
642 validate_mutations(&self.mutations)?;
643
644 // Verify author_did and Ed25519 signature
645 let pubkey_bytes = decode_did_key_ed25519(&self.author_did)?;
646 let verifying_key = cached_verifying_key(&pubkey_bytes).map_err(|_| {
647 SynapseError::new(RefusalCode::DidKeyInvalid, "invalid Ed25519 public key")
648 })?;
649 let sig_arr: [u8; 64] = self.signature.as_slice().try_into().map_err(|_| {
650 SynapseError::new(
651 RefusalCode::AuthSignatureInvalid,
652 "signature must be 64 bytes",
653 )
654 })?;
655 let sig = Signature::from_bytes(&sig_arr);
656 let signable = self.canonical_signable_bytes();
657 verifying_key.verify(&signable, &sig).map_err(|_| {
658 SynapseError::new(
659 RefusalCode::AuthSignatureInvalid,
660 "Ed25519 signature verification failed for changeset envelope",
661 )
662 })?;
663
664 Ok(self.compute_id())
665 }
666
667 /// Sign the envelope using an Ed25519 `SigningKey`, setting `author_did` and `signature`.
668 pub fn sign(&mut self, signing_key: &SigningKey) {
669 self.author_did = encode_did_key_ed25519(&signing_key.verifying_key().to_bytes());
670 let signable = self.canonical_signable_bytes();
671 let sig = signing_key.sign(&signable);
672 self.signature = sig.to_bytes().to_vec();
673 }
674
675 /// Deterministically encode all unsigned fields with domain separation for Ed25519 signing.
676 pub fn canonical_signable_bytes(&self) -> Vec<u8> {
677 let mut buf = Vec::with_capacity(512);
678 buf.extend_from_slice(DOMAIN_CHANGESET_SIGN_V1);
679 buf.extend_from_slice(&self.version.to_le_bytes());
680 put_str(&mut buf, self.repo_id.as_str());
681 buf.extend_from_slice(&self.base_git_oid.0);
682 buf.extend_from_slice(&(self.parent_changesets.len() as u32).to_le_bytes());
683 for parent in &self.parent_changesets {
684 buf.extend_from_slice(&parent.0);
685 }
686 put_str(&mut buf, &self.author_did);
687 buf.extend_from_slice(&self.idempotency_key.0);
688 buf.extend_from_slice(&self.created_at_ms.to_le_bytes());
689 put_str(&mut buf, &self.intent_summary);
690 buf.extend_from_slice(&(self.mutations.len() as u32).to_le_bytes());
691 for m in &self.mutations {
692 put_str(&mut buf, &m.path);
693 match &m.op {
694 MutationOp::Upsert {
695 mode,
696 blob_digest,
697 size_bytes,
698 } => {
699 buf.push(1);
700 buf.push(mode.tag_byte());
701 buf.extend_from_slice(&blob_digest.0);
702 buf.extend_from_slice(&size_bytes.to_le_bytes());
703 }
704 MutationOp::Delete => {
705 buf.push(2);
706 }
707 }
708 }
709 buf.extend_from_slice(&(self.evidence_receipts.len() as u32).to_le_bytes());
710 for ev in &self.evidence_receipts {
711 put_str(&mut buf, &ev.gate_name);
712 buf.push(u8::from(ev.passed));
713 buf.extend_from_slice(&ev.artifact_digest);
714 put_str(&mut buf, &ev.summary);
715 }
716 buf
717 }
718
719 /// Compute the domain-separated `ChangesetId` over the canonical signable bytes and signature.
720 pub fn compute_id(&self) -> ChangesetId {
721 let mut hasher = Sha256::new();
722 hasher.update(DOMAIN_CHANGESET_ID_V1);
723 let signable = self.canonical_signable_bytes();
724 hasher.update((signable.len() as u64).to_le_bytes());
725 hasher.update(&signable);
726 hasher.update((self.signature.len() as u64).to_le_bytes());
727 hasher.update(&self.signature);
728 ChangesetId(hasher.finalize().into())
729 }
730}
731
732fn put_str(buf: &mut Vec<u8>, s: &str) {
733 buf.extend_from_slice(&(s.len() as u32).to_le_bytes());
734 buf.extend_from_slice(s.as_bytes());
735}
736
737/// Longest `intent_summary` in either envelope version.
738pub const MAX_INTENT_SUMMARY_BYTES: usize = 4096;
739
740/// An intent summary must be 1..=`MAX_INTENT_SUMMARY_BYTES` bytes (envelopes v1 and v2).
741pub(crate) fn validate_intent_summary(intent_summary: &str) -> SynapseResult<()> {
742 if intent_summary.is_empty() || intent_summary.len() > MAX_INTENT_SUMMARY_BYTES {
743 return Err(SynapseError::new(
744 RefusalCode::QuotaPayloadTooLarge,
745 "intent_summary must be 1..=4096 bytes",
746 ));
747 }
748 Ok(())
749}
750
751/// Parent changesets must be strictly ascending (sorted and unique).
752pub(crate) fn validate_parent_changesets(parents: &[ChangesetId]) -> SynapseResult<()> {
753 for pair in parents.windows(2) {
754 if pair[0] >= pair[1] {
755 return Err(SynapseError::new(
756 RefusalCode::MutationsUnsorted,
757 "parent_changesets must be strictly sorted and unique",
758 ));
759 }
760 }
761 Ok(())
762}
763
764/// Mutations must be non-empty, on valid repository-relative paths, strictly sorted by path.
765pub(crate) fn validate_mutations(mutations: &[PathMutation]) -> SynapseResult<()> {
766 if mutations.is_empty() {
767 return Err(SynapseError::new(
768 RefusalCode::PathInvalid,
769 "changeset must contain at least one path mutation",
770 ));
771 }
772 let mut prev_path: Option<&str> = None;
773 for m in mutations {
774 validate_repo_relative_path(&m.path)?;
775 if let Some(prev) = prev_path {
776 if prev == m.path {
777 return Err(SynapseError::new(
778 RefusalCode::PathDuplicate,
779 format!("duplicate path in changeset: {}", m.path),
780 ));
781 }
782 if prev > m.path.as_str() {
783 return Err(SynapseError::new(
784 RefusalCode::MutationsUnsorted,
785 format!("unsorted path in changeset: {} after {}", m.path, prev),
786 ));
787 }
788 }
789 prev_path = Some(&m.path);
790 }
791 Ok(())
792}
793
794/// Validate that a path is a clean, normalized repository-relative POSIX path.
795/// Refuses leading/trailing `/`, empty segments, `.` or `..`, backslashes, NULs, and `.git`.
796pub fn validate_repo_relative_path(path: &str) -> SynapseResult<()> {
797 if path.is_empty() || path.len() > 2048 {
798 return Err(SynapseError::new(
799 RefusalCode::PathInvalid,
800 "path must be 1..=2048 bytes",
801 ));
802 }
803 if path.starts_with('/') || path.ends_with('/') || path.contains('\\') || path.contains('\0') {
804 return Err(SynapseError::new(
805 RefusalCode::PathInvalid,
806 format!("path contains forbidden slash or control characters: {path}"),
807 ));
808 }
809 for segment in path.split('/') {
810 if segment.is_empty() || segment == "." || segment == ".." || segment == ".git" {
811 return Err(SynapseError::new(
812 RefusalCode::PathInvalid,
813 format!("path contains forbidden segment '{segment}': {path}"),
814 ));
815 }
816 }
817 Ok(())
818}
819
820const BASE58_ALPHABET: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
821
822/// Encode raw bytes into Base58btc (Bitcoin alphabet used by Multibase `z` in Radicle).
823pub fn base58btc_encode(input: &[u8]) -> String {
824 let mut zeros = 0;
825 while zeros < input.len() && input[zeros] == 0 {
826 zeros += 1;
827 }
828 let mut digits = Vec::with_capacity(input.len() * 138 / 100 + 1);
829 for &byte in &input[zeros..] {
830 let mut carry = u32::from(byte);
831 for d in &mut digits {
832 carry += u32::from(*d) << 8;
833 *d = (carry % 58) as u8;
834 carry /= 58;
835 }
836 while carry > 0 {
837 digits.push((carry % 58) as u8);
838 carry /= 58;
839 }
840 }
841 let mut out = String::with_capacity(zeros + digits.len());
842 for _ in 0..zeros {
843 out.push('1');
844 }
845 for &d in digits.iter().rev() {
846 out.push(char::from(BASE58_ALPHABET[d as usize]));
847 }
848 out
849}
850
851/// Decode Base58btc string into raw bytes.
852pub fn base58btc_decode(input: &str) -> SynapseResult<Vec<u8>> {
853 let bytes = input.as_bytes();
854 let mut zeros = 0;
855 while zeros < bytes.len() && bytes[zeros] == b'1' {
856 zeros += 1;
857 }
858 let mut b256 = Vec::with_capacity(bytes.len() * 733 / 1000 + 1);
859 for &ch in &bytes[zeros..] {
860 let val = BASE58_ALPHABET
861 .iter()
862 .position(|&c| c == ch)
863 .ok_or_else(|| {
864 SynapseError::new(RefusalCode::DidKeyInvalid, "invalid base58btc char")
865 })? as u32;
866 let mut carry = val;
867 for b in &mut b256 {
868 carry += u32::from(*b) * 58;
869 *b = (carry & 0xff) as u8;
870 carry >>= 8;
871 }
872 while carry > 0 {
873 b256.push((carry & 0xff) as u8);
874 carry >>= 8;
875 }
876 }
877 let mut out = vec![0u8; zeros];
878 out.extend(b256.into_iter().rev());
879 Ok(out)
880}
881
882/// Encode a 32-byte Ed25519 public key as a Radicle-compatible `did:key:z6Mk...` string.
883pub fn encode_did_key_ed25519(pubkey: &[u8; 32]) -> String {
884 let mut prefixed = [0u8; 34];
885 prefixed[0] = 0xed;
886 prefixed[1] = 0x01;
887 prefixed[2..].copy_from_slice(pubkey);
888 format!("did:key:z{}", base58btc_encode(&prefixed))
889}
890
891/// Decode a `did:key:z6Mk...` (or `z6Mk...` Radicle NID) into a 32-byte Ed25519 public key.
892pub fn decode_did_key_ed25519(did: &str) -> SynapseResult<[u8; 32]> {
893 let multibase = did.strip_prefix("did:key:").unwrap_or(did);
894 let b58 = multibase.strip_prefix('z').ok_or_else(|| {
895 SynapseError::new(
896 RefusalCode::DidKeyInvalid,
897 "did:key must use multibase 'z' (base58btc)",
898 )
899 })?;
900 let decoded = base58btc_decode(b58)?;
901 if decoded.len() != 34 || decoded[0] != 0xed || decoded[1] != 0x01 {
902 return Err(SynapseError::new(
903 RefusalCode::DidKeyInvalid,
904 "did:key must have Ed25519 multicodec prefix 0xed01 and 32-byte key",
905 ));
906 }
907 let mut out = [0u8; 32];
908 out.copy_from_slice(&decoded[2..34]);
909 Ok(out)
910}
911
912#[cfg(test)]
913mod tests {
914 use super::*;
915 use std::path::Path;
916
917 #[test]
918 fn test_radicle_did_key_roundtrip_and_real_spark_did() {
919 // Real Radicle DID from `rad self` on the DGX Spark:
920 let real_did = "did:key:z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK";
921 let pubkey = decode_did_key_ed25519(real_did).expect("decode real Radicle DID");
922 let reencoded = encode_did_key_ed25519(&pubkey);
923 assert_eq!(reencoded, real_did);
924
925 // Also accept bare Radicle NID without `did:key:` prefix
926 let nid = "z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK";
927 assert_eq!(decode_did_key_ed25519(nid).unwrap(), pubkey);
928 }
929
930 #[test]
931 fn test_distinct_identities_and_domain_separation() {
932 let payload = b"fn main() {}\n";
933 let blob_digest = BlobDigest::compute(payload);
934 let git_oid = GitOid::compute_blob(payload);
935 assert_ne!(&blob_digest.0[..20], &git_oid.0[..]);
936
937 let signing_key = SigningKey::from_bytes(&[7u8; 32]);
938 let mut env = ChangesetEnvelope {
939 version: SYNAPSE_ENVELOPE_VERSION,
940 repo_id: RepoId::new("aien-spark/synapse").unwrap(),
941 base_git_oid: git_oid,
942 parent_changesets: vec![],
943 author_did: String::new(),
944 idempotency_key: IdempotencyKey::from_label("req-001"),
945 created_at_ms: 1_789_800_000_000,
946 intent_summary: "Add main entrypoint".to_string(),
947 mutations: vec![PathMutation {
948 path: "src/main.rs".to_string(),
949 op: MutationOp::Upsert {
950 mode: FileMode::Regular644,
951 blob_digest,
952 size_bytes: payload.len() as u64,
953 },
954 }],
955 evidence_receipts: vec![EvidenceAttachment {
956 gate_name: "cargo-test".to_string(),
957 passed: true,
958 artifact_digest: [0x11; 32],
959 summary: "12 passed, 0 failed".to_string(),
960 }],
961 signature: vec![],
962 };
963 env.sign(&signing_key);
964
965 let cs_id = env.validate().expect("valid signed envelope");
966 assert_ne!(cs_id.0, blob_digest.0);
967
968 // Tampering with intent_summary must fail signature verification
969 let mut tampered = env.clone();
970 tampered.intent_summary = "Tampered summary".to_string();
971 let err = tampered.validate().unwrap_err();
972 assert_eq!(err.code, RefusalCode::AuthSignatureInvalid);
973 }
974
975 #[test]
976 fn test_path_validation_refuses_traversal_and_git_dir() {
977 assert!(validate_repo_relative_path("crates/synapse-core/src/lib.rs").is_ok());
978 for bad in [
979 "",
980 "/etc/passwd",
981 "src/../secrets",
982 "./src/lib.rs",
983 ".git/config",
984 "sub/.git/hooks/pre-commit",
985 "trailing/",
986 "back\\slash.rs",
987 ] {
988 let err = validate_repo_relative_path(bad).unwrap_err();
989 assert_eq!(err.code, RefusalCode::PathInvalid, "path {bad} must fail");
990 }
991 }
992
993 #[test]
994 fn test_unslop_zero_em_or_en_dashes_across_workspace() {
995 let root = Path::new(env!("CARGO_MANIFEST_DIR"))
996 .parent()
997 .unwrap()
998 .parent()
999 .unwrap();
1000 let mut checked = 0usize;
1001 check_dir_unslop(root, &mut checked);
1002 assert!(checked >= 5, "expected to check workspace files");
1003 }
1004
1005 fn check_dir_unslop(dir: &Path, checked: &mut usize) {
1006 let entries = std::fs::read_dir(dir).expect("read_dir");
1007 for entry in entries {
1008 let entry = entry.expect("entry");
1009 let path = entry.path();
1010 let name = entry.file_name();
1011 let name_str = name.to_string_lossy();
1012 if name_str == ".git" || name_str == "target" {
1013 continue;
1014 }
1015 if path.is_dir() {
1016 check_dir_unslop(&path, checked);
1017 } else if matches!(
1018 path.extension().and_then(|e| e.to_str()),
1019 Some("rs" | "md" | "toml" | "json" | "sh")
1020 ) && name_str != "Cargo.lock"
1021 {
1022 let content = std::fs::read_to_string(&path).expect("read text file");
1023 assert!(
1024 !content.contains('\u{2014}'),
1025 "em dash found in {}",
1026 path.display()
1027 );
1028 assert!(
1029 !content.contains('\u{2013}'),
1030 "en dash found in {}",
1031 path.display()
1032 );
1033 *checked += 1;
1034 }
1035 }
1036 }
1037}