Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-store/src/revision.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-store / src / revision.rs` 2434 lines ยท 104575 bytes Raw Blame History 1 //! Revision ledger: envelope v2 revisions, their change identities, admission witnesses, 2 //! obsolescence markers (ADR 0003 section 5.1, step B1; `docs/B1_CHANGE_IDENTITY.md`), and 3 //! revision states with owner-chain visibility (section 5.3, step B4; 4 //! `docs/B4_REVISION_STATES.md`). 5 //! 6 //! The ledger is a pure function of the revision records (`RevisionAdmitted`, 7 //! `ObsolescenceRecorded`, `RevisionStateMoved`) applied in `WalSeq` order: replay, a 8 //! checkpoint (which keeps the records themselves), and a live store all rebuild exactly the 9 //! same ledger. v1 changesets stay in their own map with their own IDs; the two ID domains 10 //! never meet. 11 12 use crate::seal::{next_head, RevisionSealKey}; 13 use crate::{SignedStateMove, StateMoveFault, WalRecord}; 14 use sha2::{Digest, Sha256}; 15 use std::collections::{BTreeMap, BTreeSet}; 16 use synapse_core::{ 17 derive_revision_output, AdmissionWitness, AuthorshipAttestation, BlobDigest, ChainPath, 18 ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, DerivationTrees, 19 DerivedRevision, IdempotencyKey, MutationOp, ObsolescenceKind, ObsolescenceMarker, RefusalCode, 20 RepoId, RevisionContent, RevisionState, ServerKeyLookup, ServerKeyRegistry, SynapseError, 21 SynapseResult, WalSeq, 22 }; 23 24 /// Domain tag of the revision part of the state root (only hashed when revisions exist). 25 pub const DOMAIN_STATE_ROOT_REVISIONS_V1: &[u8] = b"SYNAPSE_STATE_ROOT_REVISIONS_V1\0"; 26 27 /// The authority an admission was granted under, from the verified delegation chain. 28 #[derive(Debug, Clone, PartialEq, Eq)] 29 pub struct AdmissionAuthority { 30 /// The request's chain (link digests, root first). 31 pub chain: ChainPath, 32 /// `ChangeId`s the chain's leaf grant names explicitly in its change scope. A grant 33 /// that allows any change names none: it never lets a key join a change outside its 34 /// creating chain. 35 pub change_scope: Vec, 36 } 37 38 /// One admitted revision: its content, every authorship attestation (agents), every 39 /// derivation attestation (the server, step B5), and every admission witness, in admission 40 /// order. A revision only the server derived has no authorship attestation. 41 #[derive(Debug, Clone, PartialEq, Eq)] 42 pub struct StoredRevision { 43 pub repo_id: RepoId, 44 pub changeset_id: ChangesetId, 45 pub content: RevisionContent, 46 /// Sequence of the first admission. 47 pub first_seq: WalSeq, 48 pub attestations: Vec, 49 pub derivations: Vec, 50 pub witnesses: Vec, 51 /// Current state (step B4): `Private` from the first admission; it only moves forward. 52 pub state: RevisionState, 53 } 54 55 /// A recorded obsolescence marker with the chain it was recorded under. 56 #[derive(Debug, Clone, PartialEq, Eq)] 57 pub struct RecordedMarker { 58 pub seq: WalSeq, 59 pub marker: ObsolescenceMarker, 60 pub chain: ChainPath, 61 pub recorded_at_ms: u64, 62 } 63 64 /// Status of one change: its creating chain, revisions, and which of them are live. 65 #[derive(Debug, Clone, PartialEq, Eq)] 66 pub struct ChangeStatus { 67 pub repo_id: RepoId, 68 pub change_id: ChangeId, 69 /// The chain of the first admission under this `ChangeId`. 70 pub creating_chain: ChainPath, 71 /// Every revision, in first-admission order. 72 pub revisions: Vec, 73 /// Revisions no marker names as predecessor, in first-admission order. 74 pub live: Vec, 75 /// Revisions some marker names as predecessor, in first-admission order. 76 pub obsolete: Vec, 77 pub markers: Vec, 78 /// More than one live revision: divergent attempts (ADR 0003 section 5.1). 79 pub divergent: bool, 80 } 81 82 /// Outcome of [`crate::SynapseStore::admit_revision`]. 83 #[derive(Debug, Clone, PartialEq, Eq)] 84 pub enum RevisionOutcome { 85 /// A new admission (a new revision, or a new attestation of an existing one) at 86 /// `wal_seq`. 87 Admitted { 88 wal_seq: WalSeq, 89 changeset_id: ChangesetId, 90 /// The revision already existed: this admission added an attestation and a witness. 91 joined_existing_revision: bool, 92 }, 93 /// The same repository, signer DID, and `IdempotencyKey` were already admitted with the 94 /// same revision: the first admission's `WalSeq`. 95 IdempotentDuplicate { 96 wal_seq: WalSeq, 97 changeset_id: ChangesetId, 98 }, 99 } 100 101 #[derive(Debug, Clone, Default)] 102 struct ChangeEntry { 103 creating_chain: Option, 104 revisions: Vec, 105 markers: Vec, 106 } 107 108 /// What replay did with WAL kind 9 state moves that changed nothing (ADR 0003 B4, issue 109 /// #89). A live store writes only moves that verify and are owner moves, so every count here 110 /// is a record written without the store: a forgery or a bug, never a normal event. 111 /// `StrictFailClosed` recovery refuses a store with any unverified move 112 /// (`RevisionStateMoveUnverified`); `TruncateTornTail` opens it with the moves applied as 113 /// no-ops and reports them here. 114 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] 115 pub struct StateMoveReplayReport { 116 /// Moves whose mover signature does not verify strictly. 117 pub signature_invalid: u64, 118 /// Moves whose mover key is not the audience of their chain's leaf link. 119 pub signer_not_chain_leaf: u64, 120 /// Verified moves that are not owner moves: not by an owner chain, not an edge the owner 121 /// may take, or naming an unknown revision (#88's replay rule; kept, change nothing). 122 pub not_owner_move: u64, 123 /// Sequence of the first unverified move (signature or leaf), for the refusal message. 124 pub first_unverified: Option<(WalSeq, StateMoveFault)>, 125 /// Unverified moves this process left out of a checkpoint (`checkpoint_and_compact` 126 /// under `TruncateTornTail`), so they are gone from the store and strict recovery 127 /// accepts it again. Not persisted: a reopened store reports zero. 128 pub dropped_by_compaction: u64, 129 } 130 131 impl StateMoveReplayReport { 132 /// Moves that do not verify (signature or leaf). 133 pub fn unverified(&self) -> u64 { 134 self.signature_invalid + self.signer_not_chain_leaf 135 } 136 } 137 138 /// What replay did with revision records whose keyed seal (issue #101) did not verify, in a 139 /// store opened with a seal key. A sealing store writes only sealed records, so every count 140 /// here is a record written without the server's key: a forgery, a removed or reordered 141 /// record (which breaks the seal chain from there on), or a record from before the store was 142 /// sealed. Such records stay in the log but change nothing. `StrictFailClosed` recovery 143 /// refuses the store (`RevisionRecordUnsealed`); `TruncateTornTail` opens it and reports them 144 /// here. All zero in a store opened without a seal key (seals are then not checked). 145 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] 146 pub struct SealReplayReport { 147 /// Revision records whose seal is missing or does not verify against the chain so far. 148 pub unsealed: u64, 149 /// Sequence of the first such record, for the refusal message. 150 pub first_unsealed: Option, 151 /// Unsealed records this process left out of a checkpoint (`checkpoint_and_compact` 152 /// under `TruncateTornTail`). Not persisted: a reopened store reports zero. 153 pub dropped_by_compaction: u64, 154 } 155 156 /// In-memory revision state, rebuilt from revision records. 157 #[derive(Debug, Clone, Default)] 158 pub(crate) struct RevisionLedger { 159 /// Every revision record applied, in sequence order (what checkpoints keep). 160 log: Vec<(WalSeq, WalRecord)>, 161 revisions: BTreeMap<(RepoId, ChangesetId), StoredRevision>, 162 changes: BTreeMap<(RepoId, ChangeId), ChangeEntry>, 163 /// (repository, signer key, idempotency key) to the first admission. 164 idempotency: BTreeMap<(RepoId, [u8; 32], IdempotencyKey), (WalSeq, ChangesetId)>, 165 /// Kind 9 records that changed nothing, by reason. 166 state_moves: StateMoveReplayReport, 167 /// (repository, derivation attestation digest) to its admission (replay refusal, B5). 168 derivations: BTreeMap<(RepoId, [u8; 32]), WalSeq>, 169 /// Public half of the seal key (issue #101): when set, a revision record is applied only 170 /// if its seal verifies against `seal_head`. 171 seal_key: Option<[u8; 32]>, 172 /// Head of the seal chain after the last sealed record applied (zero before the first). 173 seal_head: [u8; 32], 174 /// Revision records whose seal did not verify (applied as nothing). 175 unsealed: BTreeSet, 176 seals: SealReplayReport, 177 } 178 179 /// What a checkpoint keeps of the revision log, and what it leaves out. 180 pub(crate) struct CompactedRevisionLog { 181 pub(crate) log: Vec<(WalSeq, WalRecord)>, 182 pub(crate) dropped_moves: u64, 183 pub(crate) dropped_unsealed: u64, 184 } 185 186 /// Digest of one revision record over its canonical core encodings. 187 pub(crate) fn record_digest(record: &WalRecord) -> [u8; 32] { 188 let mut h = Sha256::new(); 189 h.update([record.kind_byte()]); 190 let mut chain = Vec::new(); 191 match record { 192 WalRecord::RevisionAdmitted { 193 envelope, 194 chain: c, 195 admitted_at_ms, 196 new_blobs, 197 .. 198 } => { 199 let e = envelope.encode(); 200 h.update((e.len() as u64).to_le_bytes()); 201 h.update(&e); 202 c.encode_into(&mut chain); 203 h.update(&chain); 204 h.update(admitted_at_ms.to_le_bytes()); 205 h.update((new_blobs.len() as u64).to_le_bytes()); 206 for b in new_blobs { 207 h.update(b.0); 208 } 209 } 210 WalRecord::ObsolescenceRecorded { 211 marker, 212 chain: c, 213 recorded_at_ms, 214 .. 215 } => { 216 let m = marker.encode(); 217 h.update((m.len() as u64).to_le_bytes()); 218 h.update(&m); 219 c.encode_into(&mut chain); 220 h.update(&chain); 221 h.update(recorded_at_ms.to_le_bytes()); 222 } 223 WalRecord::RevisionStateMoved { 224 state_move: m, 225 moved_at_ms, 226 .. 227 } => { 228 h.update((m.repo_id.as_str().len() as u64).to_le_bytes()); 229 h.update(m.repo_id.as_str().as_bytes()); 230 h.update(m.changeset_id.0); 231 h.update([m.to.tag_byte()]); 232 m.chain.encode_into(&mut chain); 233 h.update(&chain); 234 h.update(moved_at_ms.to_le_bytes()); 235 h.update(m.signed_at_ms.to_le_bytes()); 236 let link = m.leaf_link.encode(); 237 h.update((link.len() as u64).to_le_bytes()); 238 h.update(&link); 239 h.update(m.mover_key); 240 h.update(m.signature); 241 } 242 WalRecord::GitBridgeImported { repo_id, entry, .. } => { 243 crate::git_bridge::record_digest_input(repo_id, entry, &mut h); 244 } 245 WalRecord::DerivedRevisionAdmitted { 246 derived, 247 chain: c, 248 admitted_at_ms, 249 .. 250 } => { 251 let d = derived.encode(); 252 h.update((d.len() as u64).to_le_bytes()); 253 h.update(&d); 254 c.encode_into(&mut chain); 255 h.update(&chain); 256 h.update(admitted_at_ms.to_le_bytes()); 257 } 258 _ => {} 259 } 260 h.finalize().into() 261 } 262 263 fn not_found(msg: String) -> SynapseError { 264 SynapseError::new(RefusalCode::ChangesetNotFound, msg) 265 } 266 267 /// Owner chain rule (ADR 0003 section 5.3, step B4): `chain` owns a revision when it is, or 268 /// dominates, the chain of the revision's first admission (the key that submitted it and the 269 /// keys its grant descends from). A later admission of identical content (a B1 join) adds a 270 /// witness but never an owner: otherwise a joiner could read the owner's authorship records 271 /// and publish its `Private` attempt without the owner's consent. 272 fn owned_by(rev: &StoredRevision, chain: &ChainPath) -> bool { 273 rev.witnesses 274 .first() 275 .is_some_and(|w| chain.dominates(&w.chain)) 276 } 277 278 /// A `Private` revision is visible only to its owner chain; every later state is visible to 279 /// any chain (path `Read` scope is the API's filter). 280 fn visible_to(rev: &StoredRevision, viewer: &ChainPath) -> bool { 281 rev.state != RevisionState::Private || owned_by(rev, viewer) 282 } 283 284 impl RevisionLedger { 285 pub(crate) fn log(&self) -> &[(WalSeq, WalRecord)] { 286 &self.log 287 } 288 289 /// The log without the records whose seal did not verify (issue #101): the records that 290 /// took effect, in sequence order. 291 pub(crate) fn applied_log(&self) -> impl Iterator { 292 self.log 293 .iter() 294 .filter(|(seq, _)| !self.unsealed.contains(seq)) 295 } 296 297 /// Kind 9 records that changed nothing, by reason (issue #89). 298 pub(crate) fn state_move_report(&self) -> StateMoveReplayReport { 299 self.state_moves 300 } 301 302 /// What a checkpoint keeps: the log without the records that changed nothing because 303 /// they do not verify, and how many were left out. Unsealed records (issue #101) go, 304 /// since they never joined the seal chain; so do kind 9 records that do not verify 305 /// (review of PR #100), unless they are sealed: removing a sealed record would break 306 /// the chain of every later one. Verified moves that changed nothing stay. 307 pub(crate) fn compacted_log(&self) -> CompactedRevisionLog { 308 let mut out = CompactedRevisionLog { 309 log: Vec::with_capacity(self.log.len()), 310 dropped_moves: 0, 311 dropped_unsealed: 0, 312 }; 313 for (seq, record) in &self.log { 314 if self.unsealed.contains(seq) { 315 out.dropped_unsealed += 1; 316 continue; 317 } 318 if let WalRecord::RevisionStateMoved { state_move, .. } = record { 319 if self.seal_key.is_none() && state_move.verify().is_err() { 320 out.dropped_moves += 1; 321 continue; 322 } 323 } 324 out.log.push((*seq, record.clone())); 325 } 326 out 327 } 328 329 /// Rebuild from the log a checkpoint kept, recording what it left out. 330 pub(crate) fn rebuild_after_compaction(&mut self, compacted: CompactedRevisionLog) { 331 let moves = self.state_moves.dropped_by_compaction + compacted.dropped_moves; 332 let unsealed = self.seals.dropped_by_compaction + compacted.dropped_unsealed; 333 *self = Self::from_log(compacted.log, self.seal_key); 334 self.state_moves.dropped_by_compaction = moves; 335 self.seals.dropped_by_compaction = unsealed; 336 } 337 338 /// An empty ledger that checks seals under `seal_key` when it is set (issue #101). 339 pub(crate) fn new(seal_key: Option<[u8; 32]>) -> Self { 340 Self { 341 seal_key, 342 ..Self::default() 343 } 344 } 345 346 /// Rebuild a ledger from checkpointed records. 347 pub(crate) fn from_log(log: Vec<(WalSeq, WalRecord)>, seal_key: Option<[u8; 32]>) -> Self { 348 let mut l = Self::new(seal_key); 349 for (seq, record) in log { 350 l.apply(seq, record); 351 } 352 l 353 } 354 355 /// Unsealed revision records replay kept as no-ops (issue #101). 356 pub(crate) fn seal_report(&self) -> SealReplayReport { 357 self.seals 358 } 359 360 /// The seal head `record` at `seq` moves the chain to, when its seal verifies against the 361 /// chain so far; `None` when it does not (and the record must change nothing). 362 fn sealed_head(&self, key: &[u8; 32], seq: WalSeq, record: &WalRecord) -> Option<[u8; 32]> { 363 let head = next_head(&self.seal_head, seq, &record_digest(record)); 364 record 365 .seal() 366 .is_some_and(|s| s.verifies(key, &head)) 367 .then_some(head) 368 } 369 370 /// Whether `record` at `seq` would take effect: always without a seal key, else only when 371 /// its seal verifies against the chain so far (issue #101). 372 pub(crate) fn accepts(&self, seq: WalSeq, record: &WalRecord) -> bool { 373 match self.seal_key { 374 Some(key) if record.is_revision_record() => { 375 self.sealed_head(&key, seq, record).is_some() 376 } 377 _ => true, 378 } 379 } 380 381 /// Seal `record`, to be written at `seq`, as the next link of this ledger's chain. 382 pub(crate) fn seal_record(&self, key: &RevisionSealKey, seq: WalSeq, record: &mut WalRecord) { 383 let head = next_head(&self.seal_head, seq, &record_digest(record)); 384 record.set_seal(key.seal(&head)); 385 } 386 387 /// Feed the revision part of the state root (nothing when the ledger is empty, so roots 388 /// of stores without revisions are unchanged). 389 pub(crate) fn hash_into(log: &[(WalSeq, WalRecord)], snapshot: WalSeq, h: &mut Sha256) { 390 let visible: Vec<_> = log.iter().filter(|(s, _)| *s <= snapshot).collect(); 391 if visible.is_empty() { 392 return; 393 } 394 h.update(DOMAIN_STATE_ROOT_REVISIONS_V1); 395 h.update((visible.len() as u64).to_le_bytes()); 396 for (seq, record) in visible { 397 h.update(seq.0.to_le_bytes()); 398 h.update(record_digest(record)); 399 } 400 } 401 402 /// Apply one revision record (other records are ignored). Total: a record that could 403 /// not have been admitted is still applied the same way on every replica. 404 pub(crate) fn apply(&mut self, seq: WalSeq, record: WalRecord) { 405 if !record.is_revision_record() { 406 return; 407 } 408 // Issue #101: in a sealed store a revision record counts only when the server's seal 409 // over the chain so far verifies; nothing in it (not even its unsigned `chain`) can 410 // then have been changed, inserted, reordered, or removed without the key. 411 if let Some(key) = self.seal_key { 412 if let Some(head) = self.sealed_head(&key, seq, &record) { 413 self.seal_head = head; 414 } else { 415 self.seals.unsealed += 1; 416 self.seals.first_unsealed.get_or_insert(seq); 417 self.unsealed.insert(seq); 418 self.log.push((seq, record)); 419 return; 420 } 421 } 422 match &record { 423 WalRecord::RevisionAdmitted { 424 envelope, 425 chain, 426 admitted_at_ms, 427 .. 428 } => { 429 let att = &envelope.attestation; 430 let id = att.changeset_id; 431 let repo = att.repo_id.clone(); 432 let witness = 433 AdmissionWitness::of_attestation(att, chain.clone(), seq, *admitted_at_ms); 434 let entry = self 435 .changes 436 .entry((repo.clone(), envelope.content.change_id)) 437 .or_default(); 438 if entry.creating_chain.is_none() { 439 entry.creating_chain = Some(chain.clone()); 440 } 441 if !entry.revisions.contains(&id) { 442 entry.revisions.push(id); 443 } 444 self.idempotency 445 .entry((repo.clone(), att.author_key, att.idempotency_key)) 446 .or_insert((seq, id)); 447 let rev = 448 self.revisions 449 .entry((repo.clone(), id)) 450 .or_insert_with(|| StoredRevision { 451 repo_id: repo, 452 changeset_id: id, 453 content: envelope.content.clone(), 454 first_seq: seq, 455 attestations: Vec::new(), 456 derivations: Vec::new(), 457 witnesses: Vec::new(), 458 state: RevisionState::Private, 459 }); 460 rev.attestations.push(att.clone()); 461 rev.witnesses.push(witness); 462 } 463 WalRecord::DerivedRevisionAdmitted { 464 derived, 465 chain, 466 admitted_at_ms, 467 .. 468 } => { 469 let att = &derived.attestation; 470 let id = att.output_changeset; 471 let repo = att.repo_id.clone(); 472 let witness = 473 AdmissionWitness::of_derivation(derived, chain.clone(), seq, *admitted_at_ms); 474 let entry = self 475 .changes 476 .entry((repo.clone(), derived.content.change_id)) 477 .or_default(); 478 if entry.creating_chain.is_none() { 479 entry.creating_chain = Some(chain.clone()); 480 } 481 if !entry.revisions.contains(&id) { 482 entry.revisions.push(id); 483 } 484 self.derivations 485 .entry((repo.clone(), att.digest())) 486 .or_insert(seq); 487 let rev = 488 self.revisions 489 .entry((repo.clone(), id)) 490 .or_insert_with(|| StoredRevision { 491 repo_id: repo, 492 changeset_id: id, 493 content: derived.content.clone(), 494 first_seq: seq, 495 attestations: Vec::new(), 496 derivations: Vec::new(), 497 witnesses: Vec::new(), 498 state: RevisionState::Private, 499 }); 500 rev.derivations.push(att.clone()); 501 rev.witnesses.push(witness); 502 } 503 WalRecord::ObsolescenceRecorded { 504 marker, 505 chain, 506 recorded_at_ms, 507 .. 508 } => { 509 self.changes 510 .entry((marker.repo_id.clone(), marker.change_id)) 511 .or_default() 512 .markers 513 .push(RecordedMarker { 514 seq, 515 marker: marker.clone(), 516 chain: chain.clone(), 517 recorded_at_ms: *recorded_at_ms, 518 }); 519 } 520 WalRecord::RevisionStateMoved { state_move: m, .. } => { 521 // Kind 9 is permanently the owner-move record: `Verified` and `Canonical` come 522 // only from the evidence-bearing records of B3, E1, and E2. The WAL seal is 523 // unkeyed (CRC32C and an unkeyed hash chain detect corruption, not forgery), 524 // so replay applies a move only when (1) its mover signature verifies strictly 525 // and the mover key is the audience of the chain's leaf link (issue #89), and 526 // (2) it is an owner move (`Private -> Draft`, `Private -> Proposed`, 527 // `Draft -> Proposed`, by a chain that is or dominates the first admission's 528 // chain; #88). Both are pure functions of the record and the log that never 529 // change, so an old log keeps its meaning. Any other record stays in the log 530 // and the state root but changes nothing; it is counted in the replay report, 531 // and strict recovery refuses a store with an unverified one. 532 match m.verify() { 533 Err(fault) => { 534 let r = &mut self.state_moves; 535 match fault { 536 StateMoveFault::SignatureInvalid => r.signature_invalid += 1, 537 StateMoveFault::SignerNotChainLeaf => r.signer_not_chain_leaf += 1, 538 } 539 r.first_unverified.get_or_insert((seq, fault)); 540 } 541 Ok(()) => { 542 let rev = self.revisions.get_mut(&(m.repo_id.clone(), m.changeset_id)); 543 match rev { 544 Some(rev) 545 if owned_by(rev, &m.chain) 546 && rev.state.check_owner_move(m.to).is_ok() => 547 { 548 rev.state = m.to; 549 } 550 _ => self.state_moves.not_owner_move += 1, 551 } 552 } 553 } 554 } 555 // Git bridge records are kept in the log (checkpoint and state root); their map 556 // lives in `git_bridge::GitBridgeLedger`. 557 WalRecord::GitBridgeImported { .. } => {} 558 _ => return, 559 } 560 self.log.push((seq, record)); 561 } 562 563 pub(crate) fn get_revision(&self, repo: &RepoId, id: ChangesetId) -> Option<&StoredRevision> { 564 self.revisions.get(&(repo.clone(), id)) 565 } 566 567 /// The revision if `viewer` may see it; `None` both when it does not exist and when it 568 /// is another owner's `Private` revision, so the two cannot be told apart. 569 pub(crate) fn get_visible( 570 &self, 571 repo: &RepoId, 572 id: ChangesetId, 573 viewer: &ChainPath, 574 ) -> Option<&StoredRevision> { 575 self.get_revision(repo, id) 576 .filter(|rev| visible_to(rev, viewer)) 577 } 578 579 /// Checks of a signed state move (steps B4 and issue #89). A move to `Canonical` is 580 /// refused first, whatever the revision (`CanonicalOutsidePromotionQueue`); then a 581 /// signature that does not verify, or a mover key that is not the audience of the 582 /// chain's leaf link, is `AuthSignatureInvalid`; a revision the chain cannot see is 583 /// `ChangesetNotFound`; a chain that is not the owner chain is `AuthChainNotDominant`; 584 /// then the owner-move rule of `RevisionState`. 585 pub(crate) fn plan_move(&self, m: &SignedStateMove) -> SynapseResult<()> { 586 let (id, to, chain) = (m.changeset_id, m.to, &m.chain); 587 if to == RevisionState::Canonical { 588 return Err(SynapseError::new( 589 RefusalCode::CanonicalOutsidePromotionQueue, 590 format!( 591 "revision {id} -> Canonical: canonical moves only through the promotion queue" 592 ), 593 )); 594 } 595 m.verify().map_err(StateMoveFault::into_error)?; 596 let rev = self 597 .get_visible(&m.repo_id, id, chain) 598 .ok_or_else(|| not_found(format!("revision {id} not found")))?; 599 if !owned_by(rev, chain) { 600 return Err(SynapseError::new( 601 RefusalCode::AuthChainNotDominant, 602 format!( 603 "moving revision {id} needs a chain that is or dominates the chain of its first admission" 604 ), 605 )); 606 } 607 rev.state.check_owner_move(to) 608 } 609 610 /// Every revision (for compaction roots). 611 pub(crate) fn revisions(&self) -> impl Iterator { 612 self.revisions.values() 613 } 614 615 pub(crate) fn idempotent( 616 &self, 617 repo: &RepoId, 618 key: &[u8; 32], 619 idem: IdempotencyKey, 620 ) -> Option<(WalSeq, ChangesetId)> { 621 self.idempotency.get(&(repo.clone(), *key, idem)).copied() 622 } 623 624 /// Join rule (ADR 0003 sections 5.1 and 5.8): a revision under an existing `ChangeId` 625 /// is admitted only from a chain that descends from the creating chain, or when the 626 /// leaf grant names the `ChangeId` in its change scope. 627 pub(crate) fn check_join( 628 &self, 629 repo: &RepoId, 630 change_id: ChangeId, 631 authority: &AdmissionAuthority, 632 ) -> SynapseResult<()> { 633 let Some(creating) = self 634 .changes 635 .get(&(repo.clone(), change_id)) 636 .and_then(|e| e.creating_chain.as_ref()) 637 else { 638 return Ok(()); 639 }; 640 if authority.chain.descends_from(creating) || authority.change_scope.contains(&change_id) { 641 return Ok(()); 642 } 643 Err(SynapseError::new( 644 RefusalCode::AuthChangeOutOfScope, 645 format!( 646 "change {change_id} belongs to another creating chain and the grant does not name it in its change scope" 647 ), 648 )) 649 } 650 651 /// Checks of a derived revision at admission `WalSeq` `at` (ADR 0003 B5), shared by 652 /// admission and replay verification so both refuse exactly the same records. In order: 653 /// content rules, the attestation names this content and its signature verifies under the 654 /// server key it names (`DerivationSignatureInvalid`); the identity documents `keys` holds 655 /// belong to the attestation's repository (`DerivationIdentityRepoMismatch`); that key is 656 /// the identity document's server key in effect at `at` (`DerivationServerKeyUnregistered`); 657 /// the attestation was not admitted before (`DerivationAttestationReplayed`); the inputs fit 658 /// the rule and are held where `viewer` may see them, so another owner's `Private` revision 659 /// counts as not held (step B4, `DerivationInputMismatch`); recomputing the rule on them 660 /// gives the attested `ChangesetId` and `TreeDigest` (`DerivationRecomputeMismatch`). 661 pub(crate) fn check_derivation( 662 &self, 663 derived: &DerivedRevision, 664 at: WalSeq, 665 viewer: &ChainPath, 666 keys: &dyn ServerKeyRegistry, 667 trees: &mut dyn DerivationTrees, 668 ) -> SynapseResult { 669 let id = derived.validate()?; 670 let att = &derived.attestation; 671 let repo = att.repo_id.clone(); 672 match keys.registered_server_key(&repo, at) { 673 ServerKeyLookup::Registered(key) if key == att.server_key => {} 674 ServerKeyLookup::Registered(_) => { 675 return Err(SynapseError::new( 676 RefusalCode::DerivationServerKeyUnregistered, 677 format!( 678 "server key {} is not the server key of the identity document in effect at {at}", 679 att.server_did() 680 ), 681 )) 682 } 683 ServerKeyLookup::NoDocument => { 684 return Err(SynapseError::new( 685 RefusalCode::DerivationServerKeyUnregistered, 686 format!("no identity document of {repo} is in effect at {at}"), 687 )) 688 } 689 ServerKeyLookup::OtherRepository(other) => { 690 return Err(SynapseError::new( 691 RefusalCode::DerivationIdentityRepoMismatch, 692 format!( 693 "the identity documents checked belong to {other}, the derivation attestation names {repo}" 694 ), 695 )) 696 } 697 } 698 let digest = att.digest(); 699 if let Some(first) = self.derivations.get(&(repo.clone(), digest)) { 700 return Err(SynapseError::new( 701 RefusalCode::DerivationAttestationReplayed, 702 format!( 703 "derivation attestation {} was already admitted at {first}", 704 hex::encode(digest) 705 ), 706 )); 707 } 708 // Another owner's `Private` revision is not an input this chain can name (B4). 709 let lookup = |input: ChangesetId| { 710 self.get_visible(&repo, input, viewer) 711 .map(|r| r.content.clone()) 712 }; 713 let (content, tree) = derive_revision_output(att.rule, &att.inputs, &lookup, trees)?; 714 let recomputed = content.changeset_id(); 715 if recomputed != att.output_changeset || tree != att.output_tree { 716 return Err(SynapseError::new( 717 RefusalCode::DerivationRecomputeMismatch, 718 format!( 719 "recomputed {:?} on the named inputs gives revision {recomputed} tree {tree}, the attestation names revision {} tree {}", 720 att.rule, att.output_changeset, att.output_tree 721 ), 722 )); 723 } 724 Ok(id) 725 } 726 727 /// Checks of an obsolescence marker against the ledger. `Ok(Some(seq))` when the same 728 /// predecessor and successors are already recorded (the first marker's sequence). 729 pub(crate) fn plan_marker( 730 &self, 731 marker: &ObsolescenceMarker, 732 chain: &ChainPath, 733 ) -> SynapseResult> { 734 marker.validate()?; 735 let repo = &marker.repo_id; 736 let entry = self 737 .changes 738 .get(&(repo.clone(), marker.change_id)) 739 .filter(|e| e.creating_chain.is_some()) 740 .ok_or_else(|| not_found(format!("change {} not found", marker.change_id)))?; 741 for id in std::iter::once(&marker.predecessor).chain(&marker.successors) { 742 // Another owner's `Private` revision is refused exactly like an unknown one (B4). 743 if !entry.revisions.contains(id) || self.get_visible(repo, *id, chain).is_none() { 744 return Err(not_found(format!( 745 "revision {id} is not a revision of change {}", 746 marker.change_id 747 ))); 748 } 749 } 750 if let Some(m) = entry.markers.iter().find(|m| { 751 m.marker.predecessor == marker.predecessor && m.marker.successors == marker.successors 752 }) { 753 return Ok(Some(m.seq)); 754 } 755 // No cycles: no successor may already lead back to the predecessor. 756 let mut seen = BTreeSet::new(); 757 let mut work: Vec = marker.successors.clone(); 758 while let Some(id) = work.pop() { 759 if id == marker.predecessor { 760 return Err(SynapseError::new( 761 RefusalCode::ObsolescenceMarkerInvalid, 762 format!("marker would make revision {id} its own successor"), 763 )); 764 } 765 if seen.insert(id) { 766 for m in entry.markers.iter().filter(|m| m.marker.predecessor == id) { 767 work.extend(m.marker.successors.iter().copied()); 768 } 769 } 770 } 771 let creating = entry.creating_chain.as_ref().expect("filtered above"); 772 let allowed = match marker.kind() { 773 ObsolescenceKind::Pruned => chain.dominates(creating), 774 ObsolescenceKind::Rewritten | ObsolescenceKind::Split => { 775 chain.dominates(creating) 776 || self 777 .get_revision(repo, marker.predecessor) 778 .and_then(|r| r.witnesses.first()) 779 .is_some_and(|w| chain.dominates(&w.chain)) 780 } 781 }; 782 if !allowed { 783 return Err(SynapseError::new( 784 RefusalCode::AuthChainNotDominant, 785 format!( 786 "{:?} of revision {} needs a chain that is or dominates the creating chain of change {}", 787 marker.kind(), 788 marker.predecessor, 789 marker.change_id 790 ), 791 )); 792 } 793 Ok(None) 794 } 795 796 pub(crate) fn change_status(&self, repo: &RepoId, change_id: ChangeId) -> Option { 797 let entry = self.changes.get(&(repo.clone(), change_id))?; 798 let creating_chain = entry.creating_chain.clone()?; 799 let obsoleted: BTreeSet = 800 entry.markers.iter().map(|m| m.marker.predecessor).collect(); 801 let (obsolete, live): (Vec<_>, Vec<_>) = entry 802 .revisions 803 .iter() 804 .copied() 805 .partition(|id| obsoleted.contains(id)); 806 Some(ChangeStatus { 807 repo_id: repo.clone(), 808 change_id, 809 creating_chain, 810 revisions: entry.revisions.clone(), 811 divergent: live.len() > 1, 812 live, 813 obsolete, 814 markers: entry.markers.clone(), 815 }) 816 } 817 818 /// The change as `viewer` may see it (step B4): only revisions visible to it, and only 819 /// markers whose predecessor and successors are all visible to it; live, obsolete, and 820 /// divergence are computed over those. `None` when the viewer sees no revision. 821 pub(crate) fn change_status_visible( 822 &self, 823 repo: &RepoId, 824 change_id: ChangeId, 825 viewer: &ChainPath, 826 ) -> Option { 827 let entry = self.changes.get(&(repo.clone(), change_id))?; 828 let creating_chain = entry.creating_chain.clone()?; 829 let seen = |id: &ChangesetId| self.get_visible(repo, *id, viewer).is_some(); 830 let revisions: Vec = entry.revisions.iter().copied().filter(seen).collect(); 831 if revisions.is_empty() { 832 return None; 833 } 834 let markers: Vec = entry 835 .markers 836 .iter() 837 .filter(|m| seen(&m.marker.predecessor) && m.marker.successors.iter().all(seen)) 838 .cloned() 839 .collect(); 840 let obsoleted: BTreeSet = 841 markers.iter().map(|m| m.marker.predecessor).collect(); 842 let (obsolete, live): (Vec<_>, Vec<_>) = revisions 843 .iter() 844 .copied() 845 .partition(|id| obsoleted.contains(id)); 846 Some(ChangeStatus { 847 repo_id: repo.clone(), 848 change_id, 849 creating_chain, 850 revisions, 851 divergent: live.len() > 1, 852 live, 853 obsolete, 854 markers, 855 }) 856 } 857 } 858 859 /// Replica verification of revision records (ADR 0003 B5): replay `records` in `WalSeq` 860 /// order into a fresh ledger and refuse the first record that could not have been admitted 861 /// on its own evidence. An agent revision (kind 7) must carry a strictly verifying agent 862 /// signature over its own content: a derived revision presented with an agent signature it 863 /// does not have is refused (`AuthSignatureInvalid`). A marker (kind 8) must verify. A derived 864 /// revision (kind 11) must pass the admission checks of its derivation at its own `WalSeq` 865 /// (signature, server key registered then, not a replay, inputs admitted before it and 866 /// visible to the record's chain, the same digests on recomputation). A state move (kind 9) 867 /// must verify (`RevisionStateMoveUnverified`), the rule strict recovery applies (issue #89). 868 /// The refusal keeps its code and names the record's `WalSeq`. Returns the number of records 869 /// verified. Authorization (chains, join rule) and blobs are not re-checked here. 870 pub fn verify_revision_log( 871 records: &[(WalSeq, WalRecord)], 872 keys: &dyn ServerKeyRegistry, 873 trees: &mut dyn DerivationTrees, 874 ) -> SynapseResult { 875 let mut ledger = RevisionLedger::default(); 876 let mut prev: Option = None; 877 for (seq, record) in records { 878 let at_seq = |e: SynapseError| { 879 SynapseError::new(e.code, format!("revision record at {seq}: {}", e.message)) 880 }; 881 if prev.is_some_and(|p| p >= *seq) { 882 return Err(SynapseError::new( 883 RefusalCode::WalSequenceGap, 884 format!("revision record at {seq} does not follow the previous record"), 885 )); 886 } 887 prev = Some(*seq); 888 match record { 889 WalRecord::RevisionAdmitted { envelope, .. } => { 890 envelope.validate().map_err(at_seq)?; 891 } 892 WalRecord::ObsolescenceRecorded { marker, .. } => { 893 marker.validate().map_err(at_seq)?; 894 } 895 WalRecord::DerivedRevisionAdmitted { derived, chain, .. } => { 896 ledger 897 .check_derivation(derived, *seq, chain, keys, trees) 898 .map_err(at_seq)?; 899 } 900 WalRecord::RevisionStateMoved { state_move, .. } => { 901 // The same rule as strict recovery (issue #89): a move that does not verify 902 // was not written with the mover's key. 903 state_move.verify().map_err(|fault| { 904 SynapseError::new( 905 RefusalCode::RevisionStateMoveUnverified, 906 format!("state move at {seq} does not verify: {fault:?}"), 907 ) 908 })?; 909 } 910 other => { 911 return Err(SynapseError::new( 912 RefusalCode::WalRecordMalformed, 913 format!( 914 "record of kind {} at {seq} is not a revision record", 915 other.kind_byte() 916 ), 917 )) 918 } 919 } 920 ledger.apply(*seq, record.clone()); 921 } 922 Ok(records.len()) 923 } 924 925 impl crate::SynapseStore { 926 /// Admit an envelope v2 revision under `authority` at server time `now_ms` (ADR 0003 927 /// B1). Checks, in order: the envelope (content rules, attestation names this content, 928 /// strict signature); idempotency on (repository, signer key, `IdempotencyKey`), where a 929 /// repeat with the same revision returns the first `WalSeq` and any other revision is 930 /// `IdempotencyKeyConflict`; the path-count limit; the join rule 931 /// (`AuthChangeOutOfScope`); parents (an admitted revision or a v1 changeset of the same 932 /// repository); blobs (provided with the declared digest and size, or already visible). 933 /// Identical content already admitted gains one more attestation and witness. 934 pub fn admit_revision( 935 &mut self, 936 envelope: ChangesetEnvelopeV2, 937 blobs: &[(BlobDigest, Vec)], 938 authority: AdmissionAuthority, 939 now_ms: u64, 940 ) -> SynapseResult { 941 self.check_writable()?; 942 self.check_binary_codec()?; 943 let id = envelope.validate()?; 944 let content = &envelope.content; 945 let att = &envelope.attestation; 946 let repo = att.repo_id.clone(); 947 if let Some((wal_seq, existing)) = 948 self.revisions 949 .idempotent(&repo, &att.author_key, att.idempotency_key) 950 { 951 if existing == id { 952 return Ok(RevisionOutcome::IdempotentDuplicate { 953 wal_seq, 954 changeset_id: id, 955 }); 956 } 957 return Err(SynapseError::new( 958 RefusalCode::IdempotencyKeyConflict, 959 format!( 960 "idempotency key {} of {} already bound to revision {existing}, cannot rebind to {id}", 961 att.idempotency_key.to_hex(), 962 att.author_did() 963 ), 964 )); 965 } 966 if content.mutations.len() > self.limits.max_paths_per_changeset { 967 return Err(SynapseError::new( 968 RefusalCode::QuotaTooManyPaths, 969 format!( 970 "revision touches {} paths, exceeding limit {}", 971 content.mutations.len(), 972 self.limits.max_paths_per_changeset 973 ), 974 )); 975 } 976 self.revisions 977 .check_join(&repo, content.change_id, &authority)?; 978 self.check_revision_parents(&repo, content, &authority.chain)?; 979 let mut provided: BTreeMap = BTreeMap::new(); 980 let mut total = 0u64; 981 for (declared, bytes) in blobs { 982 let len = bytes.len() as u64; 983 total = total.saturating_add(len); 984 if len > self.limits.max_blob_bytes || total > self.limits.max_total_changeset_bytes { 985 return Err(SynapseError::new( 986 RefusalCode::QuotaPayloadTooLarge, 987 "revision blobs exceed max_blob_bytes or max_total_changeset_bytes", 988 )); 989 } 990 let actual = BlobDigest::compute(bytes); 991 if actual != *declared { 992 return Err(SynapseError::new( 993 RefusalCode::BlobDigestMismatch, 994 format!("declared blob digest {declared} does not match computed {actual}"), 995 )); 996 } 997 provided.insert(*declared, bytes.as_slice()); 998 } 999 let mut inline: Vec<(BlobDigest, &[u8])> = Vec::new(); 1000 for m in &content.mutations { 1001 if let MutationOp::Upsert { 1002 blob_digest, 1003 size_bytes, 1004 .. 1005 } = &m.op 1006 { 1007 if let Some(raw) = provided.get(blob_digest) { 1008 if raw.len() as u64 != *size_bytes { 1009 return Err(SynapseError::new( 1010 RefusalCode::BlobDigestMismatch, 1011 format!( 1012 "mutation path {} declared size {size_bytes} but blob is {} bytes", 1013 m.path, 1014 raw.len() 1015 ), 1016 )); 1017 } 1018 if !inline.iter().any(|(d, _)| d == blob_digest) { 1019 inline.push((*blob_digest, raw)); 1020 } 1021 } else if !self.blob_first_visible_seq.contains_key(blob_digest) { 1022 return Err(SynapseError::new( 1023 RefusalCode::BlobNotFound, 1024 format!( 1025 "mutation path {} references missing blob {blob_digest}", 1026 m.path 1027 ), 1028 )); 1029 } 1030 } 1031 } 1032 let joined_existing_revision = self.revisions.get_revision(&repo, id).is_some(); 1033 let record = WalRecord::RevisionAdmitted { 1034 envelope, 1035 chain: authority.chain, 1036 admitted_at_ms: now_ms, 1037 new_blobs: inline.iter().map(|(d, _)| *d).collect(), 1038 seal: None, 1039 }; 1040 let wal_seq = self.append_revision_record(record, &inline, None)?; 1041 Ok(RevisionOutcome::Admitted { 1042 wal_seq, 1043 changeset_id: id, 1044 joined_existing_revision, 1045 }) 1046 } 1047 1048 /// Parents of a revision: each an admitted revision or a v1 changeset of `repo`. 1049 fn check_revision_parents( 1050 &self, 1051 repo: &RepoId, 1052 content: &RevisionContent, 1053 viewer: &ChainPath, 1054 ) -> SynapseResult<()> { 1055 for parent in &content.parents { 1056 // Another owner's `Private` revision is not a parent this chain can name (B4). 1057 let parent_repo = if self.revisions.get_visible(repo, *parent, viewer).is_some() { 1058 repo 1059 } else if self 1060 .git_bridge 1061 .repo(repo) 1062 .is_some_and(|r| r.commit_by_changeset(*parent).is_some()) 1063 { 1064 // An imported Git commit (step H1) of this repository. 1065 repo 1066 } else if let Some(cs) = self.changesets.get(parent) { 1067 &cs.envelope.repo_id 1068 } else { 1069 return Err(SynapseError::new( 1070 RefusalCode::ParentChangesetNotFound, 1071 format!("parent {parent} not found"), 1072 )); 1073 }; 1074 if parent_repo != repo { 1075 return Err(SynapseError::new( 1076 RefusalCode::AuthCrossRepoDenied, 1077 "parent changeset belongs to a different repository", 1078 )); 1079 } 1080 } 1081 Ok(()) 1082 } 1083 1084 /// Admit a server-derived revision (ADR 0003 B5) under `authority` at server time 1085 /// `now_ms`. `keys` answers which server key the repository identity document registered 1086 /// at the admission `WalSeq`; `trees` is the tree store the rule is recomputed on. Checks, 1087 /// in order: the derivation (see `RevisionLedger::check_derivation`: signature, registered 1088 /// key, replay, inputs, recomputation); the path-count limit; the join rule against the 1089 /// change's creating chain (`AuthChangeOutOfScope`); parents; every upserted blob already 1090 /// visible (`BlobNotFound`: a derived revision brings no new content). Nothing is written 1091 /// on a refusal. The witness records the server key, its signature, and the attestation 1092 /// digest; no agent signature is recorded or claimed. 1093 pub fn admit_derived_revision( 1094 &mut self, 1095 derived: DerivedRevision, 1096 authority: AdmissionAuthority, 1097 keys: &dyn ServerKeyRegistry, 1098 trees: &mut dyn DerivationTrees, 1099 now_ms: u64, 1100 ) -> SynapseResult { 1101 self.check_writable()?; 1102 self.check_binary_codec()?; 1103 let at = self.committed_seq().next(); 1104 let id = self 1105 .revisions 1106 .check_derivation(&derived, at, &authority.chain, keys, trees)?; 1107 let content = &derived.content; 1108 let repo = derived.attestation.repo_id.clone(); 1109 if content.mutations.len() > self.limits.max_paths_per_changeset { 1110 return Err(SynapseError::new( 1111 RefusalCode::QuotaTooManyPaths, 1112 format!( 1113 "revision touches {} paths, exceeding limit {}", 1114 content.mutations.len(), 1115 self.limits.max_paths_per_changeset 1116 ), 1117 )); 1118 } 1119 self.revisions 1120 .check_join(&repo, content.change_id, &authority)?; 1121 self.check_revision_parents(&repo, content, &authority.chain)?; 1122 // Every upserted blob is visible already, or was produced by the recomputation above 1123 // (a tier T1 merged file, step D1): those are written with the record. 1124 let mut produced: Vec<(BlobDigest, Vec)> = Vec::new(); 1125 for m in &content.mutations { 1126 if let MutationOp::Upsert { blob_digest, .. } = &m.op { 1127 if self.blob_first_visible_seq.contains_key(blob_digest) 1128 || produced.iter().any(|(d, _)| d == blob_digest) 1129 { 1130 continue; 1131 } 1132 match trees.produced_blob(*blob_digest) { 1133 Some(bytes) if BlobDigest::compute(bytes) == *blob_digest => { 1134 produced.push((*blob_digest, bytes.to_vec())); 1135 } 1136 _ => { 1137 return Err(SynapseError::new( 1138 RefusalCode::BlobNotFound, 1139 format!( 1140 "derived mutation path {} references blob {blob_digest}, which is not visible", 1141 m.path 1142 ), 1143 )) 1144 } 1145 } 1146 } 1147 } 1148 let blobs: Vec<(BlobDigest, &[u8])> = 1149 produced.iter().map(|(d, b)| (*d, b.as_slice())).collect(); 1150 let joined_existing_revision = self.revisions.get_revision(&repo, id).is_some(); 1151 let record = WalRecord::DerivedRevisionAdmitted { 1152 derived, 1153 chain: authority.chain, 1154 admitted_at_ms: now_ms, 1155 seal: None, 1156 }; 1157 let wal_seq = self.append_revision_record(record, &blobs, Some(at))?; 1158 Ok(RevisionOutcome::Admitted { 1159 wal_seq, 1160 changeset_id: id, 1161 joined_existing_revision, 1162 }) 1163 } 1164 1165 /// Every revision record (kinds 7, 8 and 11) this store holds, in `WalSeq` order: what a 1166 /// replica replays and verifies with [`verify_revision_log`]. 1167 pub fn revision_records(&self) -> &[(WalSeq, WalRecord)] { 1168 self.revisions.log() 1169 } 1170 1171 /// [`verify_revision_log`] over this store's revision records. 1172 pub fn verify_revisions( 1173 &self, 1174 keys: &dyn ServerKeyRegistry, 1175 trees: &mut dyn DerivationTrees, 1176 ) -> SynapseResult { 1177 verify_revision_log(self.revisions.log(), keys, trees) 1178 } 1179 1180 /// Record an obsolescence marker authorized under `chain` at server time `now_ms`. A 1181 /// prune needs a chain that is or dominates the change's creating chain; a rewrite or a 1182 /// split needs that, or a chain that is or dominates the chain of the predecessor's first 1183 /// admission (`AuthChainNotDominant` otherwise). Predecessor and successors must be 1184 /// revisions of the marker's change (`ChangesetNotFound`); a marker that would close a 1185 /// cycle is `ObsolescenceMarkerInvalid`. The same predecessor and successors recorded 1186 /// again return the first marker's `WalSeq`. 1187 pub fn record_obsolescence( 1188 &mut self, 1189 marker: ObsolescenceMarker, 1190 chain: ChainPath, 1191 now_ms: u64, 1192 ) -> SynapseResult { 1193 self.check_writable()?; 1194 self.check_binary_codec()?; 1195 if let Some(seq) = self.revisions.plan_marker(&marker, &chain)? { 1196 return Ok(seq); 1197 } 1198 let record = WalRecord::ObsolescenceRecorded { 1199 marker, 1200 chain, 1201 recorded_at_ms: now_ms, 1202 seal: None, 1203 }; 1204 self.append_revision_record(record, &[], None) 1205 } 1206 1207 /// Record the signed state move `state_move` at server time `now_ms` (ADR 0003 step B4, 1208 /// issue #89). Refused, with nothing written: any move to `Canonical` 1209 /// (`CanonicalOutsidePromotionQueue`: canonical moves only through the promotion queue, 1210 /// step E2); a mover signature that does not verify strictly, or a mover key that is not 1211 /// the audience of the chain's leaf link (`AuthSignatureInvalid`); a revision the chain 1212 /// cannot see (`ChangesetNotFound`, the same as an unknown one); a chain that is not, and 1213 /// does not dominate, the chain of the revision's first admission 1214 /// (`AuthChainNotDominant`); a move to `Verified`, or any move that is backwards, in 1215 /// place, or skips a state (`RevisionStateMoveInvalid`). The owner chain may move 1216 /// `Private -> Draft`, `Private -> Proposed`, and `Draft -> Proposed`. 1217 pub fn advance_revision_state( 1218 &mut self, 1219 state_move: SignedStateMove, 1220 now_ms: u64, 1221 ) -> SynapseResult { 1222 self.check_writable()?; 1223 self.check_binary_codec()?; 1224 self.revisions.plan_move(&state_move)?; 1225 let record = WalRecord::RevisionStateMoved { 1226 state_move, 1227 moved_at_ms: now_ms, 1228 seal: None, 1229 }; 1230 self.append_revision_record(record, &[], None) 1231 } 1232 1233 /// Kind 9 records replay kept as no-ops, by reason (issue #89): unverified moves (only 1234 /// under `TruncateTornTail`; strict recovery refuses them) and verified moves that are 1235 /// not owner moves. All zero for a log written only by stores. 1236 pub fn state_move_replay_report(&self) -> StateMoveReplayReport { 1237 self.revisions.state_move_report() 1238 } 1239 1240 /// Revision records replay kept as no-ops because their seal did not verify (issue #101; 1241 /// only in a store opened with [`Self::open_sealed`] under `TruncateTornTail`, since 1242 /// strict recovery refuses them). All zero for a log written only by this sealed store. 1243 pub fn seal_replay_report(&self) -> SealReplayReport { 1244 self.revisions.seal_report() 1245 } 1246 1247 /// An admitted revision of `repo_id` as `viewer` may see it (step B4): another owner's 1248 /// `Private` revision is `ChangesetNotFound`, exactly like an unknown one. 1249 pub fn get_revision_visible_to( 1250 &self, 1251 repo_id: &RepoId, 1252 changeset_id: ChangesetId, 1253 viewer: &ChainPath, 1254 ) -> SynapseResult { 1255 self.revisions 1256 .get_visible(repo_id, changeset_id, viewer) 1257 .cloned() 1258 .ok_or_else(|| not_found(format!("revision {changeset_id} not found"))) 1259 } 1260 1261 /// A change as `viewer` may see it (step B4): only its visible revisions and the markers 1262 /// that name only visible revisions. `ChangesetNotFound` when the viewer sees none. 1263 pub fn change_status_visible_to( 1264 &self, 1265 repo_id: &RepoId, 1266 change_id: ChangeId, 1267 viewer: &ChainPath, 1268 ) -> SynapseResult { 1269 self.revisions 1270 .change_status_visible(repo_id, change_id, viewer) 1271 .ok_or_else(|| not_found(format!("change {change_id} not found"))) 1272 } 1273 1274 /// An admitted revision of `repo_id`, whatever its state (server side: no visibility 1275 /// filter; reads on behalf of a key use [`Self::get_revision_visible_to`]). 1276 pub fn get_revision( 1277 &self, 1278 repo_id: &RepoId, 1279 changeset_id: ChangesetId, 1280 ) -> SynapseResult { 1281 self.revisions 1282 .get_revision(repo_id, changeset_id) 1283 .cloned() 1284 .ok_or_else(|| not_found(format!("revision {changeset_id} not found"))) 1285 } 1286 1287 /// Creating chain, revisions, live and obsolete revisions, and divergence of a change. 1288 pub fn change_status( 1289 &self, 1290 repo_id: &RepoId, 1291 change_id: ChangeId, 1292 ) -> SynapseResult { 1293 self.revisions 1294 .change_status(repo_id, change_id) 1295 .ok_or_else(|| not_found(format!("change {change_id} not found"))) 1296 } 1297 1298 pub(crate) fn check_binary_codec(&self) -> SynapseResult<()> { 1299 if self.codec == crate::RecordCodec::JsonV1 { 1300 return Err(SynapseError::new( 1301 RefusalCode::EnvelopeVersionUnsupported, 1302 "this store still writes v1 JSON records: envelope v2 needs the binary codec (run the migration checkpoint first)", 1303 )); 1304 } 1305 Ok(()) 1306 } 1307 1308 /// Append one revision record (blobs inline in the segment store, blob files first in 1309 /// the `wal.log` layout) and apply it. With `checked_at`, the record was checked against 1310 /// that `WalSeq` (a derivation against the identity document in effect there) and must be 1311 /// written at exactly that sequence: a writer whose next sequence differs is refused 1312 /// before anything is written, and a frame that lands at another sequence anyway is not 1313 /// applied and poisons the store (`WalSequenceGap` in both cases), so a record is never 1314 /// admitted at a sequence it was not checked at. Real checks in every build profile. 1315 pub(crate) fn append_revision_record( 1316 &mut self, 1317 mut record: WalRecord, 1318 blobs: &[(BlobDigest, &[u8])], 1319 mut checked_at: Option, 1320 ) -> SynapseResult { 1321 // Issue #101: a sealed store seals the record for the exact sequence it is written 1322 // at, so it is checked at that sequence like a derivation (a record that would land 1323 // elsewhere is refused, one that did is not applied). 1324 if let Some(key) = &self.revision_seal { 1325 let at = checked_at.unwrap_or_else(|| self.committed_seq.next()); 1326 self.revisions.seal_record(key, at, &mut record); 1327 checked_at = Some(at); 1328 } 1329 if self.v2_mode { 1330 let encoded = crate::wal2::encode_record(&record, blobs, self.codec)?; 1331 self.check_frame_cap(encoded.payload.len())?; 1332 let mut ticket = self.v2_begin()?; 1333 if let Some(err) = 1334 checked_at.and_then(|at| sequence_mismatch(at, ticket.base_seq.next(), false)) 1335 { 1336 // Hand the writer back untouched; the refusal is the result. 1337 let refused = self.v2_finish( 1338 ticket, 1339 Err(crate::wal2::BatchFailure::RolledBack(err.clone())), 1340 ); 1341 return Err(refused.err().unwrap_or(err)); 1342 } 1343 let result = Self::v2_write(&mut ticket, &[&encoded]); 1344 let placed = self.v2_finish(ticket, result)?; 1345 let seq = placed[0].seq; 1346 self.refuse_misplaced(checked_at, seq)?; 1347 self.apply_v2_ingest(&placed[0], record, &encoded); 1348 return Ok(seq); 1349 } 1350 if let Some(err) = 1351 checked_at.and_then(|at| sequence_mismatch(at, self.committed_seq.next(), false)) 1352 { 1353 return Err(err); 1354 } 1355 let payload = self.encode_v1_payload(&record)?; 1356 for (digest, bytes) in blobs { 1357 self.write_blob_file(*digest, bytes)?; 1358 } 1359 let (seq, _, _) = self.append_v1_payload(record.kind_byte(), &payload)?; 1360 self.refuse_misplaced(checked_at, seq)?; 1361 self.apply_record(seq, record); 1362 Ok(seq) 1363 } 1364 1365 /// After a durable write: a record checked at `checked_at` that landed at `seq` instead 1366 /// is not applied, and the store refuses writes until it is reopened. 1367 fn refuse_misplaced(&mut self, checked_at: Option, seq: WalSeq) -> SynapseResult<()> { 1368 match checked_at.and_then(|at| sequence_mismatch(at, seq, true)) { 1369 Some(err) => { 1370 self.poisoned = Some(err.message.clone()); 1371 Err(err) 1372 } 1373 None => Ok(()), 1374 } 1375 } 1376 } 1377 1378 /// `WalSequenceGap` when a record checked at `checked_at` would be (`written == false`) or was 1379 /// (`written == true`) placed at `seq`. 1380 fn sequence_mismatch(checked_at: WalSeq, seq: WalSeq, written: bool) -> Option { 1381 (checked_at != seq).then(|| { 1382 SynapseError::new( 1383 RefusalCode::WalSequenceGap, 1384 if written { 1385 format!("record checked at {checked_at} was written at {seq}; it is not applied and the store refuses writes until it is reopened") 1386 } else { 1387 format!("record checked at {checked_at} would be written at {seq}; nothing was written") 1388 }, 1389 ) 1390 }) 1391 } 1392 1393 #[cfg(test)] 1394 mod b4_tests { 1395 use super::*; 1396 use crate::{AdmissionAuthority, FsyncPolicy, RecoveryPolicy, StoreLimits, SynapseStore}; 1397 use `ed25519`_dalek::SigningKey; 1398 use std::path::PathBuf; 1399 use synapse_auth::{ 1400 Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, 1401 OperationSet, PathScope, ReferenceScope, ROOT_PARENT, 1402 }; 1403 use synapse_core::{FileMode, PathMutation, TreeDigest}; 1404 1405 struct SplitMix64(u64); 1406 1407 impl SplitMix64 { 1408 fn next(&mut self) -> u64 { 1409 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); 1410 let mut z = self.0; 1411 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); 1412 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); 1413 z ^ (z >> 31) 1414 } 1415 1416 fn below(&mut self, n: u64) -> u64 { 1417 self.next() % n 1418 } 1419 } 1420 1421 fn repo() -> RepoId { 1422 RepoId::new("aien-spark/synapse").unwrap() 1423 } 1424 1425 /// SHA-256 of a purpose and a label path: keys and nonces of these tests are derived, 1426 /// never fixed byte values. 1427 fn derived(what: &str, labels: &[u8]) -> [u8; 32] { 1428 let mut h = Sha256::new(); 1429 h.update(b"synapse-store revision unit fixture\0"); 1430 h.update(what.as_bytes()); 1431 h.update([0]); 1432 h.update(labels); 1433 h.finalize().into() 1434 } 1435 1436 /// The key presenting the chain with label path `labels`. 1437 fn key_of(labels: &[u8]) -> SigningKey { 1438 SigningKey::from_bytes(&derived("key", labels)) 1439 } 1440 1441 fn caveats() -> LinkCaveats { 1442 LinkCaveats { 1443 operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), 1444 paths: PathScope::whole_repository(), 1445 references: ReferenceScope::from_kinds(&[]), 1446 changes: ChangeScope::any(), 1447 quotas: ChainQuotas { 1448 max_ops_per_window: 1_000, 1449 window_duration_ms: 60_000, 1450 storage_bytes: 1 << 30, 1451 footprint_paths: 1 << 20, 1452 max_bytes_per_op: 1 << 20, 1453 }, 1454 issued_at_ms: 0, 1455 expires_at_ms: u64::MAX, 1456 } 1457 } 1458 1459 /// The last F1 link of the chain with label path `labels`: issued by the key of the 1460 /// parent path (a fixture authority for a root link), delegating to the key of `labels`. 1461 fn link_of(labels: &[u8]) -> CapabilityLink { 1462 let (issuer, parent) = match labels.split_last() { 1463 Some((_, [])) | None => ( 1464 SigningKey::from_bytes(&derived("authority", &[])), 1465 ROOT_PARENT, 1466 ), 1467 Some((_, up)) => (key_of(up), link_of(up).digest()), 1468 }; 1469 CapabilityLink::issue( 1470 &issuer, 1471 parent, 1472 derived("nonce", labels), 1473 repo(), 1474 key_of(labels).verifying_key().to_bytes(), 1475 caveats(), 1476 ) 1477 } 1478 1479 fn chain_of(labels: &[u8]) -> CapabilityChain { 1480 CapabilityChain::new((1..=labels.len()).map(|n| link_of(&labels[..n])).collect()) 1481 } 1482 1483 /// Link digests of the chain with label path `labels`; label prefixes are ancestors. 1484 fn path(labels: &[u8]) -> ChainPath { 1485 ChainPath::new( 1486 chain_of(labels) 1487 .link_digests() 1488 .iter() 1489 .map(|d| d.0) 1490 .collect(), 1491 ) 1492 .unwrap() 1493 } 1494 1495 fn random_labels(rng: &mut SplitMix64) -> Vec { 1496 let len = 1 + rng.below(3) as usize; 1497 (0..len).map(|_| 1 + rng.below(3) as u8).collect() 1498 } 1499 1500 /// A move of `id` to `to` signed by the leaf key of the chain with label path `labels`. 1501 fn signed(labels: &[u8], id: ChangesetId, to: RevisionState) -> SignedStateMove { 1502 SignedStateMove::sign_new(&key_of(labels), repo(), id, to, &chain_of(labels), 6_000) 1503 .unwrap() 1504 } 1505 1506 /// The same move with one signature bit flipped (a resealed edit of a signed record). 1507 fn bad_signature(mut m: SignedStateMove) -> SignedStateMove { 1508 m.signature[17] ^= 0x01; 1509 m 1510 } 1511 1512 /// The same move re-signed, validly, by a key that is not the chain leaf's audience. 1513 fn non_leaf_signer(mut m: SignedStateMove, signer: &[u8]) -> SignedStateMove { 1514 let k = key_of(signer); 1515 m.mover_key = k.verifying_key().to_bytes(); 1516 m.signature = SignedStateMove::sign_statement( 1517 &k, 1518 &m.repo_id, 1519 m.changeset_id, 1520 m.to, 1521 &m.chain, 1522 m.signed_at_ms, 1523 ); 1524 m 1525 } 1526 1527 fn moved(state_move: SignedStateMove) -> WalRecord { 1528 WalRecord::RevisionStateMoved { 1529 state_move, 1530 moved_at_ms: 6_000, 1531 seal: None, 1532 } 1533 } 1534 1535 fn body(n: u32) -> [u8; 4] { 1536 n.to_le_bytes() 1537 } 1538 1539 fn admission(chain: ChainPath, author: &[u8], n: u32) -> WalRecord { 1540 let body = body(n); 1541 let content = RevisionContent { 1542 change_id: ChangeId([(n % 7) as u8; 16]), 1543 base_tree: TreeDigest([0x7E; 32]), 1544 parents: vec![], 1545 mutations: vec![PathMutation { 1546 path: "src/lib.rs".into(), 1547 op: MutationOp::Upsert { 1548 mode: FileMode::Regular644, 1549 blob_digest: BlobDigest::compute(&body), 1550 size_bytes: body.len() as u64, 1551 }, 1552 }], 1553 intent_summary: "implement the task".into(), 1554 }; 1555 let mut idem = derived("idempotency", &n.to_le_bytes()); 1556 idem[0] ^= author.len() as u8; 1557 let envelope = ChangesetEnvelopeV2::sign_new( 1558 &key_of(author), 1559 repo(), 1560 content, 1561 IdempotencyKey(idem), 1562 1_000, 1563 ); 1564 WalRecord::RevisionAdmitted { 1565 envelope, 1566 chain, 1567 admitted_at_ms: 5_000, 1568 new_blobs: vec![], 1569 seal: None, 1570 } 1571 } 1572 1573 /// Property (acceptance 1 of B4 and of issue #89, replay side): the ledger applies any 1574 /// sequence of revision records, including forged moves no store call would write 1575 /// (backwards, in place, skipping, to `Verified` or `Canonical`, by chains that do not 1576 /// own the revision, with a broken signature, or signed by a key that is not the chain 1577 /// leaf's audience). Only verified owner moves apply, so no revision ever moves 1578 /// backwards or past `Proposed`, every verified owner move moves its revision, the 1579 /// replay report counts every no-op by reason, and rebuilding from the log gives the 1580 /// same states and the same report. 1581 #[test] 1582 fn b4_property_forged_record_sequences_never_move_a_revision_backwards() { 1583 let mut rng = SplitMix64(0xB4_0003); 1584 let (mut forged_refused, mut unverified_refused) = (0u32, 0u32); 1585 for _case in 0..200 { 1586 let mut ledger = RevisionLedger::default(); 1587 let mut ids: Vec = Vec::new(); 1588 let mut last: BTreeMap = BTreeMap::new(); 1589 let mut want = StateMoveReplayReport::default(); 1590 for seq in 1..=60u64 { 1591 let record = if ids.is_empty() || rng.below(4) == 0 { 1592 let n = rng.below(12) as u32; 1593 let author = random_labels(&mut rng); 1594 let r = admission(path(&random_labels(&mut rng)), &author, n); 1595 if let WalRecord::RevisionAdmitted { envelope, .. } = &r { 1596 let id = envelope.changeset_id(); 1597 if !ids.contains(&id) { 1598 ids.push(id); 1599 } 1600 } 1601 r 1602 } else { 1603 let id = ids[rng.below(ids.len() as u64) as usize]; 1604 let to = RevisionState::ALL[rng.below(5) as usize]; 1605 let m = signed(&random_labels(&mut rng), id, to); 1606 moved(match rng.below(6) { 1607 0 => bad_signature(m), 1608 1 => non_leaf_signer(m, &random_labels(&mut rng)), 1609 _ => m, 1610 }) 1611 }; 1612 let before = match &record { 1613 WalRecord::RevisionStateMoved { state_move: m, .. } => { 1614 let rev = ledger.get_revision(&repo(), m.changeset_id).unwrap(); 1615 let verified = m.verify(); 1616 let owner = 1617 owned_by(rev, &m.chain) && rev.state.check_owner_move(m.to).is_ok(); 1618 match verified { 1619 Err(StateMoveFault::SignatureInvalid) => want.signature_invalid += 1, 1620 Err(StateMoveFault::SignerNotChainLeaf) => { 1621 want.signer_not_chain_leaf += 1 1622 } 1623 Ok(()) if !owner => want.not_owner_move += 1, 1624 Ok(()) => {} 1625 } 1626 if let Err(fault) = verified { 1627 want.first_unverified.get_or_insert((WalSeq(seq), fault)); 1628 unverified_refused += 1; 1629 } 1630 Some((m.changeset_id, m.to, rev.state, verified.is_ok() && owner)) 1631 } 1632 _ => None, 1633 }; 1634 ledger.apply(WalSeq(seq), record); 1635 if let Some((id, to, from, legal)) = before { 1636 let now = ledger.get_revision(&repo(), id).unwrap().state; 1637 assert_eq!( 1638 now, 1639 if legal { to } else { from }, 1640 "{id}: {from:?} -> {to:?}" 1641 ); 1642 if !legal { 1643 forged_refused += 1; 1644 } 1645 } 1646 for id in &ids { 1647 let now = ledger.get_revision(&repo(), *id).unwrap().state; 1648 let before = last.insert(*id, now).unwrap_or(RevisionState::Private); 1649 assert!(now.rank() >= before.rank(), "{id}: {before:?} -> {now:?}"); 1650 assert!(now <= RevisionState::Proposed, "{id} reached {now:?}"); 1651 } 1652 } 1653 assert_eq!(ledger.state_move_report(), want); 1654 let rebuilt = RevisionLedger::from_log(ledger.log().to_vec(), None); 1655 assert_eq!(rebuilt.state_move_report(), want); 1656 for id in &ids { 1657 assert_eq!( 1658 rebuilt.get_revision(&repo(), *id).unwrap().state, 1659 ledger.get_revision(&repo(), *id).unwrap().state 1660 ); 1661 } 1662 } 1663 assert!(forged_refused > 0, "the sequences included forged moves"); 1664 assert!( 1665 unverified_refused > 0, 1666 "the sequences included unverified moves" 1667 ); 1668 } 1669 1670 /// Replay applies a state move only when its mover signature verifies, its mover key is 1671 /// the chain leaf's audience, and it is an owner move (`Private -> Draft`, 1672 /// `Private -> Proposed`, `Draft -> Proposed`, by a chain that is or dominates the first 1673 /// admission's chain). A signed `Proposed -> Verified` record, even by the owner, is 1674 /// refused on replay: `Verified` comes only from B3/E1 evidence records, never kind 9. 1675 #[test] 1676 fn b4_replay_refuses_a_forged_move_to_verified() { 1677 let owner: &[u8] = &[1, 2]; 1678 let record = admission(path(owner), owner, 1); 1679 let id = match &record { 1680 WalRecord::RevisionAdmitted { envelope, .. } => envelope.changeset_id(), 1681 _ => unreachable!(), 1682 }; 1683 let mv = |to: RevisionState, labels: &[u8]| moved(signed(labels, id, to)); 1684 let log = vec![ 1685 (WalSeq(1), record), 1686 (WalSeq(2), mv(RevisionState::Proposed, owner)), 1687 (WalSeq(3), mv(RevisionState::Verified, owner)), 1688 (WalSeq(4), mv(RevisionState::Verified, &[1, 9])), 1689 (WalSeq(5), mv(RevisionState::Canonical, owner)), 1690 ]; 1691 let replayed = RevisionLedger::from_log(log, None); 1692 assert_eq!( 1693 replayed.get_revision(&repo(), id).unwrap().state, 1694 RevisionState::Proposed, 1695 "a move to Verified or Canonical changes nothing on replay" 1696 ); 1697 assert_eq!( 1698 replayed.log().len(), 1699 5, 1700 "kept in the log, applied as no-ops" 1701 ); 1702 let report = replayed.state_move_report(); 1703 assert_eq!(report.not_owner_move, 3); 1704 assert_eq!(report.unverified(), 0); 1705 } 1706 1707 fn temp_dir(name: &str) -> PathBuf { 1708 let nanos = std::time::SystemTime::now() 1709 .duration_since(std::time::UNIX_EPOCH) 1710 .unwrap() 1711 .as_nanos(); 1712 let dir = 1713 std::env::temp_dir().join(format!("synapse-b89-{name}-{}-{nanos}", std::process::id())); 1714 std::fs::create_dir_all(&dir).unwrap(); 1715 dir 1716 } 1717 1718 fn open(dir: &PathBuf, policy: RecoveryPolicy) -> SynapseResult { 1719 let limits = StoreLimits { 1720 wal_prealloc_bytes: 64 * 1024, 1721 ..Default::default() 1722 }; 1723 SynapseStore::open(dir, FsyncPolicy::EveryCommit, policy, limits) 1724 } 1725 1726 /// Admit revision 1 under the chain with label path `owner`; its changeset id. 1727 fn admit(s: &mut SynapseStore, owner: &[u8]) -> ChangesetId { 1728 let WalRecord::RevisionAdmitted { envelope, .. } = admission(path(owner), owner, 1) else { 1729 unreachable!() 1730 }; 1731 let id = envelope.changeset_id(); 1732 let body = body(1); 1733 let blobs = vec![(BlobDigest::compute(&body), body.to_vec())]; 1734 let authority = AdmissionAuthority { 1735 chain: path(owner), 1736 change_scope: Vec::new(), 1737 }; 1738 s.admit_revision(envelope, &blobs, authority, 5_000) 1739 .unwrap(); 1740 id 1741 } 1742 1743 /// Issue #89 acceptance 1 (red on the #88 head, where kind 9 carried no signature): an 1744 /// owner move written straight into the WAL through the store's own framing (valid 1745 /// CRC32C and hash chain, so a resealed forgery) without the owner's key changes nothing 1746 /// on replay, whether its signature is broken or it is validly signed by a key that is 1747 /// not the chain leaf's audience. Torn-tail recovery keeps both as counted no-ops 1748 /// and strict recovery refuses the store (until a torn-tail compaction drops them: see 1749 /// `b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store`). 1750 #[test] 1751 fn b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay() { 1752 const TORN: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; 1753 let owner: &[u8] = &[1, 2]; 1754 let dir = temp_dir("forged"); 1755 let mut s = open(&dir, TORN).unwrap(); 1756 let id = admit(&mut s, owner); 1757 let honest = signed(owner, id, RevisionState::Draft); 1758 let broken = bad_signature(honest.clone()); 1759 assert_eq!(broken.verify(), Err(StateMoveFault::SignatureInvalid)); 1760 let impostor = non_leaf_signer(honest, &[1, 9]); 1761 assert_eq!(impostor.verify(), Err(StateMoveFault::SignerNotChainLeaf)); 1762 let first = s.append_revision_record(moved(broken), &[], None).unwrap(); 1763 s.append_revision_record(moved(impostor), &[], None) 1764 .unwrap(); 1765 assert_eq!( 1766 s.get_revision(&repo(), id).unwrap().state, 1767 RevisionState::Private 1768 ); 1769 drop(s); 1770 1771 let check = |s: &SynapseStore| { 1772 assert_eq!( 1773 s.get_revision(&repo(), id).unwrap().state, 1774 RevisionState::Private, 1775 "a forged, resealed owner move must change nothing on replay" 1776 ); 1777 let report = s.state_move_replay_report(); 1778 assert_eq!(report.signature_invalid, 1); 1779 assert_eq!(report.signer_not_chain_leaf, 1); 1780 assert_eq!(report.not_owner_move, 0); 1781 assert_eq!( 1782 report.first_unverified, 1783 Some((first, StateMoveFault::SignatureInvalid)) 1784 ); 1785 }; 1786 let strict_refuses = || { 1787 let err = open(&dir, RecoveryPolicy::StrictFailClosed).err().unwrap(); 1788 assert_eq!( 1789 err.code, 1790 RefusalCode::RevisionStateMoveUnverified, 1791 "{err:?}" 1792 ); 1793 }; 1794 check(&open(&dir, TORN).unwrap()); 1795 strict_refuses(); 1796 check(&open(&dir, TORN).unwrap()); 1797 strict_refuses(); 1798 let _ = std::fs::remove_dir_all(&dir); 1799 } 1800 1801 /// Review of PR #100 (note 1): torn-tail recovery keeps unverified kind 9 records as 1802 /// no-ops, but compaction must not carry them into the checkpoint, or strict recovery 1803 /// refuses the store forever. A torn-tail open followed by `checkpoint_and_compact` 1804 /// drops them (and only them), keeps every applied move, and leaves a store strict 1805 /// recovery accepts with the same revision states. 1806 #[test] 1807 fn b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store() { 1808 const TORN: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; 1809 const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; 1810 let owner: &[u8] = &[1, 2]; 1811 let dir = temp_dir("compact-forged"); 1812 let mut s = open(&dir, TORN).unwrap(); 1813 let id = admit(&mut s, owner); 1814 let honest = signed(owner, id, RevisionState::Draft); 1815 s.append_revision_record(moved(bad_signature(honest.clone())), &[], None) 1816 .unwrap(); 1817 s.append_revision_record(moved(non_leaf_signer(honest.clone(), &[1, 9])), &[], None) 1818 .unwrap(); 1819 s.advance_revision_state(honest, 6_500).unwrap(); 1820 // A verified move that is not an owner move is an ordinary no-op and stays. 1821 s.append_revision_record( 1822 moved(signed(&[1, 9], id, RevisionState::Proposed)), 1823 &[], 1824 None, 1825 ) 1826 .unwrap(); 1827 drop(s); 1828 assert!( 1829 open(&dir, STRICT).is_err(), 1830 "strict refuses before compaction" 1831 ); 1832 1833 let mut s = open(&dir, TORN).unwrap(); 1834 assert_eq!(s.state_move_replay_report().unverified(), 2); 1835 s.checkpoint_and_compact(7_000).unwrap(); 1836 let check = |s: &SynapseStore| { 1837 assert_eq!( 1838 s.get_revision(&repo(), id).unwrap().state, 1839 RevisionState::Draft 1840 ); 1841 let report = s.state_move_replay_report(); 1842 assert_eq!(report.unverified(), 0, "{report:?}"); 1843 assert_eq!(report.first_unverified, None); 1844 assert_eq!(report.not_owner_move, 1, "verified no-ops are kept"); 1845 }; 1846 check(&s); 1847 assert_eq!(s.state_move_replay_report().dropped_by_compaction, 2); 1848 let root = s.state_root_digest(None).unwrap(); 1849 drop(s); 1850 let s = open(&dir, STRICT).expect("strict recovery accepts the compacted store"); 1851 check(&s); 1852 assert_eq!( 1853 s.state_move_replay_report().dropped_by_compaction, 1854 0, 1855 "not persisted" 1856 ); 1857 assert_eq!(s.state_root_digest(None).unwrap(), root); 1858 let _ = std::fs::remove_dir_all(&dir); 1859 } 1860 1861 /// Review of PR #100 (note 2): `SignedStateMove::verify` checks only that the mover key 1862 /// is the audience of a link whose digest ends the chain; it does not check who issued 1863 /// that link. A forger can mint a root link of its own, or append a link of its own 1864 /// under the owner's chain, and sign a move that verifies. The store is safe because it 1865 /// also requires the chain to be, or dominate, the first admission's chain; this test 1866 /// fails if replay or the store call skips that check. 1867 #[test] 1868 fn b89_a_forger_minted_leaf_link_verifies_but_never_owns_a_revision() { 1869 let owner: &[u8] = &[1, 2]; 1870 let record = admission(path(owner), owner, 1); 1871 let id = match &record { 1872 WalRecord::RevisionAdmitted { envelope, .. } => envelope.changeset_id(), 1873 _ => unreachable!(), 1874 }; 1875 let forger = key_of(&[7]); 1876 let forged = |parent: Option<&[u8]>| { 1877 let (parent_digest, mut digests) = match parent { 1878 None => (ROOT_PARENT, Vec::new()), 1879 Some(labels) => (link_of(labels).digest(), path(labels).links().to_vec()), 1880 }; 1881 let link = CapabilityLink::issue( 1882 &forger, 1883 parent_digest, 1884 derived("forged nonce", parent.unwrap_or(&[])), 1885 repo(), 1886 forger.verifying_key().to_bytes(), 1887 caveats(), 1888 ); 1889 digests.push(link.digest().0); 1890 let chain = ChainPath::new(digests).unwrap(); 1891 let to = RevisionState::Proposed; 1892 SignedStateMove { 1893 repo_id: repo(), 1894 changeset_id: id, 1895 to, 1896 signature: SignedStateMove::sign_statement(&forger, &repo(), id, to, &chain, 6_000), 1897 chain, 1898 signed_at_ms: 6_000, 1899 leaf_link: link, 1900 mover_key: forger.verifying_key().to_bytes(), 1901 } 1902 }; 1903 let moves = [forged(None), forged(Some(owner))]; 1904 for m in &moves { 1905 assert_eq!( 1906 m.verify(), 1907 Ok(()), 1908 "verify alone accepts a forger-minted leaf" 1909 ); 1910 } 1911 let mut log = vec![ 1912 (WalSeq(1), record), 1913 (WalSeq(2), moved(signed(owner, id, RevisionState::Draft))), 1914 ]; 1915 // The revision is `Draft`, so every chain sees it: only ownership can refuse. 1916 let shared = RevisionLedger::from_log(log.clone(), None); 1917 for m in &moves { 1918 let err = shared.plan_move(m).unwrap_err(); 1919 assert_eq!(err.code, RefusalCode::AuthChainNotDominant); 1920 } 1921 log.extend( 1922 moves 1923 .into_iter() 1924 .zip(3..) 1925 .map(|(m, n)| (WalSeq(n), moved(m))), 1926 ); 1927 let replayed = RevisionLedger::from_log(log, None); 1928 assert_eq!( 1929 replayed.get_revision(&repo(), id).unwrap().state, 1930 RevisionState::Draft 1931 ); 1932 assert_eq!(replayed.state_move_report().not_owner_move, 2); 1933 } 1934 1935 /// Issue #89 acceptance 2: a legitimate signed owner move round-trips write, strict 1936 /// replay, checkpoint, and compaction, and the state root covers it. 1937 #[test] 1938 fn b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction() { 1939 const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; 1940 let owner: &[u8] = &[1, 2]; 1941 let dir = temp_dir("legit"); 1942 let mut s = open(&dir, STRICT).unwrap(); 1943 let id = admit(&mut s, owner); 1944 let before = s.state_root_digest(None).unwrap(); 1945 s.advance_revision_state(signed(owner, id, RevisionState::Draft), 6_000) 1946 .unwrap(); 1947 let root = s.state_root_digest(None).unwrap(); 1948 assert_ne!(root, before, "the state root covers the move"); 1949 drop(s); 1950 let check = |s: &SynapseStore| { 1951 assert_eq!( 1952 s.get_revision(&repo(), id).unwrap().state, 1953 RevisionState::Draft 1954 ); 1955 assert_eq!( 1956 s.state_move_replay_report(), 1957 StateMoveReplayReport::default() 1958 ); 1959 assert_eq!(s.state_root_digest(None).unwrap(), root); 1960 }; 1961 let mut s = open(&dir, STRICT).unwrap(); 1962 check(&s); 1963 s.checkpoint_and_compact(7_000).unwrap(); 1964 check(&s); 1965 drop(s); 1966 check(&open(&dir, STRICT).unwrap()); 1967 let _ = std::fs::remove_dir_all(&dir); 1968 } 1969 1970 /// The kind 9 record digest (an input of the state root) covers every signed and 1971 /// unsigned field, so two logs that differ only in a signature, a mover key, or a leaf 1972 /// link have different state roots. 1973 #[test] 1974 fn b89_state_root_record_digest_covers_the_signature_fields() { 1975 let id = ChangesetId(derived("changeset", &[1])); 1976 let m = signed(&[1, 2], id, RevisionState::Draft); 1977 let base = record_digest(&moved(m.clone())); 1978 let mut other_leaf = m.clone(); 1979 other_leaf.leaf_link = link_of(&[1, 9]); 1980 let variants = [ 1981 bad_signature(m.clone()), 1982 non_leaf_signer(m.clone(), &[1, 9]), 1983 other_leaf, 1984 SignedStateMove { 1985 signed_at_ms: 6_001, 1986 ..m.clone() 1987 }, 1988 ]; 1989 for v in variants { 1990 assert_ne!(record_digest(&moved(v)), base); 1991 } 1992 let later = WalRecord::RevisionStateMoved { 1993 state_move: m, 1994 moved_at_ms: 6_001, 1995 seal: None, 1996 }; 1997 assert_ne!(record_digest(&later), base); 1998 } 1999 2000 // --------------------------------------------------------------------------------- 2001 // Issue #101: the keyed seal over revision records 2002 // --------------------------------------------------------------------------------- 2003 2004 fn server_key() -> crate::RevisionSealKey { 2005 crate::RevisionSealKey::new(SigningKey::from_bytes(&derived("server machine key", &[]))) 2006 } 2007 2008 fn open_sealed(dir: &PathBuf, policy: RecoveryPolicy) -> SynapseResult { 2009 open_sealed_with(dir, policy, server_key()) 2010 } 2011 2012 fn open_sealed_with( 2013 dir: &PathBuf, 2014 policy: RecoveryPolicy, 2015 key: crate::RevisionSealKey, 2016 ) -> SynapseResult { 2017 let limits = StoreLimits { 2018 wal_prealloc_bytes: 64 * 1024, 2019 ..Default::default() 2020 }; 2021 SynapseStore::open_sealed(dir, FsyncPolicy::EveryCommit, policy, limits, key) 2022 } 2023 2024 /// A root link a forger minted with its own key (no repository authority signed it), 2025 /// delegating to itself: what a whole-log rewrite can put in an unsigned `chain` field. 2026 fn forger_chain() -> (SigningKey, CapabilityChain, ChainPath) { 2027 let forger = key_of(&[7]); 2028 let link = CapabilityLink::issue( 2029 &forger, 2030 ROOT_PARENT, 2031 derived("forged nonce", &[]), 2032 repo(), 2033 forger.verifying_key().to_bytes(), 2034 caveats(), 2035 ); 2036 let chain = CapabilityChain::new(vec![link]); 2037 let digests = chain.link_digests().iter().map(|d| d.0).collect(); 2038 (forger, chain, ChainPath::new(digests).unwrap()) 2039 } 2040 2041 fn with_chain(mut record: WalRecord, swapped: ChainPath) -> WalRecord { 2042 if let WalRecord::RevisionAdmitted { chain, .. } = &mut record { 2043 *chain = swapped; 2044 } 2045 record 2046 } 2047 2048 /// Issue #101 acceptance 1: a whole-log rewrite that swaps an admission's chain for a 2049 /// forger-minted one and signs an owner move under it. Written through the store's own 2050 /// framing (valid CRC32C and hash chain), carrying over the honest record's seal bytes. 2051 /// Opened without a seal key (the behaviour on PR #100's head) the forger owns and 2052 /// publishes the revision; opened with the server's seal key the rewrite changes nothing: 2053 /// strict recovery refuses the store, torn-tail recovery applies neither record. A 2054 /// rewrite resealed with another key is refused the same way. 2055 #[test] 2056 fn s101_whole_log_rewrite_swapping_an_admission_chain_changes_nothing_on_sealed_replay() { 2057 const TORN: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; 2058 const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; 2059 let owner: &[u8] = &[1, 2]; 2060 let honest_dir = temp_dir("s101-honest"); 2061 let mut s = open_sealed(&honest_dir, STRICT).unwrap(); 2062 let id = admit(&mut s, owner); 2063 let honest = s.revision_records()[0].1.clone(); 2064 assert!( 2065 honest.seal().is_some(), 2066 "a sealed store seals what it writes" 2067 ); 2068 drop(s); 2069 2070 let (forger, forger_links, forged_chain) = forger_chain(); 2071 let forged_move = SignedStateMove::sign_new( 2072 &forger, 2073 repo(), 2074 id, 2075 RevisionState::Draft, 2076 &forger_links, 2077 6_000, 2078 ) 2079 .unwrap(); 2080 assert_eq!(forged_move.verify(), Ok(())); 2081 2082 for reseal in [None, Some(crate::RevisionSealKey::new(key_of(&[8])))] { 2083 let dir = temp_dir("s101-forged"); 2084 // The rewrite: a fresh log holding the swapped admission and the forged move. 2085 let mut w = match reseal.clone() { 2086 None => open(&dir, STRICT).unwrap(), 2087 Some(k) => open_sealed_with(&dir, STRICT, k).unwrap(), 2088 }; 2089 let swapped = with_chain(honest.clone(), forged_chain.clone()); 2090 let blob = body(1); 2091 w.append_revision_record(swapped, &[(BlobDigest::compute(&blob), &blob[..])], None) 2092 .unwrap(); 2093 w.append_revision_record(moved(forged_move.clone()), &[], None) 2094 .unwrap(); 2095 drop(w); 2096 2097 // Without a seal key the rewrite takes effect: the attack of issue #101. 2098 let unsealed = open(&dir, STRICT).unwrap(); 2099 let rev = unsealed.get_revision(&repo(), id).unwrap(); 2100 assert_eq!(rev.state, RevisionState::Draft); 2101 assert_eq!(rev.witnesses[0].chain, forged_chain); 2102 2103 let err = open_sealed(&dir, STRICT).err().unwrap(); 2104 assert_eq!(err.code, RefusalCode::RevisionRecordUnsealed, "{err:?}"); 2105 let s = open_sealed(&dir, TORN).unwrap(); 2106 assert_eq!( 2107 s.get_revision(&repo(), id).unwrap_err().code, 2108 RefusalCode::ChangesetNotFound, 2109 "the swapped admission must change nothing" 2110 ); 2111 let report = s.seal_replay_report(); 2112 assert_eq!(report.unsealed, 2, "{report:?}"); 2113 assert_eq!(report.first_unsealed, Some(WalSeq(1))); 2114 assert_eq!( 2115 s.state_move_replay_report(), 2116 StateMoveReplayReport::default(), 2117 "an unsealed move is not even considered" 2118 ); 2119 let _ = std::fs::remove_dir_all(&dir); 2120 } 2121 let _ = std::fs::remove_dir_all(&honest_dir); 2122 } 2123 2124 /// Records appended to a sealed store without the key (here by opening it without one) 2125 /// change nothing on sealed replay; the honest records keep their meaning, the store 2126 /// keeps sealing after them, and a torn-tail compaction drops exactly the unsealed 2127 /// records so strict recovery accepts the store again with the same states and root. 2128 #[test] 2129 fn s101_appended_unsealed_records_change_nothing_and_compaction_restores_strict() { 2130 const TORN: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; 2131 const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; 2132 let owner: &[u8] = &[1, 2]; 2133 let dir = temp_dir("s101-appended"); 2134 let mut s = open_sealed(&dir, STRICT).unwrap(); 2135 let id = admit(&mut s, owner); 2136 drop(s); 2137 2138 let (forger, forger_links, forged_chain) = forger_chain(); 2139 let forged = admission(forged_chain, &[7], 2); 2140 let forged_id = match &forged { 2141 WalRecord::RevisionAdmitted { envelope, .. } => envelope.changeset_id(), 2142 _ => unreachable!(), 2143 }; 2144 let mut w = open(&dir, STRICT).unwrap(); 2145 let blob = body(2); 2146 w.append_revision_record(forged, &[(BlobDigest::compute(&blob), &blob[..])], None) 2147 .unwrap(); 2148 let forged_move = SignedStateMove::sign_new( 2149 &forger, 2150 repo(), 2151 forged_id, 2152 RevisionState::Proposed, 2153 &forger_links, 2154 6_000, 2155 ) 2156 .unwrap(); 2157 w.append_revision_record(moved(forged_move), &[], None) 2158 .unwrap(); 2159 drop(w); 2160 2161 assert_eq!( 2162 open_sealed(&dir, STRICT).err().unwrap().code, 2163 RefusalCode::RevisionRecordUnsealed 2164 ); 2165 let mut s = open_sealed(&dir, TORN).unwrap(); 2166 assert_eq!(s.seal_replay_report().unsealed, 2); 2167 assert!(s.get_revision(&repo(), forged_id).is_err()); 2168 // The sealed chain continues after the unsealed records. 2169 s.advance_revision_state(signed(owner, id, RevisionState::Draft), 6_500) 2170 .unwrap(); 2171 drop(s); 2172 let mut s = open_sealed(&dir, TORN).unwrap(); 2173 assert_eq!( 2174 s.get_revision(&repo(), id).unwrap().state, 2175 RevisionState::Draft 2176 ); 2177 s.checkpoint_and_compact(7_000).unwrap(); 2178 assert_eq!(s.seal_replay_report().dropped_by_compaction, 2); 2179 assert_eq!(s.seal_replay_report().unsealed, 0); 2180 let root = s.state_root_digest(None).unwrap(); 2181 drop(s); 2182 let s = open_sealed(&dir, STRICT).expect("strict accepts the compacted store"); 2183 assert_eq!( 2184 s.get_revision(&repo(), id).unwrap().state, 2185 RevisionState::Draft 2186 ); 2187 assert!(s.get_revision(&repo(), forged_id).is_err()); 2188 assert_eq!(s.seal_replay_report(), SealReplayReport::default()); 2189 assert_eq!(s.state_root_digest(None).unwrap(), root); 2190 let _ = std::fs::remove_dir_all(&dir); 2191 } 2192 2193 /// The seal chain binds each record's sequence and the records before it: removing a 2194 /// sealed record (its sequence filled by anything else), reordering two sealed 2195 /// admissions (which would hand ownership to the second admitter), or changing any 2196 /// field breaks the chain from that record on. The ledger applies nothing from there. 2197 #[test] 2198 fn s101_removed_reordered_or_edited_sealed_records_break_the_chain() { 2199 let key = server_key(); 2200 let public = Some(key.public_key()); 2201 // Two admissions of the same content by different chains, then an owner move. 2202 let first = admission(path(&[1, 2]), &[1, 2], 1); 2203 let joiner = admission(path(&[3]), &[3], 1); 2204 let id = match &first { 2205 WalRecord::RevisionAdmitted { envelope, .. } => envelope.changeset_id(), 2206 _ => unreachable!(), 2207 }; 2208 let mut sealing = RevisionLedger::new(public); 2209 let mut log = Vec::new(); 2210 for (n, mut r) in [ 2211 first, 2212 joiner, 2213 moved(signed(&[1, 2], id, RevisionState::Draft)), 2214 ] 2215 .into_iter() 2216 .enumerate() 2217 { 2218 let seq = WalSeq(n as u64 + 1); 2219 sealing.seal_record(&key, seq, &mut r); 2220 sealing.apply(seq, r.clone()); 2221 log.push((seq, r)); 2222 } 2223 let honest = RevisionLedger::from_log(log.clone(), public); 2224 assert_eq!(honest.seal_report(), SealReplayReport::default()); 2225 let rev = honest.get_revision(&repo(), id).unwrap(); 2226 assert_eq!(rev.state, RevisionState::Draft); 2227 assert_eq!(rev.witnesses[0].chain, path(&[1, 2])); 2228 2229 // Removed: the joiner's record is gone; the move after it no longer verifies. 2230 let removed = vec![log[0].clone(), log[2].clone()]; 2231 let l = RevisionLedger::from_log(removed, public); 2232 assert_eq!(l.seal_report().first_unsealed, Some(WalSeq(3))); 2233 assert_eq!( 2234 l.get_revision(&repo(), id).unwrap().state, 2235 RevisionState::Private 2236 ); 2237 2238 // Reordered: the joiner first would own the revision; neither record verifies. 2239 let reordered = vec![ 2240 (WalSeq(1), log[1].1.clone()), 2241 (WalSeq(2), log[0].1.clone()), 2242 log[2].clone(), 2243 ]; 2244 let l = RevisionLedger::from_log(reordered, public); 2245 assert_eq!(l.seal_report().unsealed, 3); 2246 assert!(l.get_revision(&repo(), id).is_none()); 2247 2248 // Edited: the first admission's time changed, everything after it is cut off. 2249 let mut edited = log.clone(); 2250 if let WalRecord::RevisionAdmitted { admitted_at_ms, .. } = &mut edited[0].1 { 2251 *admitted_at_ms += 1; 2252 } 2253 let l = RevisionLedger::from_log(edited, public); 2254 assert_eq!(l.seal_report().unsealed, 3); 2255 2256 // Without a seal key the seals are carried but not checked. 2257 let unchecked = RevisionLedger::from_log(log, None); 2258 assert_eq!(unchecked.seal_report(), SealReplayReport::default()); 2259 assert_eq!( 2260 unchecked.get_revision(&repo(), id).unwrap().state, 2261 RevisionState::Draft 2262 ); 2263 } 2264 2265 /// Issue #101 acceptance 2: a legitimate sealed store (admission, owner move, marker) 2266 /// round-trips strict replay, checkpoint, and compaction unchanged, with the same state 2267 /// root as the same operations in an unsealed store (the seal is not part of the root). 2268 #[test] 2269 fn s101_sealed_store_round_trips_replay_checkpoint_and_compaction() { 2270 const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; 2271 let owner: &[u8] = &[1, 2]; 2272 let run = |s: &mut SynapseStore| { 2273 let id = admit(s, owner); 2274 s.advance_revision_state(signed(owner, id, RevisionState::Draft), 6_000) 2275 .unwrap(); 2276 let marker = ObsolescenceMarker::sign_new( 2277 &key_of(owner), 2278 repo(), 2279 ChangeId([1; 16]), 2280 id, 2281 vec![], 2282 6_100, 2283 ); 2284 s.record_obsolescence(marker, path(owner), 6_200).unwrap(); 2285 id 2286 }; 2287 let plain_dir = temp_dir("s101-plain"); 2288 let mut plain = open(&plain_dir, STRICT).unwrap(); 2289 run(&mut plain); 2290 let plain_root = plain.state_root_digest(None).unwrap(); 2291 2292 let dir = temp_dir("s101-roundtrip"); 2293 let mut s = open_sealed(&dir, STRICT).unwrap(); 2294 let id = run(&mut s); 2295 assert_eq!(s.revision_records().len(), 3); 2296 assert!(s.revision_records().iter().all(|(_, r)| r.seal().is_some())); 2297 assert_eq!(s.state_root_digest(None).unwrap(), plain_root); 2298 drop(s); 2299 let check = |s: &SynapseStore| { 2300 assert_eq!( 2301 s.get_revision(&repo(), id).unwrap().state, 2302 RevisionState::Draft 2303 ); 2304 assert_eq!( 2305 s.change_status(&repo(), ChangeId([1; 16])) 2306 .unwrap() 2307 .obsolete, 2308 vec![id] 2309 ); 2310 assert_eq!(s.seal_replay_report(), SealReplayReport::default()); 2311 assert_eq!(s.state_root_digest(None).unwrap(), plain_root); 2312 }; 2313 let mut s = open_sealed(&dir, STRICT).unwrap(); 2314 check(&s); 2315 s.checkpoint_and_compact(7_000).unwrap(); 2316 check(&s); 2317 // Writing after the checkpoint continues the same chain. 2318 s.advance_revision_state(signed(owner, id, RevisionState::Proposed), 7_100) 2319 .unwrap(); 2320 drop(s); 2321 let s = open_sealed(&dir, STRICT).unwrap(); 2322 assert_eq!( 2323 s.get_revision(&repo(), id).unwrap().state, 2324 RevisionState::Proposed 2325 ); 2326 assert_eq!(s.seal_replay_report(), SealReplayReport::default()); 2327 drop(s); 2328 // An existing unsealed store is refused by strict sealed recovery: its records 2329 // predate the seal and cannot be told apart from forgeries. 2330 drop(plain); 2331 assert_eq!( 2332 open_sealed(&plain_dir, STRICT).err().unwrap().code, 2333 RefusalCode::RevisionRecordUnsealed 2334 ); 2335 let _ = std::fs::remove_dir_all(&dir); 2336 let _ = std::fs::remove_dir_all(&plain_dir); 2337 } 2338 2339 /// The segment store (group commit) seals and replays the same way. 2340 #[test] 2341 fn s101_group_commit_store_seals_and_replays() { 2342 const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; 2343 let owner: &[u8] = &[1, 2]; 2344 let dir = temp_dir("s101-group"); 2345 let reopen = || { 2346 let limits = StoreLimits { 2347 wal_prealloc_bytes: 64 * 1024, 2348 ..Default::default() 2349 }; 2350 let fsync = FsyncPolicy::GroupCommit { 2351 max_batch_records: 8, 2352 max_batch_delay_us: 0, 2353 }; 2354 SynapseStore::open_sealed(&dir, fsync, STRICT, limits, server_key()).unwrap() 2355 }; 2356 let mut s = reopen(); 2357 let id = admit(&mut s, owner); 2358 s.advance_revision_state(signed(owner, id, RevisionState::Draft), 6_000) 2359 .unwrap(); 2360 assert!(s.revision_records().iter().all(|(_, r)| r.seal().is_some())); 2361 drop(s); 2362 let mut s = reopen(); 2363 assert_eq!( 2364 s.get_revision(&repo(), id).unwrap().state, 2365 RevisionState::Draft 2366 ); 2367 s.checkpoint_and_compact(7_000).unwrap(); 2368 s.advance_revision_state(signed(owner, id, RevisionState::Proposed), 7_100) 2369 .unwrap(); 2370 drop(s); 2371 let s = reopen(); 2372 assert_eq!( 2373 s.get_revision(&repo(), id).unwrap().state, 2374 RevisionState::Proposed 2375 ); 2376 assert_eq!(s.seal_replay_report(), SealReplayReport::default()); 2377 let _ = std::fs::remove_dir_all(&dir); 2378 } 2379 2380 /// The seal trailer is canonical: sealed records of every kind round-trip the binary 2381 /// codec, an unsealed record ends at its body, a trailer cut short is `Truncated`, and 2382 /// bytes that do not open with the seal tag, or follow a seal, are `TrailingBytes`. 2383 #[test] 2384 fn s101_seal_trailer_round_trips_and_malformed_trailers_are_refused_typed() { 2385 let key = server_key(); 2386 let id = ChangesetId(derived("changeset", &[1])); 2387 let marker = ObsolescenceMarker::sign_new( 2388 &key_of(&[1]), 2389 repo(), 2390 ChangeId([1; 16]), 2391 id, 2392 vec![], 2393 6_100, 2394 ); 2395 let records = [ 2396 admission(path(&[1, 2]), &[1, 2], 1), 2397 moved(signed(&[1, 2], id, RevisionState::Draft)), 2398 WalRecord::ObsolescenceRecorded { 2399 marker, 2400 chain: path(&[1]), 2401 recorded_at_ms: 6_200, 2402 seal: None, 2403 }, 2404 ]; 2405 let cap = 1 << 20; 2406 for mut record in records { 2407 let unsealed = crate::codec::encode_record(&record).unwrap(); 2408 let ledger = RevisionLedger::new(Some(key.public_key())); 2409 ledger.seal_record(&key, WalSeq(1), &mut record); 2410 let sealed = crate::codec::encode_record(&record).unwrap(); 2411 assert_eq!(sealed.len(), unsealed.len() + 97); 2412 assert_eq!(&sealed[..unsealed.len()], &unsealed[..]); 2413 assert_eq!(crate::codec::decode_record(&sealed, cap).unwrap(), record); 2414 let mut bad_tag = sealed.clone(); 2415 bad_tag[unsealed.len()] = 2; 2416 assert!(matches!( 2417 crate::codec::decode_record(&bad_tag, cap), 2418 Err(crate::CodecRefusal::TrailingBytes { .. }) 2419 )); 2420 for cut in unsealed.len() + 1..sealed.len() { 2421 assert!(matches!( 2422 crate::codec::decode_record(&sealed[..cut], cap), 2423 Err(crate::CodecRefusal::Truncated { .. }) 2424 )); 2425 } 2426 let mut extra = sealed.clone(); 2427 extra.push(0); 2428 assert!(matches!( 2429 crate::codec::decode_record(&extra, cap), 2430 Err(crate::CodecRefusal::TrailingBytes { .. }) 2431 )); 2432 } 2433 } 2434 }