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-wire/src/session.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-wire / src / session.rs` 623 lines ยท 22029 bytes Raw Blame History 1 //! Have-want chunk negotiation and change submission over wire frames. 2 //! 3 //! One change crosses the transport in two round trips: 4 //! 5 //! ```text 6 //! client server 7 //! Hello -------------------------------> (once per connection, both ways) 8 //! <------------------------------- Hello 9 //! Have {repo, digests the change needs} -> 10 //! <---------- Want {the offered digests the server lacks} 11 //! Chunk * |Want|, Submit {chained request} -> (one write) 12 //! <--------------- Accepted {wal_seq} | Refused {code} 13 //! ``` 14 //! 15 //! The server lacks a digest when no committed changeset references it and no chunk of the 16 //! current negotiation carried it, so a chunk the server already holds is never resent 17 //! (FindMissingBlobs style, ADR 0003 section 5.9). Until G2 a chunk is a whole blob. 18 //! 19 //! Server rules (each break is a typed refusal, and the negotiation is reset): 20 //! * `Hello` first, once (`WireProtocolViolation`). 21 //! * One `Have` per negotiation, for the server's repository (`AuthCrossRepoDenied`). 22 //! * A `Chunk` must be wanted and not yet received (`WireProtocolViolation`), match its 23 //! digest (`BlobDigestMismatch`), and fit the pending-bytes cap (`QuotaPayloadTooLarge`). 24 //! * A `Submit` must come after every wanted chunk (`WireProtocolViolation`); its payload 25 //! must be one canonical binary envelope (`WireFrameMalformed`); its capability chain is 26 //! checked by `PolicyEnforcer::authorize_chain` (step F1) with `Capability::Propose`; the 27 //! envelope must be for this repository and authored by the leaf audience, and the request 28 //! scope must list exactly the envelope's paths; then the store admits it with group commit 29 //! and the reply is sent only after the change is durable. 30 //! * A frame the server never accepts from a client (`Want`, `Accepted`, `Refused`) is a 31 //! `WireProtocolViolation`. A malformed frame is refused with `WireFrameMalformed` and the 32 //! connection is closed, since framing can no longer be trusted. 33 34 use crate::frame::{Accepted, Chunk, Frame, FrameBody, Have, Hello, Refused, Want, WireLimits}; 35 use crate::transport::FrameConn; 36 use `ed25519`_dalek::SigningKey; 37 use std::collections::{BTreeMap, BTreeSet}; 38 use std::io::{Read, Write}; 39 use std::sync::{Arc, Mutex}; 40 use synapse_auth::{ 41 BoundaryKind, Capability, CapabilityChain, ChainedRequest, PolicyEnforcer, RequestScope, 42 }; 43 use synapse_core::{ 44 BlobDigest, ChangesetEnvelope, MutationOp, RefusalCode, RepoId, SynapseError, SynapseResult, 45 WalSeq, 46 }; 47 use synapse_store::codec::{decode_envelope, encode_envelope}; 48 use synapse_store::{IngestOutcome, SharedStore}; 49 50 /// Default cap on chunk bytes buffered for one negotiation (64 MiB). 51 pub const DEFAULT_MAX_PENDING_CHUNK_BYTES: u64 = 64 << 20; 52 /// Refusals close a connection before one peer can consume the shared audit capacity. 53 const MAX_SESSION_REFUSALS: u32 = 64; 54 55 fn violation(msg: impl Into) -> SynapseError { 56 SynapseError::new(RefusalCode::WireProtocolViolation, msg) 57 } 58 59 /// Build the chained `Propose` request that carries `envelope` over the wire: payload is the 60 /// binary envelope, scope paths are exactly the envelope's mutation paths. 61 pub fn submit_request( 62 agent_key: &SigningKey, 63 chain: CapabilityChain, 64 envelope: &ChangesetEnvelope, 65 request_nonce: [u8; 32], 66 timestamp_ms: u64, 67 ) -> SynapseResult { 68 Ok(ChainedRequest::sign_new( 69 agent_key, 70 chain, 71 envelope.repo_id.clone(), 72 Capability::Propose, 73 RequestScope { 74 paths: envelope.mutations.iter().map(|m| m.path.clone()).collect(), 75 reference: None, 76 join_change: None, 77 }, 78 request_nonce, 79 timestamp_ms, 80 encode_envelope(envelope)?, 81 )) 82 } 83 84 /// Digests of the blobs an envelope's upserts reference. 85 fn upsert_digests(envelope: &ChangesetEnvelope) -> impl Iterator + '_ { 86 envelope.mutations.iter().filter_map(|m| match &m.op { 87 MutationOp::Upsert { blob_digest, .. } => Some(*blob_digest), 88 MutationOp::Delete => None, 89 }) 90 } 91 92 /// Server configuration. 93 #[derive(Debug, Clone)] 94 pub struct ServerConfig { 95 pub repo_id: RepoId, 96 /// Limits for frames the server reads (announced in its `Hello`). 97 pub read_limits: WireLimits, 98 pub max_pending_chunk_bytes: u64, 99 } 100 101 /// A wire server for one repository over a shared group-commit store. 102 #[derive(Clone)] 103 pub struct WireServer { 104 cfg: ServerConfig, 105 store: Arc, 106 auth: Arc>, 107 known: Arc>>, 108 clock: Arc u64 + Send + Sync>, 109 } 110 111 fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { 112 m.lock().unwrap_or_else(|p| p.into_inner()) 113 } 114 115 impl WireServer { 116 /// Serve `store` with `auth` (holding the repository authority and granted links). 117 /// `clock` returns the server time in milliseconds. 118 pub fn new( 119 cfg: ServerConfig, 120 store: Arc, 121 auth: PolicyEnforcer, 122 clock: Arc u64 + Send + Sync>, 123 ) -> SynapseResult { 124 let mut known = BTreeSet::new(); 125 for cs in store.read().list_changesets(None, None, None)? { 126 known.extend(upsert_digests(&cs.envelope)); 127 } 128 Ok(Self { 129 cfg, 130 store, 131 auth: Arc::new(Mutex::new(auth)), 132 known: Arc::new(Mutex::new(known)), 133 clock, 134 }) 135 } 136 137 pub fn config(&self) -> &ServerConfig { 138 &self.cfg 139 } 140 141 pub fn store(&self) -> &Arc { 142 &self.store 143 } 144 145 /// Whether a committed changeset references `digest`. 146 pub fn knows(&self, digest: &BlobDigest) -> bool { 147 lock(&self.known).contains(digest) 148 } 149 150 /// A new per-connection session. 151 pub fn session(&self) -> Session<'_> { 152 Session { 153 server: self, 154 hello_done: false, 155 refusals: 0, 156 neg: Negotiation::default(), 157 } 158 } 159 160 /// Serve one connection until the peer closes it or sends a malformed frame. 161 pub fn serve(&self, stream: S) -> SynapseResult { 162 let mut conn = FrameConn::new(stream, self.cfg.read_limits); 163 let mut session = self.session(); 164 loop { 165 match conn.recv() { 166 Ok(None) => break, 167 Ok(Some(frame)) => { 168 if let (false, FrameBody::Hello(h)) = (session.hello_done, &frame.body) { 169 conn.peer_limits = WireLimits { 170 max_frame_body: h.max_frame_body, 171 }; 172 } 173 let reply = session.handle(frame); 174 for f in &reply.frames { 175 // A reply the peer's own cap refuses cannot be sent: close. 176 if conn.queue(f).is_err() { 177 conn.flush()?; 178 return Ok(conn_stats(&conn)); 179 } 180 } 181 conn.flush()?; 182 if reply.close { 183 break; 184 } 185 } 186 Err(e) if e.code == RefusalCode::WireFrameMalformed => { 187 conn.send(&Frame { 188 request_id: 0, 189 body: FrameBody::Refused(Refused { 190 code: e.code, 191 message: e.message, 192 }), 193 })?; 194 break; 195 } 196 Err(e) => return Err(e), 197 } 198 } 199 Ok(conn_stats(&conn)) 200 } 201 } 202 203 fn conn_stats(conn: &FrameConn) -> FrameConnStats { 204 FrameConnStats { 205 bytes_sent: conn.bytes_sent, 206 bytes_received: conn.bytes_received, 207 frames_sent: conn.frames_sent, 208 frames_received: conn.frames_received, 209 } 210 } 211 212 /// Byte and frame counts of one served connection. 213 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] 214 pub struct FrameConnStats { 215 pub bytes_sent: u64, 216 pub bytes_received: u64, 217 pub frames_sent: u64, 218 pub frames_received: u64, 219 } 220 221 #[derive(Debug, Default)] 222 struct Negotiation { 223 active: bool, 224 wanted: BTreeSet, 225 received: BTreeMap>, 226 pending_bytes: u64, 227 } 228 229 /// Frames to send back, and whether to close the connection after them. 230 #[derive(Debug, Default)] 231 pub struct Reply { 232 pub frames: Vec, 233 pub close: bool, 234 } 235 236 /// Server state of one connection. 237 pub struct Session<'a> { 238 server: &'a WireServer, 239 hello_done: bool, 240 refusals: u32, 241 neg: Negotiation, 242 } 243 244 impl Session<'_> { 245 fn refuse(&mut self, request_id: u32, e: SynapseError) -> Reply { 246 self.neg = Negotiation::default(); 247 self.refusals += 1; 248 let close = self.refusals >= MAX_SESSION_REFUSALS 249 || e.code == RefusalCode::BackpressureOverCapacity; 250 Reply { 251 frames: vec![Frame { 252 request_id, 253 body: FrameBody::Refused(Refused { 254 code: e.code, 255 message: e.message, 256 }), 257 }], 258 close, 259 } 260 } 261 262 /// Handle one well-formed frame from the client. 263 pub fn handle(&mut self, frame: Frame) -> Reply { 264 let id = frame.request_id; 265 let reply_body = match (self.hello_done, frame.body) { 266 (false, FrameBody::Hello(_)) => { 267 self.hello_done = true; 268 Ok(Some(FrameBody::Hello(Hello { 269 max_frame_body: self.server.cfg.read_limits.max_frame_body, 270 max_pending_chunk_bytes: self.server.cfg.max_pending_chunk_bytes, 271 }))) 272 } 273 (false, other) => { 274 let mut r = self.refuse( 275 id, 276 violation(format!( 277 "{} before Hello: Hello must be the first frame", 278 other.kind().name() 279 )), 280 ); 281 r.close = true; 282 return r; 283 } 284 (true, FrameBody::Hello(_)) => Err(violation("second Hello on one connection")), 285 (true, FrameBody::Have(h)) => self.have(h).map(|w| Some(FrameBody::Want(w))), 286 (true, FrameBody::Chunk(c)) => self.chunk(c).map(|()| None), 287 (true, FrameBody::Submit(req)) => self.submit(*req).map(|a| { 288 self.neg = Negotiation::default(); 289 Some(FrameBody::Accepted(a)) 290 }), 291 ( 292 true, 293 other @ (FrameBody::Want(_) | FrameBody::Accepted(_) | FrameBody::Refused(_)), 294 ) => Err(violation(format!( 295 "a server never accepts {} from a client", 296 other.kind().name() 297 ))), 298 }; 299 match reply_body { 300 Ok(Some(body)) => Reply { 301 frames: vec![Frame { 302 request_id: id, 303 body, 304 }], 305 close: false, 306 }, 307 Ok(None) => Reply::default(), 308 Err(e) => self.refuse(id, e), 309 } 310 } 311 312 fn have(&mut self, h: Have) -> SynapseResult { 313 if self.neg.active { 314 return Err(violation("Have while a negotiation is open (Submit first)")); 315 } 316 if h.repo_id != self.server.cfg.repo_id { 317 return Err(SynapseError::new( 318 RefusalCode::AuthCrossRepoDenied, 319 format!( 320 "Have for {} on a server for {}", 321 h.repo_id, self.server.cfg.repo_id 322 ), 323 )); 324 } 325 let known = lock(&self.server.known); 326 let wanted: Vec = h 327 .digests 328 .iter() 329 .filter(|d| !known.contains(d)) 330 .copied() 331 .collect(); 332 drop(known); 333 self.neg = Negotiation { 334 active: true, 335 wanted: wanted.iter().copied().collect(), 336 received: BTreeMap::new(), 337 pending_bytes: 0, 338 }; 339 Ok(Want { digests: wanted }) 340 } 341 342 fn chunk(&mut self, c: Chunk) -> SynapseResult<()> { 343 if !self.neg.wanted.contains(&c.digest) { 344 return Err(violation(format!( 345 "unsolicited chunk {} (not in the last Want)", 346 c.digest 347 ))); 348 } 349 if self.neg.received.contains_key(&c.digest) { 350 return Err(violation(format!("chunk {} sent twice", c.digest))); 351 } 352 let computed = BlobDigest::compute(&c.bytes); 353 if computed != c.digest { 354 return Err(SynapseError::new( 355 RefusalCode::BlobDigestMismatch, 356 format!( 357 "chunk declared {} but its bytes hash to {computed}", 358 c.digest 359 ), 360 )); 361 } 362 let pending = self.neg.pending_bytes + c.bytes.len() as u64; 363 if pending > self.server.cfg.max_pending_chunk_bytes { 364 return Err(SynapseError::new( 365 RefusalCode::QuotaPayloadTooLarge, 366 format!( 367 "pending chunk bytes {pending} exceed max_pending_chunk_bytes {}", 368 self.server.cfg.max_pending_chunk_bytes 369 ), 370 )); 371 } 372 self.neg.pending_bytes = pending; 373 self.neg.received.insert(c.digest, c.bytes); 374 Ok(()) 375 } 376 377 fn submit(&mut self, req: ChainedRequest) -> SynapseResult { 378 // Before envelope decoding or signature verification, refuse if the shared audit 379 // cannot retain the next decision. The enforcer rechecks under its mutex at admission. 380 lock(&self.server.auth).audit_log().ensure_capacity()?; 381 let srv = self.server; 382 if let Some(missing) = self 383 .neg 384 .wanted 385 .iter() 386 .find(|d| !self.neg.received.contains_key(d)) 387 { 388 return Err(violation(format!( 389 "Submit before wanted chunk {missing} arrived" 390 ))); 391 } 392 let envelope = decode_envelope(&req.payload, u64::from(srv.cfg.read_limits.max_frame_body)) 393 .map_err(|r| { 394 r.into_error(RefusalCode::WireFrameMalformed, "Submit payload envelope") 395 })?; 396 let now_ms = (srv.clock)(); 397 let request_seq = WalSeq(srv.store.read().committed_seq().0 + 1); 398 lock(&srv.auth).authorize_chain( 399 BoundaryKind::Api, 400 "wire_submit", 401 &srv.cfg.repo_id, 402 Capability::Propose, 403 &req, 404 request_seq, 405 now_ms, 406 )?; 407 if envelope.repo_id != srv.cfg.repo_id { 408 return Err(SynapseError::new( 409 RefusalCode::AuthCrossRepoDenied, 410 "envelope repo_id does not match the server's repository", 411 )); 412 } 413 if envelope.author_did != req.agent_did() { 414 return Err(SynapseError::new( 415 RefusalCode::AuthSignatureInvalid, 416 "envelope author_did is not the chain's leaf audience", 417 )); 418 } 419 if req.scope.paths.len() != envelope.mutations.len() 420 || req 421 .scope 422 .paths 423 .iter() 424 .zip(&envelope.mutations) 425 .any(|(p, m)| p != &m.path) 426 { 427 return Err(SynapseError::new( 428 RefusalCode::AuthPathOutOfScope, 429 "request scope must list exactly the envelope's mutation paths", 430 )); 431 } 432 let blobs: Vec<(BlobDigest, Vec)> = 433 std::mem::take(&mut self.neg.received).into_iter().collect(); 434 let digests: Vec = upsert_digests(&envelope).collect(); 435 let outcome = srv.store.submit(envelope, &blobs)?; 436 lock(&srv.known).extend(digests); 437 Ok(match outcome { 438 IngestOutcome::Committed { 439 wal_seq, 440 changeset_id, 441 .. 442 } => Accepted { 443 wal_seq, 444 changeset_id, 445 duplicate: false, 446 }, 447 IngestOutcome::IdempotentDuplicate { 448 wal_seq, 449 changeset_id, 450 } => Accepted { 451 wal_seq, 452 changeset_id, 453 duplicate: true, 454 }, 455 }) 456 } 457 } 458 459 /// What one submission cost on the wire. 460 #[derive(Debug, Clone, PartialEq, Eq)] 461 pub struct SubmitReport { 462 pub accepted: Accepted, 463 /// Digests offered in the `Have` (0 when the change carries no blobs). 464 pub offered: usize, 465 /// Digests the server wanted, so chunks sent. 466 pub wanted: usize, 467 pub chunk_bytes_sent: u64, 468 /// Frame bytes written and read for this submission. 469 pub wire_bytes_sent: u64, 470 pub wire_bytes_received: u64, 471 } 472 473 /// Client side of a wire connection. 474 pub struct WireClient { 475 conn: FrameConn, 476 next_id: u32, 477 pub server_hello: Hello, 478 } 479 480 impl WireClient { 481 /// Exchange `Hello` frames. `read_limits` caps frames this client reads. 482 pub fn connect(stream: S, read_limits: WireLimits) -> SynapseResult { 483 let mut conn = FrameConn::new(stream, read_limits); 484 conn.send(&Frame { 485 request_id: 1, 486 body: FrameBody::Hello(Hello { 487 max_frame_body: read_limits.max_frame_body, 488 max_pending_chunk_bytes: 0, 489 }), 490 })?; 491 let server_hello = match Self::expect(&mut conn)? { 492 FrameBody::Hello(h) => h, 493 other => { 494 return Err(violation(format!( 495 "server answered Hello with {}", 496 other.kind().name() 497 ))) 498 } 499 }; 500 conn.peer_limits = WireLimits { 501 max_frame_body: server_hello.max_frame_body, 502 }; 503 Ok(Self { 504 conn, 505 next_id: 2, 506 server_hello, 507 }) 508 } 509 510 fn expect(conn: &mut FrameConn) -> SynapseResult { 511 match conn.recv()? { 512 None => Err(SynapseError::new( 513 RefusalCode::IoFailure, 514 "server closed the connection", 515 )), 516 Some(Frame { 517 body: FrameBody::Refused(r), 518 .. 519 }) => Err(SynapseError::new(r.code, r.message)), 520 Some(f) => Ok(f.body), 521 } 522 } 523 524 fn id(&mut self) -> u32 { 525 let id = self.next_id; 526 self.next_id = self.next_id.wrapping_add(1); 527 id 528 } 529 530 /// Submit one change: negotiate which of `blobs` the server lacks, send only those, then 531 /// the request. Returns after the server's durable acknowledgement. 532 pub fn submit( 533 &mut self, 534 req: &ChainedRequest, 535 blobs: &[(BlobDigest, Vec)], 536 ) -> SynapseResult { 537 let (sent0, recv0) = (self.conn.bytes_sent, self.conn.bytes_received); 538 let mut by_digest: BTreeMap = BTreeMap::new(); 539 for (d, b) in blobs { 540 by_digest.insert(*d, b); 541 } 542 let offered = by_digest.len(); 543 let mut wanted = 0; 544 let mut chunk_bytes_sent = 0u64; 545 if offered > 0 { 546 let id = self.id(); 547 self.conn.send(&Frame { 548 request_id: id, 549 body: FrameBody::Have(Have { 550 repo_id: req.target_repo_id.clone(), 551 digests: by_digest.keys().copied().collect(), 552 }), 553 })?; 554 let want = match Self::expect(&mut self.conn)? { 555 FrameBody::Want(w) => w, 556 other => { 557 return Err(violation(format!( 558 "server answered Have with {}", 559 other.kind().name() 560 ))) 561 } 562 }; 563 wanted = want.digests.len(); 564 for d in &want.digests { 565 let Some(bytes) = by_digest.get(d) else { 566 return Err(violation(format!( 567 "server wanted {d}, which was not offered" 568 ))); 569 }; 570 let id = self.id(); 571 self.conn.queue(&Frame { 572 request_id: id, 573 body: FrameBody::Chunk(Chunk { 574 digest: *d, 575 bytes: bytes.to_vec(), 576 }), 577 })?; 578 chunk_bytes_sent += bytes.len() as u64; 579 } 580 } 581 let id = self.id(); 582 self.conn.queue(&Frame { 583 request_id: id, 584 body: FrameBody::Submit(Box::new(req.clone())), 585 })?; 586 self.conn.flush()?; 587 let accepted = match Self::expect(&mut self.conn)? { 588 FrameBody::Accepted(a) => a, 589 other => { 590 return Err(violation(format!( 591 "server answered Submit with {}", 592 other.kind().name() 593 ))) 594 } 595 }; 596 Ok(SubmitReport { 597 accepted, 598 offered, 599 wanted, 600 chunk_bytes_sent, 601 wire_bytes_sent: self.conn.bytes_sent - sent0, 602 wire_bytes_received: self.conn.bytes_received - recv0, 603 }) 604 } 605 606 /// Send raw frames and read one reply (tests of server refusals). 607 pub fn exchange(&mut self, frames: &[Frame]) -> SynapseResult> { 608 for f in frames { 609 self.conn.queue(f)?; 610 } 611 self.conn.flush()?; 612 self.conn.recv() 613 } 614 615 /// Bytes written and read so far, including the hello exchange. 616 pub fn bytes(&self) -> (u64, u64) { 617 (self.conn.bytes_sent, self.conn.bytes_received) 618 } 619 620 pub fn conn_mut(&mut self) -> &mut FrameConn { 621 &mut self.conn 622 } 623 }