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/b1_chained_revisions.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 / b1_chained_revisions.rs` 332 lines ยท 11816 bytes Raw Blame History 1 //! ADR 0003 step B1 through the API with real signed F1 capability chains: authority `A` 2 //! grants orchestrator `O` and outsider `X` (root links); `O` delegates worker `W` (scoped to 3 //! `src`) and worker `V` (scoped to change `C`). 4 5 use `ed25519`_dalek::SigningKey; 6 use std::path::PathBuf; 7 use synapse_api::{RevisionStateMovePayload, SynapseService, TreeTarget}; 8 use synapse_auth::{ 9 Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, 10 LinkCaveats, OperationSet, PathScope, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT, 11 }; 12 use synapse_core::{ 13 encode_did_key_`ed25519`, BlobDigest, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, 14 GitOid, IdempotencyKey, MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RepoId, 15 RevisionContent, RevisionState, TreeDigest, WalSeq, 16 }; 17 use synapse_store::{FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits}; 18 19 const NOW: u64 = 2_000; 20 const C: ChangeId = ChangeId([0xC1; 16]); 21 22 fn repo() -> RepoId { 23 RepoId::new("aien-spark/synapse").unwrap() 24 } 25 26 fn pk(k: &SigningKey) -> [u8; 32] { 27 k.verifying_key().to_bytes() 28 } 29 30 /// `share` is the part of the parent's quotas a child link takes (children of one parent 31 /// must partition its quotas). 32 fn caveats(paths: PathScope, changes: ChangeScope, share: u64) -> LinkCaveats { 33 LinkCaveats { 34 operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), 35 paths, 36 references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]), 37 changes, 38 quotas: ChainQuotas { 39 max_ops_per_window: (1_000 / share) as u32, 40 window_duration_ms: 60_000, 41 storage_bytes: (1 << 30) / share, 42 footprint_paths: (1 << 20) / share, 43 max_bytes_per_op: 1 << 20, 44 }, 45 issued_at_ms: 1_000, 46 expires_at_ms: 100_000, 47 } 48 } 49 50 struct Fx { 51 svc: SynapseService, 52 base: TreeDigest, 53 o: (SigningKey, CapabilityChain), 54 w: (SigningKey, CapabilityChain), 55 v: (SigningKey, CapabilityChain), 56 x: (SigningKey, CapabilityChain), 57 nonce: u8, 58 } 59 60 impl Fx { 61 fn new(name: &str) -> Self { 62 let dir: PathBuf = std::env::temp_dir().join(format!( 63 "synapse-b1-api-{name}-{}-{}", 64 std::process::id(), 65 std::time::SystemTime::now() 66 .duration_since(std::time::UNIX_EPOCH) 67 .unwrap() 68 .as_nanos() 69 )); 70 let mut svc = SynapseService::open( 71 &dir, 72 repo(), 73 FsyncPolicy::EveryCommit, 74 RecoveryPolicy::StrictFailClosed, 75 StoreLimits { 76 wal_prealloc_bytes: 64 * 1024, 77 ..Default::default() 78 }, 79 ) 80 .unwrap(); 81 let a = SigningKey::from_bytes(&[1; 32]); 82 let key = |n: u8| SigningKey::from_bytes(&[n; 32]); 83 let (o, w, v, x) = (key(2), key(3), key(4), key(9)); 84 svc.auth_mut() 85 .register_repo_authority(repo(), encode_did_key_`ed25519`(&pk(&a))); 86 let whole = PathScope::whole_repository; 87 let root_o = CapabilityLink::issue( 88 &a, 89 ROOT_PARENT, 90 [0xA0; 32], 91 repo(), 92 pk(&o), 93 caveats(whole(), ChangeScope::any(), 1), 94 ); 95 let root_x = CapabilityLink::issue( 96 &a, 97 ROOT_PARENT, 98 [0xA9; 32], 99 repo(), 100 pk(&x), 101 caveats(whole(), ChangeScope::any(), 1), 102 ); 103 let link_w = CapabilityLink::issue( 104 &o, 105 root_o.digest(), 106 [0xB3; 32], 107 repo(), 108 pk(&w), 109 caveats( 110 PathScope::new(vec!["src".into()]).unwrap(), 111 ChangeScope::any(), 112 4, 113 ), 114 ); 115 let link_v = CapabilityLink::issue( 116 &o, 117 root_o.digest(), 118 [0xB4; 32], 119 repo(), 120 pk(&v), 121 caveats(whole(), ChangeScope::only(vec![C]).unwrap(), 4), 122 ); 123 let co = CapabilityChain::new(vec![root_o]); 124 let cx = CapabilityChain::new(vec![root_x]); 125 let cw = co.extended(link_w); 126 let cv = co.extended(link_v); 127 for c in [&co, &cx, &cw, &cv] { 128 svc.auth_mut().grant_link(c, WalSeq(0), NOW).unwrap(); 129 } 130 let base_oid = GitOid([0x0B; 20]); 131 svc.register_base_tree( 132 base_oid, 133 vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], 134 ) 135 .unwrap(); 136 let base = svc 137 .tree_digest(TreeTarget::BaseGitCommit(base_oid), None) 138 .unwrap(); 139 Self { 140 svc, 141 base, 142 o: (o, co), 143 w: (w, cw), 144 v: (v, cv), 145 x: (x, cx), 146 nonce: 0, 147 } 148 } 149 150 fn envelope(&self, author: &SigningKey, body: &[u8], idem: u8) -> ChangesetEnvelopeV2 { 151 let content = RevisionContent { 152 change_id: C, 153 base_tree: self.base, 154 parents: vec![], 155 mutations: vec![PathMutation { 156 path: "src/lib.rs".into(), 157 op: MutationOp::Upsert { 158 mode: FileMode::Regular644, 159 blob_digest: BlobDigest::compute(body), 160 size_bytes: body.len() as u64, 161 }, 162 }], 163 intent_summary: "implement the task".into(), 164 }; 165 ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey([idem; 32]), NOW) 166 } 167 168 fn request( 169 &mut self, 170 who: &(SigningKey, CapabilityChain), 171 paths: Vec, 172 payload: Vec, 173 ) -> ChainedRequest { 174 self.nonce += 1; 175 ChainedRequest::sign_new( 176 &who.0, 177 who.1.clone(), 178 repo(), 179 Capability::Propose, 180 RequestScope { 181 paths, 182 reference: None, 183 join_change: Some(C), 184 }, 185 [self.nonce; 32], 186 NOW, 187 payload, 188 ) 189 } 190 191 fn submit( 192 &mut self, 193 who: &(SigningKey, CapabilityChain), 194 body: &[u8], 195 idem: u8, 196 ) -> Result { 197 let env = self.envelope(&who.0, body, idem); 198 let req = self.request(who, vec!["src/lib.rs".into()], env.encode()); 199 let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; 200 self.svc 201 .submit_revision(&req, &blobs, NOW) 202 .map_err(|e| e.code) 203 } 204 205 /// The owner shares a revision (ADR 0003 B4): `Private` -> `Draft`, so chains outside 206 /// its owner chain see it and are refused for dominance rather than as unknown. 207 fn share(&mut self, who: &(SigningKey, CapabilityChain), rev: ChangesetId) { 208 let payload = RevisionStateMovePayload::sign_new( 209 &who.0, 210 &repo(), 211 &who.1, 212 rev, 213 RevisionState::Draft, 214 NOW, 215 ) 216 .unwrap() 217 .encode(); 218 let req = self.request(who, vec![], payload); 219 self.svc.advance_revision_state(&req, NOW).unwrap(); 220 } 221 222 fn mark( 223 &mut self, 224 who: &(SigningKey, CapabilityChain), 225 pred: ChangesetId, 226 succ: Vec, 227 ) -> Result { 228 let m = ObsolescenceMarker::sign_new(&who.0, repo(), C, pred, succ, NOW); 229 let req = self.request(who, vec![], m.encode()); 230 self.svc.record_obsolescence(&req, NOW).map_err(|e| e.code) 231 } 232 } 233 234 fn id(o: RevisionOutcome) -> ChangesetId { 235 match o { 236 RevisionOutcome::Admitted { changeset_id, .. } 237 | RevisionOutcome::IdempotentDuplicate { changeset_id, .. } => changeset_id, 238 } 239 } 240 241 #[test] 242 fn b1_api_join_and_prune_follow_the_creating_chain_of_real_f1_chains() { 243 let mut fx = Fx::new("join-prune"); 244 let (o, w, v, x) = (fx.o.clone(), fx.w.clone(), fx.v.clone(), fx.x.clone()); 245 let a = id(fx.submit(&o, b"orchestrator attempt", 1).unwrap()); 246 // W descends from the creating chain (O's): it joins without change scope. 247 let b = id(fx.submit(&w, b"worker attempt", 1).unwrap()); 248 // X is outside it and its grant allows any change, which names none: refused. 249 assert_eq!( 250 fx.submit(&x, b"outsider attempt", 1).unwrap_err(), 251 RefusalCode::AuthChangeOutOfScope 252 ); 253 // V's grant names C explicitly. 254 fx.submit(&v, b"scoped attempt", 1).unwrap(); 255 fx.share(&o, a); 256 // Pruning needs a chain that is or dominates the creating chain. 257 assert_eq!( 258 fx.mark(&w, a, vec![]).unwrap_err(), 259 RefusalCode::AuthChainNotDominant 260 ); 261 assert_eq!( 262 fx.mark(&x, a, vec![]).unwrap_err(), 263 RefusalCode::AuthChainNotDominant 264 ); 265 fx.mark(&o, b, vec![]).unwrap(); 266 let st = fx.svc.store().change_status(&repo(), C).unwrap(); 267 assert_eq!(st.obsolete, vec![b]); 268 assert!( 269 st.divergent, 270 "the orchestrator's and V's attempts are both live" 271 ); 272 // Identical content from O and W: one revision, two attestations, two witnesses. 273 let r1 = id(fx.submit(&o, b"agreed", 7).unwrap()); 274 let r2 = id(fx.submit(&w, b"agreed", 7).unwrap()); 275 assert_eq!(r1, r2); 276 let rev = fx.svc.store().get_revision(&repo(), r1).unwrap(); 277 assert_eq!((rev.attestations.len(), rev.witnesses.len()), (2, 2)); 278 let digests = |c: &CapabilityChain| c.link_digests().iter().map(|d| d.0).collect::>(); 279 assert_eq!(rev.witnesses[0].chain.links(), digests(&o.1).as_slice()); 280 assert_eq!(rev.witnesses[1].chain.links(), digests(&w.1).as_slice()); 281 // A repeat with the same repository, DID, and idempotency key: the first WalSeq. 282 let first = rev.witnesses[0].admission_seq; 283 assert_eq!( 284 fx.submit(&o, b"agreed", 7).unwrap(), 285 RevisionOutcome::IdempotentDuplicate { 286 wal_seq: first, 287 changeset_id: r1 288 } 289 ); 290 } 291 292 #[test] 293 fn b1_api_refuses_paths_outside_scope_foreign_authors_and_unknown_bases() { 294 let mut fx = Fx::new("refusals"); 295 let (o, w) = (fx.o.clone(), fx.w.clone()); 296 fx.submit(&o, b"created", 1).unwrap(); 297 // W's path scope is `src`: a revision touching `docs` is refused by F1. 298 let mut env = fx.envelope(&w.0, b"doc", 2); 299 env.content.mutations[0].path = "docs/x.md".into(); 300 let env = 301 ChangesetEnvelopeV2::sign_new(&w.0, repo(), env.content, IdempotencyKey([2; 32]), NOW); 302 let req = fx.request(&w, vec!["docs/x.md".into()], env.encode()); 303 assert_eq!( 304 fx.svc.submit_revision(&req, &[], NOW).unwrap_err().code, 305 RefusalCode::AuthPathOutOfScope 306 ); 307 // The request scope must list exactly the mutation paths. 308 let env = fx.envelope(&w.0, b"x", 3); 309 let req = fx.request(&w, vec![], env.encode()); 310 assert_eq!( 311 fx.svc.submit_revision(&req, &[], NOW).unwrap_err().code, 312 RefusalCode::AuthPathOutOfScope 313 ); 314 // An envelope attested by another key than the chain's agent. 315 let env = fx.envelope(&o.0, b"y", 4); 316 let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); 317 assert_eq!( 318 fx.svc.submit_revision(&req, &[], NOW).unwrap_err().code, 319 RefusalCode::AuthSignatureInvalid 320 ); 321 // An unknown base tree. 322 let mut env = fx.envelope(&w.0, b"z", 5); 323 env.content.base_tree = TreeDigest([0xEE; 32]); 324 let env = 325 ChangesetEnvelopeV2::sign_new(&w.0, repo(), env.content, IdempotencyKey([5; 32]), NOW); 326 let blobs = vec![(BlobDigest::compute(b"z"), b"z".to_vec())]; 327 let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); 328 assert_eq!( 329 fx.svc.submit_revision(&req, &blobs, NOW).unwrap_err().code, 330 RefusalCode::BaseTreeNotFound 331 ); 332 }