synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-wire / src / testkit.rs
| 1 | //! Deterministic fixtures shared by the G1 tests, the fuzzer's seed corpus, and the |
| 2 | //! transport benchmark: fixed keys, a capability chain granted by a fixed repository |
| 3 | //! authority, signed envelopes, and one valid frame of every kind. |
| 4 | |
| 5 | use crate::frame::{Accepted, Chunk, Frame, FrameBody, Have, Hello, Refused, Want}; |
| 6 | use crate::session::submit_request; |
| 7 | use ed25519_dalek::SigningKey; |
| 8 | use synapse_auth::{ |
| 9 | Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, |
| 10 | OperationSet, PathScope, PolicyEnforcer, ReferenceKind, ReferenceScope, ROOT_PARENT, |
| 11 | }; |
| 12 | use synapse_core::{ |
| 13 | encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, ChangesetId, EvidenceAttachment, |
| 14 | FileMode, GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, WalSeq, |
| 15 | SYNAPSE_ENVELOPE_VERSION, |
| 16 | }; |
| 17 | |
| 18 | /// Repository of every fixture. |
| 19 | pub const REPO: &str = "aien-spark/synapse"; |
| 20 | |
| 21 | pub fn repo() -> RepoId { |
| 22 | RepoId::new(REPO).expect("valid fixture repository id") |
| 23 | } |
| 24 | |
| 25 | /// Links are valid from 0 to this time (milliseconds, year 2096). |
| 26 | pub const FIXTURE_EXPIRES_AT_MS: u64 = 4_000_000_000_000; |
| 27 | |
| 28 | fn wide_caveats() -> LinkCaveats { |
| 29 | LinkCaveats { |
| 30 | operations: OperationSet::from_capabilities(&[ |
| 31 | Capability::Read, |
| 32 | Capability::Propose, |
| 33 | Capability::Evaluate, |
| 34 | Capability::Review, |
| 35 | Capability::Publish, |
| 36 | Capability::Undo, |
| 37 | ]), |
| 38 | paths: PathScope::whole_repository(), |
| 39 | references: ReferenceScope::from_kinds(&[ |
| 40 | ReferenceKind::OwnDrafts, |
| 41 | ReferenceKind::CanonicalViaPromotionQueue, |
| 42 | ]), |
| 43 | changes: ChangeScope::any(), |
| 44 | quotas: ChainQuotas { |
| 45 | max_ops_per_window: 10_000_000, |
| 46 | window_duration_ms: 60_000, |
| 47 | storage_bytes: 1 << 40, |
| 48 | footprint_paths: 1 << 30, |
| 49 | max_bytes_per_op: 64 << 20, |
| 50 | }, |
| 51 | issued_at_ms: 0, |
| 52 | expires_at_ms: FIXTURE_EXPIRES_AT_MS, |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// A repository authority, an agent, and a granted chain from the authority to the agent. |
| 57 | pub struct ChainFixture { |
| 58 | pub authority: SigningKey, |
| 59 | pub agent: SigningKey, |
| 60 | pub chain: CapabilityChain, |
| 61 | /// Chain prefixes, shortest first, in grant order. |
| 62 | prefixes: Vec<CapabilityChain>, |
| 63 | } |
| 64 | |
| 65 | impl ChainFixture { |
| 66 | /// A chain of `depth` links (1 to 3): authority, then intermediate keys, then the agent. |
| 67 | /// `paths` narrows the leaf link's path scope (`None`: whole repository). |
| 68 | pub fn new(depth: usize, paths: Option<Vec<String>>) -> Self { |
| 69 | assert!((1..=3).contains(&depth), "fixture depth 1..=3"); |
| 70 | let authority = SigningKey::from_bytes(&[0x11; 32]); |
| 71 | let mids = [ |
| 72 | SigningKey::from_bytes(&[0x22; 32]), |
| 73 | SigningKey::from_bytes(&[0x33; 32]), |
| 74 | ]; |
| 75 | let agent = SigningKey::from_bytes(&[0x44; 32]); |
| 76 | let mut signer = authority.clone(); |
| 77 | let mut parent = ROOT_PARENT; |
| 78 | let mut links = Vec::new(); |
| 79 | let mut prefixes = Vec::new(); |
| 80 | let audiences: Vec<SigningKey> = mids[..depth - 1] |
| 81 | .iter() |
| 82 | .cloned() |
| 83 | .chain([agent.clone()]) |
| 84 | .collect(); |
| 85 | for (i, audience) in audiences.into_iter().enumerate() { |
| 86 | let mut caveats = wide_caveats(); |
| 87 | if i + 1 == depth { |
| 88 | if let Some(p) = &paths { |
| 89 | caveats.paths = PathScope::new(p.clone()).expect("valid fixture path scope"); |
| 90 | } |
| 91 | } |
| 92 | let link = CapabilityLink::issue( |
| 93 | &signer, |
| 94 | parent, |
| 95 | [0xA0 + i as u8; 32], |
| 96 | repo(), |
| 97 | audience.verifying_key().to_bytes(), |
| 98 | caveats, |
| 99 | ); |
| 100 | parent = link.digest(); |
| 101 | links.push(link); |
| 102 | prefixes.push(CapabilityChain::new(links.clone())); |
| 103 | signer = audience; |
| 104 | } |
| 105 | Self { |
| 106 | authority, |
| 107 | agent, |
| 108 | chain: CapabilityChain::new(links), |
| 109 | prefixes, |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub fn agent_did(&self) -> String { |
| 114 | encode_did_key_ed25519(&self.agent.verifying_key().to_bytes()) |
| 115 | } |
| 116 | |
| 117 | /// An enforcer that trusts the authority and has granted every link at `WalSeq(0)`. |
| 118 | pub fn enforcer(&self) -> PolicyEnforcer { |
| 119 | let mut e = PolicyEnforcer::new(); |
| 120 | e.register_repo_authority( |
| 121 | repo(), |
| 122 | encode_did_key_ed25519(&self.authority.verifying_key().to_bytes()), |
| 123 | ); |
| 124 | for c in &self.prefixes { |
| 125 | e.grant_link(c, WalSeq(0), 1).expect("fixture link grants"); |
| 126 | } |
| 127 | e |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /// A signed envelope by `agent` upserting `files` and deleting `deletes`, plus its blobs. |
| 132 | /// Paths are sorted, as the envelope requires. |
| 133 | pub fn envelope( |
| 134 | agent: &SigningKey, |
| 135 | label: &str, |
| 136 | files: &[(&str, Vec<u8>)], |
| 137 | deletes: &[&str], |
| 138 | created_at_ms: u64, |
| 139 | ) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) { |
| 140 | let mut mutations = Vec::new(); |
| 141 | let mut blobs = Vec::new(); |
| 142 | for (path, bytes) in files { |
| 143 | let d = BlobDigest::compute(bytes); |
| 144 | mutations.push(PathMutation { |
| 145 | path: (*path).to_string(), |
| 146 | op: MutationOp::Upsert { |
| 147 | mode: FileMode::Regular644, |
| 148 | blob_digest: d, |
| 149 | size_bytes: bytes.len() as u64, |
| 150 | }, |
| 151 | }); |
| 152 | blobs.push((d, bytes.clone())); |
| 153 | } |
| 154 | for path in deletes { |
| 155 | mutations.push(PathMutation { |
| 156 | path: (*path).to_string(), |
| 157 | op: MutationOp::Delete, |
| 158 | }); |
| 159 | } |
| 160 | mutations.sort_by(|a, b| a.path.cmp(&b.path)); |
| 161 | let mut env = ChangesetEnvelope { |
| 162 | version: SYNAPSE_ENVELOPE_VERSION, |
| 163 | repo_id: repo(), |
| 164 | base_git_oid: GitOid([0x5A; 20]), |
| 165 | parent_changesets: Vec::new(), |
| 166 | author_did: encode_did_key_ed25519(&agent.verifying_key().to_bytes()), |
| 167 | idempotency_key: IdempotencyKey::from_label(label), |
| 168 | created_at_ms, |
| 169 | intent_summary: format!("G1 fixture change {label}"), |
| 170 | mutations, |
| 171 | evidence_receipts: Vec::new(), |
| 172 | signature: Vec::new(), |
| 173 | }; |
| 174 | env.sign(agent); |
| 175 | (env, blobs) |
| 176 | } |
| 177 | |
| 178 | fn digest(n: u8) -> BlobDigest { |
| 179 | let mut d = [n; 32]; |
| 180 | d[0] = n; |
| 181 | BlobDigest(d) |
| 182 | } |
| 183 | |
| 184 | /// At least one valid frame of every kind, with edge cases (empty lists, empty chunk, |
| 185 | /// depth 1 and depth 3 chains, an envelope with evidence and a delete, every option tag). |
| 186 | pub fn sample_frames() -> Vec<Frame> { |
| 187 | let deep = ChainFixture::new(3, None); |
| 188 | let shallow = ChainFixture::new(1, None); |
| 189 | let (env, _) = envelope( |
| 190 | &deep.agent, |
| 191 | "sample", |
| 192 | &[("crates/a.rs", b"fn a() {}\n".to_vec())], |
| 193 | &["docs/old.md"], |
| 194 | 7, |
| 195 | ); |
| 196 | let mut env_evidence = env.clone(); |
| 197 | env_evidence.evidence_receipts.push(EvidenceAttachment { |
| 198 | gate_name: "unit".into(), |
| 199 | passed: true, |
| 200 | artifact_digest: [9u8; 32], |
| 201 | summary: "ok".into(), |
| 202 | }); |
| 203 | env_evidence.sign(&deep.agent); |
| 204 | let req = submit_request(&deep.agent, deep.chain.clone(), &env, [1u8; 32], 7).expect("req"); |
| 205 | let mut req_scoped = |
| 206 | submit_request(&deep.agent, deep.chain.clone(), &env_evidence, [2u8; 32], 8).expect("req"); |
| 207 | req_scoped.scope.reference = Some(ReferenceKind::OwnDrafts); |
| 208 | req_scoped.scope.join_change = Some(synapse_core::ChangeId([3u8; 16])); |
| 209 | let (env1, _) = envelope(&shallow.agent, "shallow", &[], &["x"], 9); |
| 210 | let mut req_shallow = |
| 211 | submit_request(&shallow.agent, shallow.chain.clone(), &env1, [4u8; 32], 9).expect("req"); |
| 212 | req_shallow.scope.reference = Some(ReferenceKind::CanonicalViaPromotionQueue); |
| 213 | let bodies = vec![ |
| 214 | FrameBody::Hello(Hello { |
| 215 | max_frame_body: 4096, |
| 216 | max_pending_chunk_bytes: 1 << 20, |
| 217 | }), |
| 218 | FrameBody::Have(Have { |
| 219 | repo_id: repo(), |
| 220 | digests: vec![], |
| 221 | }), |
| 222 | FrameBody::Have(Have { |
| 223 | repo_id: repo(), |
| 224 | digests: vec![digest(1), digest(2), digest(3)], |
| 225 | }), |
| 226 | FrameBody::Want(Want { digests: vec![] }), |
| 227 | FrameBody::Want(Want { |
| 228 | digests: vec![digest(2)], |
| 229 | }), |
| 230 | FrameBody::Chunk(Chunk { |
| 231 | digest: BlobDigest::compute(b""), |
| 232 | bytes: vec![], |
| 233 | }), |
| 234 | FrameBody::Chunk(Chunk { |
| 235 | digest: BlobDigest::compute(b"fn a() {}\n"), |
| 236 | bytes: b"fn a() {}\n".to_vec(), |
| 237 | }), |
| 238 | FrameBody::Submit(Box::new(req)), |
| 239 | FrameBody::Submit(Box::new(req_scoped)), |
| 240 | FrameBody::Submit(Box::new(req_shallow)), |
| 241 | FrameBody::Accepted(Accepted { |
| 242 | wal_seq: WalSeq(42), |
| 243 | changeset_id: ChangesetId([6u8; 32]), |
| 244 | duplicate: false, |
| 245 | }), |
| 246 | FrameBody::Accepted(Accepted { |
| 247 | wal_seq: WalSeq(u64::MAX), |
| 248 | changeset_id: ChangesetId([0u8; 32]), |
| 249 | duplicate: true, |
| 250 | }), |
| 251 | FrameBody::Refused(Refused { |
| 252 | code: RefusalCode::WireProtocolViolation, |
| 253 | message: "Submit before wanted chunk".into(), |
| 254 | }), |
| 255 | FrameBody::Refused(Refused { |
| 256 | code: RefusalCode::AuthChainBroken, |
| 257 | message: String::new(), |
| 258 | }), |
| 259 | ]; |
| 260 | bodies |
| 261 | .into_iter() |
| 262 | .enumerate() |
| 263 | .map(|(i, body)| Frame { |
| 264 | request_id: i as u32 * 7919, |
| 265 | body, |
| 266 | }) |
| 267 | .collect() |
| 268 | } |
| 269 | |
| 270 | /// A fresh empty directory under the system temp directory. |
| 271 | pub fn temp_dir(label: &str) -> std::path::PathBuf { |
| 272 | let dir = std::env::temp_dir().join(format!( |
| 273 | "synapse-wire-{label}-{}-{}", |
| 274 | std::process::id(), |
| 275 | std::time::SystemTime::now() |
| 276 | .duration_since(std::time::UNIX_EPOCH) |
| 277 | .map(|d| d.as_nanos()) |
| 278 | .unwrap_or(0) |
| 279 | )); |
| 280 | let _ = std::fs::remove_dir_all(&dir); |
| 281 | std::fs::create_dir_all(&dir).expect("create temp dir"); |
| 282 | dir |
| 283 | } |
| 284 | |
| 285 | /// A shared group-commit store (default group-commit policy, strict recovery). |
| 286 | pub fn open_store(dir: &std::path::Path) -> std::sync::Arc<synapse_store::SharedStore> { |
| 287 | std::sync::Arc::new( |
| 288 | synapse_store::SharedStore::open( |
| 289 | dir, |
| 290 | synapse_store::FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 291 | synapse_store::RecoveryPolicy::StrictFailClosed, |
| 292 | synapse_store::StoreLimits::default(), |
| 293 | ) |
| 294 | .expect("open shared store"), |
| 295 | ) |
| 296 | } |
| 297 | |
| 298 | /// Server time used by fixture servers (milliseconds). |
| 299 | pub const FIXTURE_NOW_MS: u64 = 1_000_000; |
| 300 | |
| 301 | /// A wire server for [`REPO`] over `store`, trusting `fx`'s authority, with a fixed clock. |
| 302 | pub fn server( |
| 303 | fx: &ChainFixture, |
| 304 | store: std::sync::Arc<synapse_store::SharedStore>, |
| 305 | ) -> crate::WireServer { |
| 306 | crate::WireServer::new( |
| 307 | crate::ServerConfig { |
| 308 | repo_id: repo(), |
| 309 | read_limits: crate::WireLimits::default(), |
| 310 | max_pending_chunk_bytes: crate::session::DEFAULT_MAX_PENDING_CHUNK_BYTES, |
| 311 | }, |
| 312 | store, |
| 313 | fx.enforcer(), |
| 314 | std::sync::Arc::new(|| FIXTURE_NOW_MS), |
| 315 | ) |
| 316 | .expect("wire server") |
| 317 | } |