synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / tests / b4_revision_states.rs
| 1 | //! ADR 0003 step B4 acceptance tests (issue #28): the revision state machine (`Private`, |
| 2 | //! `Draft`, `Proposed`, `Verified`, `Canonical`). Over random operation sequences no revision |
| 3 | //! moves backwards; a `Private` revision is invisible to every key outside its owner chain; |
| 4 | //! any move to `Canonical` outside the promotion queue is refused. Chains here are digests of |
| 5 | //! real F1 links from the shared fixture (`common`), and every state move carries its leaf |
| 6 | //! link and the leaf key's signature (issue #89). |
| 7 | //! |
| 8 | //! The property tests use a seeded SplitMix64 generator (no new dependency, as in F1); the |
| 9 | //! seed and case counts are fixed so every run checks the same sequences. |
| 10 | |
| 11 | use ed25519_dalek::SigningKey; |
| 12 | use std::collections::BTreeMap; |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | use synapse_core::{ |
| 15 | BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, IdempotencyKey, |
| 16 | MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RevisionContent, RevisionState, |
| 17 | TreeDigest, |
| 18 | }; |
| 19 | mod common; |
| 20 | use common::{key_of, mv, path, repo, signed}; |
| 21 | use synapse_store::codec::{decode_record, encode_record}; |
| 22 | use synapse_store::{ |
| 23 | AdmissionAuthority, FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, SynapseStore, |
| 24 | WalRecord, |
| 25 | }; |
| 26 | |
| 27 | const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; |
| 28 | const CHANGE: ChangeId = ChangeId([0xC4; 16]); |
| 29 | |
| 30 | struct SplitMix64(u64); |
| 31 | |
| 32 | impl SplitMix64 { |
| 33 | fn next(&mut self) -> u64 { |
| 34 | self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 35 | let mut z = self.0; |
| 36 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 37 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 38 | z ^ (z >> 31) |
| 39 | } |
| 40 | |
| 41 | fn below(&mut self, n: u64) -> u64 { |
| 42 | self.next() % n |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn temp_dir(name: &str) -> PathBuf { |
| 47 | let nanos = std::time::SystemTime::now() |
| 48 | .duration_since(std::time::UNIX_EPOCH) |
| 49 | .unwrap() |
| 50 | .as_nanos(); |
| 51 | let dir = |
| 52 | std::env::temp_dir().join(format!("synapse-b4-{name}-{}-{nanos}", std::process::id())); |
| 53 | std::fs::create_dir_all(&dir).unwrap(); |
| 54 | dir |
| 55 | } |
| 56 | |
| 57 | fn open(dir: &Path, policy: FsyncPolicy) -> SynapseStore { |
| 58 | let limits = StoreLimits { |
| 59 | wal_prealloc_bytes: 64 * 1024, |
| 60 | ..Default::default() |
| 61 | }; |
| 62 | SynapseStore::open(dir, policy, STRICT, limits).unwrap() |
| 63 | } |
| 64 | |
| 65 | /// The delegation tree: root `R` = [1]; orchestrator `O` = [1,2] under it; workers |
| 66 | /// `W1` = [1,2,3] and `W2` = [1,2,4] under `O`; `W1s` = [1,2,3,5], a sub-delegate of `W1`; |
| 67 | /// outsider `X` = [1,9] beside `O`. Each chain presents its own key. |
| 68 | const TREE: [&[u8]; 6] = [ |
| 69 | &[1], |
| 70 | &[1, 2], |
| 71 | &[1, 2, 3], |
| 72 | &[1, 2, 4], |
| 73 | &[1, 2, 3, 5], |
| 74 | &[1, 9], |
| 75 | ]; |
| 76 | |
| 77 | fn auth(chain: &ChainPath) -> AdmissionAuthority { |
| 78 | AdmissionAuthority { |
| 79 | chain: chain.clone(), |
| 80 | change_scope: Vec::new(), |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// A revision of `change` writing `body` to `src/lib.rs`, with its blob. |
| 85 | fn revision( |
| 86 | author: &SigningKey, |
| 87 | change: ChangeId, |
| 88 | body: &[u8], |
| 89 | idem: [u8; 32], |
| 90 | parents: Vec<ChangesetId>, |
| 91 | ) -> (ChangesetEnvelopeV2, Vec<(BlobDigest, Vec<u8>)>) { |
| 92 | let digest = BlobDigest::compute(body); |
| 93 | let content = RevisionContent { |
| 94 | change_id: change, |
| 95 | base_tree: TreeDigest([0x7E; 32]), |
| 96 | parents, |
| 97 | mutations: vec![PathMutation { |
| 98 | path: "src/lib.rs".into(), |
| 99 | op: MutationOp::Upsert { |
| 100 | mode: FileMode::Regular644, |
| 101 | blob_digest: digest, |
| 102 | size_bytes: body.len() as u64, |
| 103 | }, |
| 104 | }], |
| 105 | intent_summary: "implement the task".into(), |
| 106 | }; |
| 107 | let env = ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey(idem), 1_000); |
| 108 | (env, vec![(digest, body.to_vec())]) |
| 109 | } |
| 110 | |
| 111 | fn admit(s: &mut SynapseStore, links: &[u8], body: &[u8], idem: u8) -> ChangesetId { |
| 112 | let (env, blobs) = revision(&key_of(links), CHANGE, body, [idem; 32], vec![]); |
| 113 | match s |
| 114 | .admit_revision(env, &blobs, auth(&path(links)), 5_000) |
| 115 | .unwrap() |
| 116 | { |
| 117 | RevisionOutcome::Admitted { changeset_id, .. } => changeset_id, |
| 118 | other => panic!("expected an admission, got {other:?}"), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | fn state(s: &SynapseStore, id: ChangesetId) -> RevisionState { |
| 123 | s.get_revision(&repo(), id).unwrap().state |
| 124 | } |
| 125 | |
| 126 | /// The model the store must agree with: owner moves along the edges of section 5.3 only. |
| 127 | fn model_move( |
| 128 | current: RevisionState, |
| 129 | to: RevisionState, |
| 130 | owner: bool, |
| 131 | visible: bool, |
| 132 | ) -> Result<RevisionState, RefusalCode> { |
| 133 | if to == RevisionState::Canonical { |
| 134 | return Err(RefusalCode::CanonicalOutsidePromotionQueue); |
| 135 | } |
| 136 | if !visible { |
| 137 | return Err(RefusalCode::ChangesetNotFound); |
| 138 | } |
| 139 | if !owner { |
| 140 | return Err(RefusalCode::AuthChainNotDominant); |
| 141 | } |
| 142 | let edge = matches!( |
| 143 | (current, to), |
| 144 | (RevisionState::Private, RevisionState::Draft) |
| 145 | | (RevisionState::Private, RevisionState::Proposed) |
| 146 | | (RevisionState::Draft, RevisionState::Proposed) |
| 147 | ); |
| 148 | if edge { |
| 149 | Ok(to) |
| 150 | } else { |
| 151 | Err(RefusalCode::RevisionStateMoveInvalid) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// Property (acceptance 1): over random operation sequences (admissions by random chains, |
| 156 | /// moves of random revisions to random states by random chains, reopen with replay, and |
| 157 | /// checkpoint with compaction), no revision ever moves backwards, none reaches `Verified` or |
| 158 | /// `Canonical`, every outcome equals the model's, and a refused move writes nothing. |
| 159 | #[test] |
| 160 | fn b4_property_random_operation_sequences_never_move_a_revision_backwards() { |
| 161 | let mut rng = SplitMix64(0xB4_0001); |
| 162 | let mut moves_applied = 0u32; |
| 163 | let mut refusals = BTreeMap::<String, u32>::new(); |
| 164 | for case in 0..12 { |
| 165 | let policy = if case % 2 == 0 { |
| 166 | FsyncPolicy::EveryCommit |
| 167 | } else { |
| 168 | FsyncPolicy::GROUP_COMMIT_DEFAULT |
| 169 | }; |
| 170 | let dir = temp_dir(&format!("property-{case}")); |
| 171 | let mut s = open(&dir, policy); |
| 172 | // Every revision: (id, change, body, admission chains (the first owns it), last state). |
| 173 | let mut known: Vec<(ChangesetId, ChangeId, String, Vec<ChainPath>, RevisionState)> = |
| 174 | Vec::new(); |
| 175 | let mut idem = 0u32; |
| 176 | for _op in 0..40 { |
| 177 | idem += 1; |
| 178 | let mut idem_key = [0u8; 32]; |
| 179 | idem_key[..4].copy_from_slice(&idem.to_le_bytes()); |
| 180 | match rng.below(10) { |
| 181 | // Admit a revision under a fresh change (no join rule in play) from a random |
| 182 | // chain, or identical content of a known revision from another chain whose |
| 183 | // grant names that change (one revision, one more witness, no new owner). |
| 184 | 0..=2 => { |
| 185 | let links = TREE[rng.below(TREE.len() as u64) as usize]; |
| 186 | let rejoin = !known.is_empty() && rng.below(3) == 0; |
| 187 | let (change, body) = if rejoin { |
| 188 | let k = &known[rng.below(known.len() as u64) as usize]; |
| 189 | (k.1, k.2.clone()) |
| 190 | } else { |
| 191 | ( |
| 192 | ChangeId([(idem % 251) as u8; 16]), |
| 193 | format!("revision {idem}"), |
| 194 | ) |
| 195 | }; |
| 196 | let (env, blobs) = |
| 197 | revision(&key_of(links), change, body.as_bytes(), idem_key, vec![]); |
| 198 | let id = env.changeset_id(); |
| 199 | let authority = AdmissionAuthority { |
| 200 | chain: path(links), |
| 201 | change_scope: vec![change], |
| 202 | }; |
| 203 | let out = s.admit_revision(env, &blobs, authority, 5_000).unwrap(); |
| 204 | assert!(matches!(out, RevisionOutcome::Admitted { .. })); |
| 205 | match known.iter_mut().find(|k| k.0 == id) { |
| 206 | Some(k) => k.3.push(path(links)), |
| 207 | None => { |
| 208 | assert_eq!(state(&s, id), RevisionState::Private, "starts Private"); |
| 209 | known.push(( |
| 210 | id, |
| 211 | change, |
| 212 | body, |
| 213 | vec![path(links)], |
| 214 | RevisionState::Private, |
| 215 | )); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | // Attempt a move of a random revision (or an unknown ID) to a random state. |
| 220 | 3..=7 => { |
| 221 | if known.is_empty() { |
| 222 | continue; |
| 223 | } |
| 224 | let i = rng.below(known.len() as u64) as usize; |
| 225 | let unknown = rng.below(16) == 0; |
| 226 | let id = if unknown { |
| 227 | ChangesetId([0xEE; 32]) |
| 228 | } else { |
| 229 | known[i].0 |
| 230 | }; |
| 231 | let to = RevisionState::ALL[rng.below(5) as usize]; |
| 232 | let labels = TREE[rng.below(TREE.len() as u64) as usize]; |
| 233 | let chain = path(labels); |
| 234 | let (cur, owners) = (known[i].4, &known[i].3); |
| 235 | let owner = !unknown && chain.dominates(&owners[0]); |
| 236 | let visible = !unknown && (cur != RevisionState::Private || owner); |
| 237 | let expected = model_move(cur, to, owner, visible); |
| 238 | let before = s.committed_seq(); |
| 239 | let got = mv(&mut s, labels, id, to, 6_000).map_err(|e| e.code); |
| 240 | match (&expected, &got) { |
| 241 | (Ok(want), Ok(_)) => { |
| 242 | known[i].4 = *want; |
| 243 | moves_applied += 1; |
| 244 | } |
| 245 | (Err(want), Err(code)) => { |
| 246 | assert_eq!(want, code, "{cur:?} -> {to:?}"); |
| 247 | assert_eq!(s.committed_seq(), before, "a refusal writes nothing"); |
| 248 | *refusals.entry(format!("{code:?}")).or_default() += 1; |
| 249 | } |
| 250 | _ => panic!("{cur:?} -> {to:?}: model {expected:?}, store {got:?}"), |
| 251 | } |
| 252 | } |
| 253 | // Reopen: the ledger is rebuilt by replay. |
| 254 | 8 => { |
| 255 | drop(s); |
| 256 | s = open(&dir, policy); |
| 257 | } |
| 258 | // Checkpoint with compaction, then reopen from the checkpoint. |
| 259 | _ => { |
| 260 | s.checkpoint_and_compact(9_000).unwrap(); |
| 261 | drop(s); |
| 262 | s = open(&dir, policy); |
| 263 | } |
| 264 | } |
| 265 | for (id, _, _, _, last) in &mut known { |
| 266 | let now = state(&s, *id); |
| 267 | assert!( |
| 268 | now.rank() >= last.rank(), |
| 269 | "revision {id} moved backwards {last:?} -> {now:?}" |
| 270 | ); |
| 271 | assert!( |
| 272 | now <= RevisionState::Proposed, |
| 273 | "revision {id} reached {now:?}" |
| 274 | ); |
| 275 | assert_eq!(now, *last, "store and model agree on revision {id}"); |
| 276 | *last = now; |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | // The sequences exercised every outcome. |
| 281 | assert!(moves_applied > 0); |
| 282 | for code in [ |
| 283 | "CanonicalOutsidePromotionQueue", |
| 284 | "ChangesetNotFound", |
| 285 | "AuthChainNotDominant", |
| 286 | "RevisionStateMoveInvalid", |
| 287 | ] { |
| 288 | assert!(refusals.contains_key(code), "no {code} in {refusals:?}"); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// Acceptance 2: a `Private` revision is invisible to every key outside its owner chain |
| 293 | /// (the submitting chain and the chains it descends from): not readable, not listed in its |
| 294 | /// change, not nameable as a parent or in a marker, not movable, also after replay and a |
| 295 | /// checkpoint. Checked for the fixed delegation tree and for random chains. |
| 296 | #[test] |
| 297 | fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { |
| 298 | let dir = temp_dir("private"); |
| 299 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 300 | let w1: &[u8] = &[1, 2, 3]; |
| 301 | let o: &[u8] = &[1, 2]; |
| 302 | // O creates the change (Draft, so the change itself is visible); W1 adds a Private one. |
| 303 | let shared = admit(&mut s, o, b"orchestrator draft", 1); |
| 304 | mv(&mut s, o, shared, RevisionState::Draft, 5_100).unwrap(); |
| 305 | let p = admit(&mut s, w1, b"worker private attempt", 1); |
| 306 | assert_eq!(state(&s, p), RevisionState::Private); |
| 307 | let unknown = ChangesetId([0xEE; 32]); |
| 308 | let not_found = s |
| 309 | .get_revision_visible_to(&repo(), unknown, &path(o)) |
| 310 | .unwrap_err(); |
| 311 | |
| 312 | let check = |s: &mut SynapseStore, labels: &[u8]| { |
| 313 | let viewer = &path(labels); |
| 314 | let owner = viewer.dominates(&path(w1)); |
| 315 | let read = s.get_revision_visible_to(&repo(), p, viewer); |
| 316 | let listed = s |
| 317 | .change_status_visible_to(&repo(), CHANGE, viewer) |
| 318 | .map(|st| st.revisions.contains(&p)) |
| 319 | .unwrap_or(false); |
| 320 | if owner { |
| 321 | assert_eq!(read.unwrap().changeset_id, p, "{viewer:?} owns it"); |
| 322 | assert!(listed, "{viewer:?} owns it"); |
| 323 | return; |
| 324 | } |
| 325 | // Refused exactly like an unknown revision: same code, same message shape. |
| 326 | let err = read.unwrap_err(); |
| 327 | assert_eq!(err.code, not_found.code, "{viewer:?}"); |
| 328 | assert_eq!( |
| 329 | err.message, |
| 330 | not_found |
| 331 | .message |
| 332 | .replace(&unknown.to_string(), &p.to_string()) |
| 333 | ); |
| 334 | assert!(!listed, "{viewer:?} must not see it in the change"); |
| 335 | let before = s.committed_seq(); |
| 336 | let signer = key_of(labels); |
| 337 | // Not nameable as a parent. |
| 338 | let (env, blobs) = revision( |
| 339 | &signer, |
| 340 | ChangeId([0x77; 16]), |
| 341 | b"child", |
| 342 | common::derived("idempotency", labels), |
| 343 | vec![p], |
| 344 | ); |
| 345 | assert_eq!( |
| 346 | s.admit_revision(env, &blobs, auth(viewer), 5_200) |
| 347 | .unwrap_err() |
| 348 | .code, |
| 349 | RefusalCode::ParentChangesetNotFound, |
| 350 | "{viewer:?}" |
| 351 | ); |
| 352 | // Not nameable in a marker, as predecessor or successor. |
| 353 | for (pred, succ) in [(p, vec![]), (shared, vec![p])] { |
| 354 | let m = ObsolescenceMarker::sign_new(&signer, repo(), CHANGE, pred, succ, 6_000); |
| 355 | assert_eq!( |
| 356 | s.record_obsolescence(m, viewer.clone(), 6_000) |
| 357 | .unwrap_err() |
| 358 | .code, |
| 359 | RefusalCode::ChangesetNotFound, |
| 360 | "{viewer:?}" |
| 361 | ); |
| 362 | } |
| 363 | // Not movable. |
| 364 | assert_eq!( |
| 365 | mv(s, labels, p, RevisionState::Draft, 6_000) |
| 366 | .unwrap_err() |
| 367 | .code, |
| 368 | RefusalCode::ChangesetNotFound, |
| 369 | "{viewer:?}" |
| 370 | ); |
| 371 | assert_eq!(s.committed_seq(), before, "nothing written"); |
| 372 | }; |
| 373 | |
| 374 | // The fixed tree: R, O, W1 own it; W2, the sub-delegate W1s, and X do not. |
| 375 | for links in TREE { |
| 376 | check(&mut s, links); |
| 377 | } |
| 378 | // Random chains over the same link alphabet. |
| 379 | let mut rng = SplitMix64(0xB4_0002); |
| 380 | for _ in 0..200 { |
| 381 | let len = 1 + rng.below(4) as usize; |
| 382 | let links: Vec<u8> = (0..len) |
| 383 | .map(|_| [1u8, 2, 3, 4, 5, 9][rng.below(6) as usize]) |
| 384 | .collect(); |
| 385 | check(&mut s, &links); |
| 386 | } |
| 387 | // The same after replay and after a checkpoint. |
| 388 | drop(s); |
| 389 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 390 | for links in TREE { |
| 391 | check(&mut s, links); |
| 392 | } |
| 393 | s.checkpoint_and_compact(9_000).unwrap(); |
| 394 | drop(s); |
| 395 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 396 | for links in TREE { |
| 397 | check(&mut s, links); |
| 398 | } |
| 399 | // Once its owner moves it to Draft, it is visible to every chain. |
| 400 | mv(&mut s, w1, p, RevisionState::Draft, 9_100).unwrap(); |
| 401 | for links in TREE { |
| 402 | let viewer = path(links); |
| 403 | assert_eq!( |
| 404 | s.get_revision_visible_to(&repo(), p, &viewer) |
| 405 | .unwrap() |
| 406 | .state, |
| 407 | RevisionState::Draft |
| 408 | ); |
| 409 | let st = s |
| 410 | .change_status_visible_to(&repo(), CHANGE, &viewer) |
| 411 | .unwrap(); |
| 412 | assert_eq!(st.revisions, vec![shared, p]); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | /// Acceptance 3: any move to `Canonical` outside the promotion queue is refused, from every |
| 417 | /// state, by every chain (owner, root, outsider), for known and unknown revisions, and |
| 418 | /// nothing is written. The owner chain cannot assert `Verified` either. |
| 419 | #[test] |
| 420 | fn b4_any_move_to_canonical_outside_the_promotion_queue_is_refused() { |
| 421 | let dir = temp_dir("canonical"); |
| 422 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 423 | let w1: &[u8] = &[1, 2, 3]; |
| 424 | let private = admit(&mut s, w1, b"private", 1); |
| 425 | let draft = admit(&mut s, w1, b"draft", 2); |
| 426 | let proposed = admit(&mut s, w1, b"proposed", 3); |
| 427 | mv(&mut s, w1, draft, RevisionState::Draft, 5_100).unwrap(); |
| 428 | mv(&mut s, w1, proposed, RevisionState::Proposed, 5_101).unwrap(); |
| 429 | let before = s.committed_seq(); |
| 430 | for id in [private, draft, proposed, ChangesetId([0xEE; 32])] { |
| 431 | for links in TREE { |
| 432 | let err = mv(&mut s, links, id, RevisionState::Canonical, 6_000).unwrap_err(); |
| 433 | assert_eq!(err.code, RefusalCode::CanonicalOutsidePromotionQueue); |
| 434 | } |
| 435 | } |
| 436 | for id in [private, draft, proposed] { |
| 437 | assert_eq!( |
| 438 | mv(&mut s, w1, id, RevisionState::Verified, 6_000) |
| 439 | .unwrap_err() |
| 440 | .code, |
| 441 | RefusalCode::RevisionStateMoveInvalid |
| 442 | ); |
| 443 | } |
| 444 | assert_eq!(s.committed_seq(), before, "nothing written"); |
| 445 | assert_eq!(state(&s, private), RevisionState::Private); |
| 446 | assert_eq!(state(&s, draft), RevisionState::Draft); |
| 447 | assert_eq!(state(&s, proposed), RevisionState::Proposed); |
| 448 | // Backwards and in place are refused too. |
| 449 | for to in [ |
| 450 | RevisionState::Private, |
| 451 | RevisionState::Draft, |
| 452 | RevisionState::Proposed, |
| 453 | ] { |
| 454 | assert_eq!( |
| 455 | mv(&mut s, w1, proposed, to, 6_000).unwrap_err().code, |
| 456 | RefusalCode::RevisionStateMoveInvalid |
| 457 | ); |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | /// Acceptance 2, joins: a chain outside the owner chain that submits byte-identical content |
| 462 | /// joins the existing `Private` revision (B1 identity) but gains no ownership of it. The |
| 463 | /// owner chain is fixed by the revision's first admission. The joiner cannot read it (its |
| 464 | /// witnesses and attestations stay hidden), cannot find it in the change, and cannot move |
| 465 | /// it; outsiders still cannot see it. After the owner shares it, the joiner may read it but |
| 466 | /// still not move it. The same holds after replay and a checkpoint. |
| 467 | #[test] |
| 468 | fn b4_joining_identical_content_grants_no_ownership_of_a_private_revision() { |
| 469 | let dir = temp_dir("join"); |
| 470 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 471 | let o: &[u8] = &[1, 2]; |
| 472 | let w1: &[u8] = &[1, 2, 3]; |
| 473 | let x: &[u8] = &[1, 9]; |
| 474 | let p = admit(&mut s, o, b"orchestrator private attempt", 1); |
| 475 | // W1 descends from the creating chain, so B1 lets it join without change scope. |
| 476 | let (env, blobs) = revision( |
| 477 | &key_of(w1), |
| 478 | CHANGE, |
| 479 | b"orchestrator private attempt", |
| 480 | [2; 32], |
| 481 | vec![], |
| 482 | ); |
| 483 | match s |
| 484 | .admit_revision(env, &blobs, auth(&path(w1)), 5_000) |
| 485 | .unwrap() |
| 486 | { |
| 487 | RevisionOutcome::Admitted { |
| 488 | changeset_id, |
| 489 | joined_existing_revision, |
| 490 | .. |
| 491 | } => { |
| 492 | assert_eq!(changeset_id, p); |
| 493 | assert!(joined_existing_revision); |
| 494 | } |
| 495 | other => panic!("expected a join, got {other:?}"), |
| 496 | } |
| 497 | assert_eq!(s.get_revision(&repo(), p).unwrap().witnesses.len(), 2); |
| 498 | let check = |s: &mut SynapseStore| { |
| 499 | assert_eq!(state(s, p), RevisionState::Private); |
| 500 | for labels in [w1, x] { |
| 501 | let viewer = path(labels); |
| 502 | assert_eq!( |
| 503 | s.get_revision_visible_to(&repo(), p, &viewer) |
| 504 | .unwrap_err() |
| 505 | .code, |
| 506 | RefusalCode::ChangesetNotFound, |
| 507 | "{viewer:?} joined or is outside: not an owner" |
| 508 | ); |
| 509 | assert!(s |
| 510 | .change_status_visible_to(&repo(), CHANGE, &viewer) |
| 511 | .is_err()); |
| 512 | let before = s.committed_seq(); |
| 513 | for to in [RevisionState::Draft, RevisionState::Proposed] { |
| 514 | assert_eq!( |
| 515 | mv(s, labels, p, to, 6_000).unwrap_err().code, |
| 516 | RefusalCode::ChangesetNotFound, |
| 517 | "{viewer:?}" |
| 518 | ); |
| 519 | } |
| 520 | assert_eq!(s.committed_seq(), before, "nothing written"); |
| 521 | } |
| 522 | assert_eq!( |
| 523 | s.get_revision_visible_to(&repo(), p, &path(o)) |
| 524 | .unwrap() |
| 525 | .witnesses |
| 526 | .len(), |
| 527 | 2 |
| 528 | ); |
| 529 | }; |
| 530 | check(&mut s); |
| 531 | drop(s); |
| 532 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 533 | check(&mut s); |
| 534 | s.checkpoint_and_compact(9_000).unwrap(); |
| 535 | drop(s); |
| 536 | let mut s = open(&dir, FsyncPolicy::EveryCommit); |
| 537 | check(&mut s); |
| 538 | // The owner shares it: the joiner reads it now, but moving it stays the owner's. |
| 539 | mv(&mut s, o, p, RevisionState::Draft, 9_100).unwrap(); |
| 540 | assert_eq!( |
| 541 | s.get_revision_visible_to(&repo(), p, &path(w1)) |
| 542 | .unwrap() |
| 543 | .state, |
| 544 | RevisionState::Draft |
| 545 | ); |
| 546 | assert_eq!( |
| 547 | mv(&mut s, w1, p, RevisionState::Proposed, 9_200) |
| 548 | .unwrap_err() |
| 549 | .code, |
| 550 | RefusalCode::AuthChainNotDominant |
| 551 | ); |
| 552 | mv(&mut s, o, p, RevisionState::Proposed, 9_300).unwrap(); |
| 553 | } |
| 554 | |
| 555 | /// The kind 9 v2 record (issue #89) round-trips byte for byte and its move verifies after |
| 556 | /// decoding; truncated, extended, unknown-state, and malformed-leaf-link bytes are refused |
| 557 | /// typed, never a panic; the unsigned layout of #88 is refused (truncated). |
| 558 | #[test] |
| 559 | fn b4_state_move_records_round_trip_and_malformed_bytes_are_refused_typed() { |
| 560 | let w1: &[u8] = &[1, 2, 3]; |
| 561 | let id = ChangesetId(common::derived("codec revision", &[])); |
| 562 | let record = WalRecord::RevisionStateMoved { |
| 563 | state_move: signed(w1, id, RevisionState::Proposed, 7), |
| 564 | moved_at_ms: 8, |
| 565 | seal: None, |
| 566 | }; |
| 567 | let bytes = encode_record(&record).unwrap(); |
| 568 | assert_eq!(record.kind_byte(), 9); |
| 569 | let decoded = decode_record(&bytes, 1 << 20).unwrap(); |
| 570 | assert_eq!(decoded, record); |
| 571 | assert_eq!(encode_record(&decoded).unwrap(), bytes); |
| 572 | match &decoded { |
| 573 | WalRecord::RevisionStateMoved { state_move, .. } => { |
| 574 | assert_eq!(state_move.verify(), Ok(())) |
| 575 | } |
| 576 | other => panic!("decoded {other:?}"), |
| 577 | } |
| 578 | for cut in 0..bytes.len() { |
| 579 | let err = decode_record(&bytes[..cut], 1 << 20).unwrap_err(); |
| 580 | assert!( |
| 581 | matches!(err.kind(), "Truncated" | "EmbeddedMalformed"), |
| 582 | "cut {cut}: {err:?}" |
| 583 | ); |
| 584 | } |
| 585 | let mut longer = bytes.clone(); |
| 586 | longer.push(0); |
| 587 | assert_eq!( |
| 588 | decode_record(&longer, 1 << 20).unwrap_err().kind(), |
| 589 | "TrailingBytes" |
| 590 | ); |
| 591 | // The state tag sits after the codec byte, kind, repo string, and changeset ID. |
| 592 | let tag_at = 2 + 4 + repo().as_str().len() + 32; |
| 593 | assert_eq!(bytes[tag_at], RevisionState::Proposed.tag_byte()); |
| 594 | for bad in [0u8, 6, 0xFF] { |
| 595 | let mut b = bytes.clone(); |
| 596 | b[tag_at] = bad; |
| 597 | assert_eq!( |
| 598 | decode_record(&b, 1 << 20).unwrap_err().kind(), |
| 599 | "UnknownTag", |
| 600 | "state tag {bad}" |
| 601 | ); |
| 602 | } |
| 603 | // #88's unsigned layout ends after `moved_at_ms`: `repo | id | to | chain | moved_at_ms`. |
| 604 | let v1_len = tag_at + 1 + 4 + (1 + 32 * w1.len()) + 8; |
| 605 | assert_eq!( |
| 606 | decode_record(&bytes[..v1_len], 1 << 20).unwrap_err().kind(), |
| 607 | "Truncated" |
| 608 | ); |
| 609 | // The leaf link is decoded strictly by `CapabilityLink::decode` (its version first). |
| 610 | let link_at = v1_len + 8 + 4; |
| 611 | let mut b = bytes.clone(); |
| 612 | b[link_at] ^= 0x02; |
| 613 | assert_eq!( |
| 614 | decode_record(&b, 1 << 20).unwrap_err().kind(), |
| 615 | "EmbeddedMalformed" |
| 616 | ); |
| 617 | for i in 2..bytes.len() { |
| 618 | let mut b = bytes.clone(); |
| 619 | b[i] ^= 0x41; |
| 620 | if let Ok(r) = decode_record(&b, 1 << 20) { |
| 621 | assert_ne!(r, record); |
| 622 | } |
| 623 | } |
| 624 | } |