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-api/tests/b4_revision_states.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-api / tests / b4_revision_states.rs` 475 lines ยท 17430 bytes Raw Blame History 1 //! ADR 0003 step B4 through the API with real signed F1 capability chains: authority `A` 2 //! grants orchestrator `O`, outsider `X`, and publisher `P` (root links; `P` may also 3 //! `Publish` and touch the canonical reference through the promotion queue); `O` delegates 4 //! worker `W` (scoped to `src`), worker `V` (whole repository), and reader `D` (scoped to 5 //! `docs`). 6 7 use `ed25519`_dalek::SigningKey; 8 use sha2::{Digest, Sha256}; 9 use std::path::{Path, PathBuf}; 10 use synapse_api::{RevisionStateMovePayload, SynapseService, TreeTarget}; 11 use synapse_auth::{ 12 Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, 13 LinkCaveats, OperationSet, PathScope, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT, 14 }; 15 use synapse_core::{ 16 encode_did_key_`ed25519`, BlobDigest, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, 17 GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, 18 RevisionState, TreeDigest, WalSeq, 19 }; 20 use synapse_store::{FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, StoredRevision}; 21 22 const NOW: u64 = 2_000; 23 const C: ChangeId = ChangeId([0xC4; 16]); 24 25 type Agent = (SigningKey, CapabilityChain); 26 27 /// Link nonces for one fixture: SHA-256 of the fixture's unique directory and a counter, so 28 /// every link gets a fresh nonce and none is a fixed value. 29 fn link_nonces(dir: &Path) -> impl FnMut() -> [u8; 32] { 30 let seed = dir.to_string_lossy().into_owned(); 31 let mut issued = 0u32; 32 move || { 33 issued += 1; 34 let mut h = Sha256::new(); 35 h.update(seed.as_bytes()); 36 h.update(issued.to_le_bytes()); 37 h.finalize().into() 38 } 39 } 40 41 fn repo() -> RepoId { 42 RepoId::new("aien-spark/synapse").unwrap() 43 } 44 45 fn pk(k: &SigningKey) -> [u8; 32] { 46 k.verifying_key().to_bytes() 47 } 48 49 fn caveats( 50 ops: &[Capability], 51 paths: PathScope, 52 refs: &[ReferenceKind], 53 share: u64, 54 ) -> LinkCaveats { 55 LinkCaveats { 56 operations: OperationSet::from_capabilities(ops), 57 paths, 58 references: ReferenceScope::from_kinds(refs), 59 changes: ChangeScope::any(), 60 quotas: ChainQuotas { 61 max_ops_per_window: (1_000 / share) as u32, 62 window_duration_ms: 60_000, 63 storage_bytes: (1 << 30) / share, 64 footprint_paths: (1 << 20) / share, 65 max_bytes_per_op: 1 << 20, 66 }, 67 issued_at_ms: 1_000, 68 expires_at_ms: 100_000, 69 } 70 } 71 72 struct Fx { 73 svc: SynapseService, 74 base: TreeDigest, 75 o: Agent, 76 w: Agent, 77 v: Agent, 78 d: Agent, 79 x: Agent, 80 p: Agent, 81 nonce: u8, 82 } 83 84 impl Fx { 85 fn new(name: &str) -> Self { 86 let dir: PathBuf = std::env::temp_dir().join(format!( 87 "synapse-b4-api-{name}-{}-{}", 88 std::process::id(), 89 std::time::SystemTime::now() 90 .duration_since(std::time::UNIX_EPOCH) 91 .unwrap() 92 .as_nanos() 93 )); 94 let mut svc = SynapseService::open( 95 &dir, 96 repo(), 97 FsyncPolicy::EveryCommit, 98 RecoveryPolicy::StrictFailClosed, 99 StoreLimits { 100 wal_prealloc_bytes: 64 * 1024, 101 ..Default::default() 102 }, 103 ) 104 .unwrap(); 105 let a = SigningKey::from_bytes(&[1; 32]); 106 let key = |n: u8| SigningKey::from_bytes(&[n; 32]); 107 let (o, w, v, d, x, p) = (key(2), key(3), key(4), key(5), key(9), key(7)); 108 svc.auth_mut() 109 .register_repo_authority(repo(), encode_did_key_`ed25519`(&pk(&a))); 110 let rp = [Capability::Read, Capability::Propose]; 111 let own = [ReferenceKind::OwnDrafts]; 112 let whole = PathScope::whole_repository; 113 let mut nonce = link_nonces(&dir); 114 let root = |nonce: [u8; 32], to: &SigningKey, c: LinkCaveats| { 115 CapabilityLink::issue(&a, ROOT_PARENT, nonce, repo(), pk(to), c) 116 }; 117 let root_o = root(nonce(), &o, caveats(&rp, whole(), &own, 1)); 118 let root_x = root(nonce(), &x, caveats(&rp, whole(), &own, 1)); 119 let root_p = root( 120 nonce(), 121 &p, 122 caveats( 123 &[Capability::Read, Capability::Propose, Capability::Publish], 124 whole(), 125 &[ 126 ReferenceKind::OwnDrafts, 127 ReferenceKind::CanonicalViaPromotionQueue, 128 ], 129 1, 130 ), 131 ); 132 let child = |nonce: [u8; 32], to: &SigningKey, paths: PathScope| { 133 CapabilityLink::issue( 134 &o, 135 root_o.digest(), 136 nonce, 137 repo(), 138 pk(to), 139 caveats(&rp, paths, &own, 4), 140 ) 141 }; 142 let link_w = child(nonce(), &w, PathScope::new(vec!["src".into()]).unwrap()); 143 let link_v = child(nonce(), &v, whole()); 144 let link_d = child(nonce(), &d, PathScope::new(vec!["docs".into()]).unwrap()); 145 let co = CapabilityChain::new(vec![root_o]); 146 let cx = CapabilityChain::new(vec![root_x]); 147 let cp = CapabilityChain::new(vec![root_p]); 148 let (cw, cv, cd) = ( 149 co.extended(link_w), 150 co.extended(link_v), 151 co.extended(link_d), 152 ); 153 for c in [&co, &cx, &cp, &cw, &cv, &cd] { 154 svc.auth_mut().grant_link(c, WalSeq(0), NOW).unwrap(); 155 } 156 let base_oid = GitOid([0x0B; 20]); 157 svc.register_base_tree( 158 base_oid, 159 vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], 160 ) 161 .unwrap(); 162 let base = svc 163 .tree_digest(TreeTarget::BaseGitCommit(base_oid), None) 164 .unwrap(); 165 Self { 166 svc, 167 base, 168 o: (o, co), 169 w: (w, cw), 170 v: (v, cv), 171 d: (d, cd), 172 x: (x, cx), 173 p: (p, cp), 174 nonce: 0, 175 } 176 } 177 178 fn request( 179 &mut self, 180 who: &Agent, 181 cap: Capability, 182 scope: RequestScope, 183 payload: Vec, 184 ) -> ChainedRequest { 185 self.nonce += 1; 186 ChainedRequest::sign_new( 187 &who.0, 188 who.1.clone(), 189 repo(), 190 cap, 191 scope, 192 [self.nonce; 32], 193 NOW, 194 payload, 195 ) 196 } 197 198 /// `who` submits a revision of change `C` writing `body` to `src/lib.rs`. 199 fn submit(&mut self, who: &Agent, body: &[u8], idem: u8) -> ChangesetId { 200 let content = RevisionContent { 201 change_id: C, 202 base_tree: self.base, 203 parents: vec![], 204 mutations: vec![PathMutation { 205 path: "src/lib.rs".into(), 206 op: MutationOp::Upsert { 207 mode: FileMode::Regular644, 208 blob_digest: BlobDigest::compute(body), 209 size_bytes: body.len() as u64, 210 }, 211 }], 212 intent_summary: "implement the task".into(), 213 }; 214 let env = 215 ChangesetEnvelopeV2::sign_new(&who.0, repo(), content, IdempotencyKey([idem; 32]), NOW); 216 let scope = RequestScope { 217 paths: vec!["src/lib.rs".into()], 218 reference: None, 219 join_change: Some(C), 220 }; 221 let req = self.request(who, Capability::Propose, scope, env.encode()); 222 let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; 223 match self.svc.submit_revision(&req, &blobs, NOW).unwrap() { 224 RevisionOutcome::Admitted { changeset_id, .. } => changeset_id, 225 other => panic!("expected an admission, got {other:?}"), 226 } 227 } 228 229 fn read( 230 &mut self, 231 who: &Agent, 232 id: ChangesetId, 233 ) -> Result { 234 let req = self.request( 235 who, 236 Capability::Read, 237 RequestScope::default(), 238 id.0.to_vec(), 239 ); 240 self.svc 241 .read_revision(&req, NOW) 242 .map_err(|e| (e.code, e.message)) 243 } 244 245 fn mv( 246 &mut self, 247 who: &Agent, 248 id: ChangesetId, 249 to: RevisionState, 250 ) -> Result { 251 let payload = RevisionStateMovePayload::sign_new(&who.0, &repo(), &who.1, id, to, NOW) 252 .unwrap() 253 .encode(); 254 let req = self.request(who, Capability::Propose, RequestScope::default(), payload); 255 self.svc 256 .advance_revision_state(&req, NOW) 257 .map_err(|e| e.code) 258 } 259 } 260 261 /// Acceptance 2 with real F1 chains: `W`'s `Private` revision is readable by `W` and by `O` 262 /// (whose grant `W`'s descends from) and by nobody else: not by the sibling `V`, the reader 263 /// `D`, or the outsider `X`, each refused exactly like an unknown revision; none of them can 264 /// move it. After `W` moves it to `Draft` it is visible within `Read` scope: to `V` and `X`, 265 /// still not to `D`, whose path scope does not cover `src/lib.rs`. 266 #[test] 267 fn b4_api_private_revision_is_invisible_outside_its_owner_chain_with_real_f1_chains() { 268 let mut fx = Fx::new("private"); 269 let (o, w, v, d, x, p) = ( 270 fx.o.clone(), 271 fx.w.clone(), 272 fx.v.clone(), 273 fx.d.clone(), 274 fx.x.clone(), 275 fx.p.clone(), 276 ); 277 fx.submit(&o, b"orchestrator attempt", 1); 278 let rev = fx.submit(&w, b"worker private attempt", 1); 279 assert_eq!(fx.read(&w, rev).unwrap().state, RevisionState::Private); 280 assert_eq!(fx.read(&o, rev).unwrap().changeset_id, rev); 281 let unknown = ChangesetId([0xEE; 32]); 282 let (code, msg) = fx.read(&o, unknown).unwrap_err(); 283 assert_eq!(code, RefusalCode::ChangesetNotFound); 284 for outsider in [&v, &d, &x, &p] { 285 let (c, m) = fx.read(outsider, rev).unwrap_err(); 286 assert_eq!(c, code); 287 assert_eq!(m, msg.replace(&unknown.to_string(), &rev.to_string())); 288 assert_eq!( 289 fx.mv(outsider, rev, RevisionState::Draft).unwrap_err(), 290 RefusalCode::ChangesetNotFound 291 ); 292 } 293 // The owner shares it: Draft is visible within Read scope. 294 fx.mv(&w, rev, RevisionState::Draft).unwrap(); 295 for reader in [&o, &w, &v, &x, &p] { 296 assert_eq!(fx.read(reader, rev).unwrap().state, RevisionState::Draft); 297 } 298 assert_eq!( 299 fx.read(&d, rev).unwrap_err().0, 300 RefusalCode::ChangesetNotFound 301 ); 302 // A non-owner may read the Draft but not move it. 303 assert_eq!( 304 fx.mv(&v, rev, RevisionState::Proposed).unwrap_err(), 305 RefusalCode::AuthChainNotDominant 306 ); 307 // The orchestrator, whose grant W's descends from, may propose it; then it never goes back. 308 fx.mv(&o, rev, RevisionState::Proposed).unwrap(); 309 for to in [ 310 RevisionState::Private, 311 RevisionState::Draft, 312 RevisionState::Proposed, 313 ] { 314 assert_eq!( 315 fx.mv(&w, rev, to).unwrap_err(), 316 RefusalCode::RevisionStateMoveInvalid 317 ); 318 } 319 assert_eq!(fx.read(&x, rev).unwrap().state, RevisionState::Proposed); 320 } 321 322 /// Acceptance 3 with real F1 chains: a move to `Canonical` through the state API is refused 323 /// for every chain, including one whose grant allows `Publish` and the canonical reference 324 /// through the promotion queue; nothing is written. Malformed payloads are refused typed. 325 #[test] 326 fn b4_api_move_to_canonical_outside_the_promotion_queue_is_refused() { 327 let mut fx = Fx::new("canonical"); 328 let (o, w, x, p) = (fx.o.clone(), fx.w.clone(), fx.x.clone(), fx.p.clone()); 329 let rev = fx.submit(&w, b"worker attempt", 1); 330 fx.mv(&w, rev, RevisionState::Proposed).unwrap(); 331 let before = fx.svc.store().committed_seq(); 332 for who in [&o, &w, &x, &p] { 333 for id in [rev, ChangesetId([0xEE; 32])] { 334 assert_eq!( 335 fx.mv(who, id, RevisionState::Canonical).unwrap_err(), 336 RefusalCode::CanonicalOutsidePromotionQueue 337 ); 338 } 339 } 340 // Asking with the canonical reference in the request scope changes nothing. 341 let payload = 342 RevisionStateMovePayload::sign_new(&p.0, &repo(), &p.1, rev, RevisionState::Canonical, NOW) 343 .unwrap() 344 .encode(); 345 let scope = RequestScope { 346 paths: vec![], 347 reference: Some(ReferenceKind::CanonicalViaPromotionQueue), 348 join_change: None, 349 }; 350 let req = fx.request(&p, Capability::Propose, scope, payload); 351 assert_eq!( 352 fx.svc.advance_revision_state(&req, NOW).unwrap_err().code, 353 RefusalCode::CanonicalOutsidePromotionQueue 354 ); 355 assert_eq!( 356 fx.mv(&w, rev, RevisionState::Verified).unwrap_err(), 357 RefusalCode::RevisionStateMoveInvalid 358 ); 359 assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); 360 assert_eq!( 361 fx.svc.store().get_revision(&repo(), rev).unwrap().state, 362 RevisionState::Proposed 363 ); 364 // Payloads: exactly changeset_id [32] | state 1..=5 | signed_at_ms u64 | signature [64]. 365 let good = 366 RevisionStateMovePayload::sign_new(&w.0, &repo(), &w.1, rev, RevisionState::Draft, NOW) 367 .unwrap() 368 .encode(); 369 assert_eq!(good.len(), RevisionStateMovePayload::LEN); 370 let mut bad_tag = good.clone(); 371 bad_tag[32] = 6; 372 let mut longer = good.clone(); 373 longer.push(0); 374 let v1_layout = good[..33].to_vec(); 375 for payload in [vec![], v1_layout, bad_tag, good[..104].to_vec(), longer] { 376 let req = fx.request(&w, Capability::Propose, RequestScope::default(), payload); 377 assert_eq!( 378 fx.svc.advance_revision_state(&req, NOW).unwrap_err().code, 379 RefusalCode::EnvelopeMalformed 380 ); 381 } 382 let req = fx.request(&w, Capability::Read, RequestScope::default(), vec![0; 31]); 383 assert_eq!( 384 fx.svc.read_revision(&req, NOW).unwrap_err().code, 385 RefusalCode::EnvelopeMalformed 386 ); 387 } 388 389 /// Joins with real F1 chains: `W`, whose grant descends from `O`'s, submits content 390 /// byte-identical to `O`'s `Private` revision and joins it (B1), but gains no ownership: it 391 /// cannot read the revision (so not `O`'s witness or attestation) and cannot move it to 392 /// `Draft`, so the outsider `X` still cannot see it. Only after `O` shares it can `W` read 393 /// it, and moving it stays `O`'s. 394 #[test] 395 fn b4_api_joining_identical_content_grants_no_ownership_of_a_private_revision() { 396 let mut fx = Fx::new("join"); 397 let (o, w, x) = (fx.o.clone(), fx.w.clone(), fx.x.clone()); 398 let rev = fx.submit(&o, b"orchestrator private attempt", 1); 399 assert_eq!(fx.submit(&w, b"orchestrator private attempt", 2), rev); 400 assert_eq!(fx.read(&o, rev).unwrap().witnesses.len(), 2); 401 for who in [&w, &x] { 402 assert_eq!( 403 fx.read(who, rev).unwrap_err().0, 404 RefusalCode::ChangesetNotFound 405 ); 406 } 407 assert_eq!( 408 fx.mv(&w, rev, RevisionState::Draft).unwrap_err(), 409 RefusalCode::ChangesetNotFound 410 ); 411 assert_eq!( 412 fx.read(&x, rev).unwrap_err().0, 413 RefusalCode::ChangesetNotFound 414 ); 415 fx.mv(&o, rev, RevisionState::Draft).unwrap(); 416 assert_eq!(fx.read(&w, rev).unwrap().state, RevisionState::Draft); 417 assert_eq!( 418 fx.mv(&w, rev, RevisionState::Proposed).unwrap_err(), 419 RefusalCode::AuthChainNotDominant 420 ); 421 } 422 423 /// Issue #89: the request agent must sign the move itself. A payload signed by another key 424 /// (even the owner's ancestor `O`), or whose signature covers another state, chain, or time, 425 /// is `AuthSignatureInvalid` and writes nothing. The agent's own signed move is recorded with 426 /// its signature and the chain's leaf link, and still applies after a reopen (strict recovery). 427 #[test] 428 fn b89_api_state_moves_must_be_signed_by_the_request_agent() { 429 let mut fx = Fx::new("signed"); 430 let (o, w) = (fx.o.clone(), fx.w.clone()); 431 let rev = fx.submit(&w, b"worker attempt", 1); 432 let before = fx.svc.store().committed_seq(); 433 let signed = |by: &Agent, chain_of: &Agent, to: RevisionState| { 434 RevisionStateMovePayload::sign_new(&by.0, &repo(), &chain_of.1, rev, to, NOW).unwrap() 435 }; 436 let mut other_state = signed(&w, &w, RevisionState::Proposed); 437 other_state.to = RevisionState::Draft; 438 let mut other_time = signed(&w, &w, RevisionState::Draft); 439 other_time.signed_at_ms += 1; 440 let mut flipped = signed(&w, &w, RevisionState::Draft); 441 flipped.signature[0] ^= 1; 442 for payload in [ 443 signed(&o, &w, RevisionState::Draft), 444 signed(&w, &o, RevisionState::Draft), 445 other_state, 446 other_time, 447 flipped, 448 ] { 449 let req = fx.request( 450 &w, 451 Capability::Propose, 452 RequestScope::default(), 453 payload.encode(), 454 ); 455 assert_eq!( 456 fx.svc.advance_revision_state(&req, NOW).unwrap_err().code, 457 RefusalCode::AuthSignatureInvalid 458 ); 459 } 460 assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); 461 assert_eq!( 462 fx.svc.store().get_revision(&repo(), rev).unwrap().state, 463 RevisionState::Private 464 ); 465 fx.mv(&w, rev, RevisionState::Draft).unwrap(); 466 assert_eq!( 467 fx.svc.store().get_revision(&repo(), rev).unwrap().state, 468 RevisionState::Draft 469 ); 470 assert_eq!( 471 fx.svc.store().state_move_replay_report(), 472 Default::default(), 473 "a store's own writes are never counted" 474 ); 475 }