synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-wire / src / frame.rs
| 1 | //! Binary wire frames (ADR 0003 section 9, step G1). |
| 2 | //! |
| 3 | //! Frame = 16-byte header, then `body_len` bytes of body. Little-endian, fixed width: |
| 4 | //! |
| 5 | //! | Bytes | Field | |
| 6 | //! | :--- | :--- | |
| 7 | //! | 0..4 | magic `SYNW` | |
| 8 | //! | 4 | version `1` | |
| 9 | //! | 5 | kind (1 hello, 2 have, 3 want, 4 chunk, 5 submit, 6 accepted, 7 refused) | |
| 10 | //! | 6 | flags `0` (any other value is refused) | |
| 11 | //! | 7 | reserved `0` (any other value is refused) | |
| 12 | //! | 8..12 | `request_id` u32 | |
| 13 | //! | 12..16 | `body_len` u32 | |
| 14 | //! |
| 15 | //! Body primitives follow the A1 codec (`synapse_store::codec`): `u8`, `u16`, `u32`, `u64` |
| 16 | //! little endian; byte strings and strings `u32 len | bytes` (strings UTF-8); sequences |
| 17 | //! `u32 count | items`; fixed arrays raw; option and enum tags one byte. There is exactly one |
| 18 | //! encoding per frame: any other tag, trailing byte, invalid UTF-8, invalid `RepoId`, |
| 19 | //! unsorted or repeated digest, or non-canonical capability chain is refused, so decode then |
| 20 | //! encode gives the input bytes back. |
| 21 | //! |
| 22 | //! Untrusted input: `body_len` is checked against the negotiated cap before anything is |
| 23 | //! allocated or read, and every inner length and count is checked against the cap and the |
| 24 | //! bytes left in the body. The body decoder only ever sees the body slice, so it cannot read |
| 25 | //! past the frame into the next one. |
| 26 | |
| 27 | use crate::probe::{NoProbe, Probe}; |
| 28 | use synapse_auth::{ |
| 29 | Capability, CapabilityChain, ChainedRequest, ReferenceKind, RequestScope, MAX_CHAIN_DEPTH, |
| 30 | }; |
| 31 | use synapse_core::{ |
| 32 | BlobDigest, ChangeId, ChangesetId, RefusalCode, RepoId, SynapseError, SynapseResult, WalSeq, |
| 33 | }; |
| 34 | |
| 35 | /// Frame magic. |
| 36 | pub const WIRE_MAGIC: [u8; 4] = *b"SYNW"; |
| 37 | /// Frame format version. |
| 38 | pub const WIRE_VERSION: u8 = 1; |
| 39 | /// Fixed header length. |
| 40 | pub const FRAME_HEADER_LEN: usize = 16; |
| 41 | /// Default cap on a frame's declared body length (16 MiB). |
| 42 | pub const DEFAULT_MAX_FRAME_BODY: u32 = 16 << 20; |
| 43 | /// Longest refusal code name carried by a `Refused` frame. |
| 44 | pub const MAX_REFUSAL_CODE_LEN: usize = 64; |
| 45 | |
| 46 | /// Limits a peer applies to frames it reads. |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 48 | pub struct WireLimits { |
| 49 | /// Largest declared body length accepted; larger declarations are refused before any |
| 50 | /// allocation or read. |
| 51 | pub max_frame_body: u32, |
| 52 | } |
| 53 | |
| 54 | impl Default for WireLimits { |
| 55 | fn default() -> Self { |
| 56 | Self { |
| 57 | max_frame_body: DEFAULT_MAX_FRAME_BODY, |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// Frame kind byte. |
| 63 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 64 | pub enum FrameKind { |
| 65 | Hello = 1, |
| 66 | Have = 2, |
| 67 | Want = 3, |
| 68 | Chunk = 4, |
| 69 | Submit = 5, |
| 70 | Accepted = 6, |
| 71 | Refused = 7, |
| 72 | } |
| 73 | |
| 74 | impl FrameKind { |
| 75 | /// Every kind, in kind-byte order. |
| 76 | pub const ALL: [FrameKind; 7] = [ |
| 77 | Self::Hello, |
| 78 | Self::Have, |
| 79 | Self::Want, |
| 80 | Self::Chunk, |
| 81 | Self::Submit, |
| 82 | Self::Accepted, |
| 83 | Self::Refused, |
| 84 | ]; |
| 85 | |
| 86 | pub fn byte(self) -> u8 { |
| 87 | self as u8 |
| 88 | } |
| 89 | |
| 90 | pub fn from_byte(b: u8) -> Option<Self> { |
| 91 | Self::ALL.get(usize::from(b).wrapping_sub(1)).copied() |
| 92 | } |
| 93 | |
| 94 | pub fn name(self) -> &'static str { |
| 95 | match self { |
| 96 | Self::Hello => "Hello", |
| 97 | Self::Have => "Have", |
| 98 | Self::Want => "Want", |
| 99 | Self::Chunk => "Chunk", |
| 100 | Self::Submit => "Submit", |
| 101 | Self::Accepted => "Accepted", |
| 102 | Self::Refused => "Refused", |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// Opening frame of each side: the limits it will apply to frames it reads. |
| 108 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 109 | pub struct Hello { |
| 110 | pub max_frame_body: u32, |
| 111 | /// Largest total of chunk bytes the receiver buffers for one negotiation. |
| 112 | pub max_pending_chunk_bytes: u64, |
| 113 | } |
| 114 | |
| 115 | /// Sender offers the chunks a change needs (strictly increasing digests). |
| 116 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 117 | pub struct Have { |
| 118 | pub repo_id: RepoId, |
| 119 | pub digests: Vec<BlobDigest>, |
| 120 | } |
| 121 | |
| 122 | /// Receiver asks for the offered chunks it lacks (strictly increasing digests). |
| 123 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 124 | pub struct Want { |
| 125 | pub digests: Vec<BlobDigest>, |
| 126 | } |
| 127 | |
| 128 | /// One chunk's content. Until G2 a chunk is a whole blob and its digest is the `BlobDigest`. |
| 129 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 130 | pub struct Chunk { |
| 131 | pub digest: BlobDigest, |
| 132 | pub bytes: Vec<u8>, |
| 133 | } |
| 134 | |
| 135 | /// The change is durable at `wal_seq` (or was already, for an idempotent duplicate). |
| 136 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 137 | pub struct Accepted { |
| 138 | pub wal_seq: WalSeq, |
| 139 | pub changeset_id: ChangesetId, |
| 140 | pub duplicate: bool, |
| 141 | } |
| 142 | |
| 143 | /// A typed refusal. |
| 144 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 145 | pub struct Refused { |
| 146 | pub code: RefusalCode, |
| 147 | pub message: String, |
| 148 | } |
| 149 | |
| 150 | /// A frame body by kind. |
| 151 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 152 | pub enum FrameBody { |
| 153 | Hello(Hello), |
| 154 | Have(Have), |
| 155 | Want(Want), |
| 156 | Chunk(Chunk), |
| 157 | /// A capability-chained request whose payload is one `synapse_store::codec` |
| 158 | /// binary envelope. |
| 159 | Submit(Box<ChainedRequest>), |
| 160 | Accepted(Accepted), |
| 161 | Refused(Refused), |
| 162 | } |
| 163 | |
| 164 | impl FrameBody { |
| 165 | pub fn kind(&self) -> FrameKind { |
| 166 | match self { |
| 167 | Self::Hello(_) => FrameKind::Hello, |
| 168 | Self::Have(_) => FrameKind::Have, |
| 169 | Self::Want(_) => FrameKind::Want, |
| 170 | Self::Chunk(_) => FrameKind::Chunk, |
| 171 | Self::Submit(_) => FrameKind::Submit, |
| 172 | Self::Accepted(_) => FrameKind::Accepted, |
| 173 | Self::Refused(_) => FrameKind::Refused, |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// One frame. |
| 179 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 180 | pub struct Frame { |
| 181 | pub request_id: u32, |
| 182 | pub body: FrameBody, |
| 183 | } |
| 184 | |
| 185 | /// Parsed and checked header. |
| 186 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 187 | pub struct FrameHeader { |
| 188 | pub kind: FrameKind, |
| 189 | pub request_id: u32, |
| 190 | pub body_len: u32, |
| 191 | } |
| 192 | |
| 193 | impl FrameHeader { |
| 194 | /// Header plus body length. |
| 195 | pub fn frame_len(&self) -> usize { |
| 196 | FRAME_HEADER_LEN + self.body_len as usize |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// Typed refusal from the frame decoder. `at` is the absolute byte offset in the frame. |
| 201 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 202 | pub enum WireRefusal { |
| 203 | /// The input ends before a field: `need` more bytes were required. |
| 204 | Truncated { at: usize, need: usize }, |
| 205 | /// The first four bytes are not `SYNW`. |
| 206 | BadMagic { found: [u8; 4] }, |
| 207 | /// The version byte is not [`WIRE_VERSION`]. |
| 208 | VersionUnsupported { found: u8 }, |
| 209 | /// The flags byte is not zero. |
| 210 | FlagsNonZero { found: u8 }, |
| 211 | /// The reserved byte is not zero. |
| 212 | ReservedNonZero { found: u8 }, |
| 213 | /// The kind byte names no frame kind. |
| 214 | UnknownKind { found: u8 }, |
| 215 | /// A declared length or count needs more than the cap allows. |
| 216 | LengthOverCap { at: usize, declared: u64, cap: u64 }, |
| 217 | /// Bytes remain after the last field of the body. |
| 218 | TrailingBytes { at: usize, count: usize }, |
| 219 | /// A tag byte (capability, reference kind, option, bool) has no meaning. |
| 220 | UnknownTag { |
| 221 | at: usize, |
| 222 | field: &'static str, |
| 223 | tag: u8, |
| 224 | }, |
| 225 | /// A string is not UTF-8. |
| 226 | InvalidUtf8 { at: usize }, |
| 227 | /// A repository id fails `RepoId::new`. |
| 228 | InvalidRepoId { at: usize }, |
| 229 | /// A second encoding of the same value would exist (unsorted or repeated digests, |
| 230 | /// a capability chain that does not re-encode to its bytes). |
| 231 | NotCanonical { at: usize, field: &'static str }, |
| 232 | /// The embedded capability chain is refused by its own decoder. |
| 233 | Chain { at: usize, code: RefusalCode }, |
| 234 | /// A `Refused` frame names no known refusal code. |
| 235 | UnknownRefusalCode { at: usize }, |
| 236 | } |
| 237 | |
| 238 | impl WireRefusal { |
| 239 | /// Short stable name of the refusal kind. |
| 240 | pub fn kind(&self) -> &'static str { |
| 241 | match self { |
| 242 | Self::Truncated { .. } => "Truncated", |
| 243 | Self::BadMagic { .. } => "BadMagic", |
| 244 | Self::VersionUnsupported { .. } => "VersionUnsupported", |
| 245 | Self::FlagsNonZero { .. } => "FlagsNonZero", |
| 246 | Self::ReservedNonZero { .. } => "ReservedNonZero", |
| 247 | Self::UnknownKind { .. } => "UnknownKind", |
| 248 | Self::LengthOverCap { .. } => "LengthOverCap", |
| 249 | Self::TrailingBytes { .. } => "TrailingBytes", |
| 250 | Self::UnknownTag { .. } => "UnknownTag", |
| 251 | Self::InvalidUtf8 { .. } => "InvalidUtf8", |
| 252 | Self::InvalidRepoId { .. } => "InvalidRepoId", |
| 253 | Self::NotCanonical { .. } => "NotCanonical", |
| 254 | Self::Chain { .. } => "Chain", |
| 255 | Self::UnknownRefusalCode { .. } => "UnknownRefusalCode", |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | /// The refusal as a `SynapseError` with code `WireFrameMalformed`. |
| 260 | pub fn into_error(self) -> SynapseError { |
| 261 | SynapseError::new( |
| 262 | RefusalCode::WireFrameMalformed, |
| 263 | format!("wire frame: {} ({self:?})", self.kind()), |
| 264 | ) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | type Decoded<T> = Result<T, WireRefusal>; |
| 269 | |
| 270 | // --------------------------------------------------------------------------------------- |
| 271 | // Encoder |
| 272 | // --------------------------------------------------------------------------------------- |
| 273 | |
| 274 | fn too_large(what: &str) -> SynapseError { |
| 275 | SynapseError::new( |
| 276 | RefusalCode::QuotaPayloadTooLarge, |
| 277 | format!("{what} exceeds the 32-bit length field"), |
| 278 | ) |
| 279 | } |
| 280 | |
| 281 | struct Writer(Vec<u8>); |
| 282 | |
| 283 | impl Writer { |
| 284 | fn u8(&mut self, v: u8) { |
| 285 | self.0.push(v); |
| 286 | } |
| 287 | fn u32(&mut self, v: u32) { |
| 288 | self.0.extend_from_slice(&v.to_le_bytes()); |
| 289 | } |
| 290 | fn u64(&mut self, v: u64) { |
| 291 | self.0.extend_from_slice(&v.to_le_bytes()); |
| 292 | } |
| 293 | fn raw(&mut self, b: &[u8]) { |
| 294 | self.0.extend_from_slice(b); |
| 295 | } |
| 296 | fn len(&mut self, n: usize, what: &str) -> SynapseResult<()> { |
| 297 | self.u32(u32::try_from(n).map_err(|_| too_large(what))?); |
| 298 | Ok(()) |
| 299 | } |
| 300 | fn bytes(&mut self, b: &[u8], what: &str) -> SynapseResult<()> { |
| 301 | self.len(b.len(), what)?; |
| 302 | self.raw(b); |
| 303 | Ok(()) |
| 304 | } |
| 305 | fn str(&mut self, s: &str, what: &str) -> SynapseResult<()> { |
| 306 | self.bytes(s.as_bytes(), what) |
| 307 | } |
| 308 | fn digests(&mut self, d: &[BlobDigest]) -> SynapseResult<()> { |
| 309 | if d.windows(2).any(|w| w[0].0 >= w[1].0) { |
| 310 | return Err(SynapseError::new( |
| 311 | RefusalCode::WireFrameMalformed, |
| 312 | "digests must be strictly increasing", |
| 313 | )); |
| 314 | } |
| 315 | self.len(d.len(), "digest count")?; |
| 316 | d.iter().for_each(|x| self.raw(&x.0)); |
| 317 | Ok(()) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | fn refusal_code_name(code: RefusalCode) -> String { |
| 322 | format!("{code:?}") |
| 323 | } |
| 324 | |
| 325 | fn put_body(w: &mut Writer, body: &FrameBody) -> SynapseResult<()> { |
| 326 | match body { |
| 327 | FrameBody::Hello(h) => { |
| 328 | w.u32(h.max_frame_body); |
| 329 | w.u64(h.max_pending_chunk_bytes); |
| 330 | } |
| 331 | FrameBody::Have(h) => { |
| 332 | RepoId::new(h.repo_id.as_str())?; |
| 333 | w.str(h.repo_id.as_str(), "repository id")?; |
| 334 | w.digests(&h.digests)?; |
| 335 | } |
| 336 | FrameBody::Want(x) => w.digests(&x.digests)?, |
| 337 | FrameBody::Chunk(c) => { |
| 338 | w.raw(&c.digest.0); |
| 339 | w.bytes(&c.bytes, "chunk")?; |
| 340 | } |
| 341 | FrameBody::Submit(r) => { |
| 342 | let n = r.chain.links.len(); |
| 343 | if n == 0 || n > MAX_CHAIN_DEPTH { |
| 344 | return Err(SynapseError::new( |
| 345 | RefusalCode::AuthChainBroken, |
| 346 | format!("chain length {n} outside 1..={MAX_CHAIN_DEPTH}"), |
| 347 | )); |
| 348 | } |
| 349 | w.bytes(&r.chain.encode(), "capability chain")?; |
| 350 | RepoId::new(r.target_repo_id.as_str())?; |
| 351 | w.str(r.target_repo_id.as_str(), "repository id")?; |
| 352 | w.raw(&r.agent_key); |
| 353 | w.u8(r.required_capability.tag_byte()); |
| 354 | w.len(r.scope.paths.len(), "scope path count")?; |
| 355 | for p in &r.scope.paths { |
| 356 | w.str(p, "scope path")?; |
| 357 | } |
| 358 | w.u8(r.scope.reference.map_or(0, ReferenceKind::tag_byte)); |
| 359 | match r.scope.join_change { |
| 360 | None => w.u8(0), |
| 361 | Some(id) => { |
| 362 | w.u8(1); |
| 363 | w.raw(&id.0); |
| 364 | } |
| 365 | } |
| 366 | w.raw(&r.request_nonce); |
| 367 | w.u64(r.timestamp_ms); |
| 368 | w.bytes(&r.payload, "payload")?; |
| 369 | w.raw(&r.agent_signature); |
| 370 | } |
| 371 | FrameBody::Accepted(a) => { |
| 372 | w.u64(a.wal_seq.0); |
| 373 | w.raw(&a.changeset_id.0); |
| 374 | w.u8(u8::from(a.duplicate)); |
| 375 | } |
| 376 | FrameBody::Refused(r) => { |
| 377 | w.str(&refusal_code_name(r.code), "refusal code")?; |
| 378 | w.str(&r.message, "refusal message")?; |
| 379 | } |
| 380 | } |
| 381 | Ok(()) |
| 382 | } |
| 383 | |
| 384 | /// Encode one frame. Fails only when a field cannot be represented (a length above `u32`, |
| 385 | /// an invalid repository id, unsorted digests, an empty or over-deep chain). |
| 386 | pub fn encode_frame(frame: &Frame) -> SynapseResult<Vec<u8>> { |
| 387 | let mut w = Writer(Vec::with_capacity(64)); |
| 388 | w.raw(&WIRE_MAGIC); |
| 389 | w.u8(WIRE_VERSION); |
| 390 | w.u8(frame.body.kind().byte()); |
| 391 | w.u8(0); |
| 392 | w.u8(0); |
| 393 | w.u32(frame.request_id); |
| 394 | w.u32(0); |
| 395 | put_body(&mut w, &frame.body)?; |
| 396 | let body_len = w.0.len() - FRAME_HEADER_LEN; |
| 397 | let body_len = u32::try_from(body_len).map_err(|_| too_large("frame body"))?; |
| 398 | w.0[12..16].copy_from_slice(&body_len.to_le_bytes()); |
| 399 | Ok(w.0) |
| 400 | } |
| 401 | |
| 402 | /// Encode one frame and refuse it (`QuotaPayloadTooLarge`) when its body exceeds the |
| 403 | /// peer's `max_frame_body`, since the peer would refuse it anyway. |
| 404 | pub fn encode_frame_within(frame: &Frame, limits: &WireLimits) -> SynapseResult<Vec<u8>> { |
| 405 | let bytes = encode_frame(frame)?; |
| 406 | let body = bytes.len() - FRAME_HEADER_LEN; |
| 407 | if body as u64 > u64::from(limits.max_frame_body) { |
| 408 | return Err(SynapseError::new( |
| 409 | RefusalCode::QuotaPayloadTooLarge, |
| 410 | format!( |
| 411 | "{} frame body {body} exceeds the peer's max_frame_body {}", |
| 412 | frame.body.kind().name(), |
| 413 | limits.max_frame_body |
| 414 | ), |
| 415 | )); |
| 416 | } |
| 417 | Ok(bytes) |
| 418 | } |
| 419 | |
| 420 | // --------------------------------------------------------------------------------------- |
| 421 | // Decoder |
| 422 | // --------------------------------------------------------------------------------------- |
| 423 | |
| 424 | /// Record that the decoder reached this source line. |
| 425 | macro_rules! cov { |
| 426 | ($r:expr) => { |
| 427 | $r.probe.site(line!()) |
| 428 | }; |
| 429 | } |
| 430 | |
| 431 | struct Reader<'b, 'p, P: Probe> { |
| 432 | buf: &'b [u8], |
| 433 | pos: usize, |
| 434 | /// Absolute offset of `buf[0]` in the frame (for refusal offsets and the probe). |
| 435 | base: usize, |
| 436 | cap: u64, |
| 437 | probe: &'p mut P, |
| 438 | } |
| 439 | |
| 440 | impl<'b, P: Probe> Reader<'b, '_, P> { |
| 441 | fn at(&self) -> usize { |
| 442 | self.base + self.pos |
| 443 | } |
| 444 | |
| 445 | fn remaining(&self) -> usize { |
| 446 | self.buf.len() - self.pos |
| 447 | } |
| 448 | |
| 449 | fn take(&mut self, n: usize) -> Decoded<&'b [u8]> { |
| 450 | if n > self.remaining() { |
| 451 | cov!(self); |
| 452 | return Err(WireRefusal::Truncated { |
| 453 | at: self.at(), |
| 454 | need: n - self.remaining(), |
| 455 | }); |
| 456 | } |
| 457 | let s = &self.buf[self.pos..self.pos + n]; |
| 458 | self.pos += n; |
| 459 | let end = self.at(); |
| 460 | self.probe.touched(end); |
| 461 | Ok(s) |
| 462 | } |
| 463 | |
| 464 | fn array<const N: usize>(&mut self) -> Decoded<[u8; N]> { |
| 465 | let mut a = [0u8; N]; |
| 466 | a.copy_from_slice(self.take(N)?); |
| 467 | Ok(a) |
| 468 | } |
| 469 | |
| 470 | fn u8(&mut self) -> Decoded<u8> { |
| 471 | Ok(self.take(1)?[0]) |
| 472 | } |
| 473 | fn u32(&mut self) -> Decoded<u32> { |
| 474 | Ok(u32::from_le_bytes(self.array()?)) |
| 475 | } |
| 476 | fn u64(&mut self) -> Decoded<u64> { |
| 477 | Ok(u64::from_le_bytes(self.array()?)) |
| 478 | } |
| 479 | |
| 480 | /// A `u32` length of a byte run: checked against the cap, then the body. |
| 481 | fn byte_len(&mut self) -> Decoded<usize> { |
| 482 | let at = self.at(); |
| 483 | let n = self.u32()?; |
| 484 | if u64::from(n) > self.cap { |
| 485 | cov!(self); |
| 486 | return Err(WireRefusal::LengthOverCap { |
| 487 | at, |
| 488 | declared: u64::from(n), |
| 489 | cap: self.cap, |
| 490 | }); |
| 491 | } |
| 492 | let n = n as usize; |
| 493 | if n > self.remaining() { |
| 494 | cov!(self); |
| 495 | return Err(WireRefusal::Truncated { |
| 496 | at: self.at(), |
| 497 | need: n - self.remaining(), |
| 498 | }); |
| 499 | } |
| 500 | cov!(self); |
| 501 | Ok(n) |
| 502 | } |
| 503 | |
| 504 | fn bytes(&mut self) -> Decoded<Vec<u8>> { |
| 505 | let n = self.byte_len()?; |
| 506 | Ok(self.take(n)?.to_vec()) |
| 507 | } |
| 508 | |
| 509 | fn str(&mut self) -> Decoded<String> { |
| 510 | let at = self.at(); |
| 511 | let n = self.byte_len()?; |
| 512 | let raw = self.take(n)?; |
| 513 | match std::str::from_utf8(raw) { |
| 514 | Ok(s) => { |
| 515 | cov!(self); |
| 516 | Ok(s.to_owned()) |
| 517 | } |
| 518 | Err(_) => { |
| 519 | cov!(self); |
| 520 | Err(WireRefusal::InvalidUtf8 { at }) |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | /// A `u32` count of items at least `min_item` bytes each: checked against the cap and |
| 526 | /// the body before anything is reserved. |
| 527 | fn count(&mut self, min_item: usize) -> Decoded<usize> { |
| 528 | let at = self.at(); |
| 529 | let n = self.u32()?; |
| 530 | let need = u64::from(n) * min_item as u64; |
| 531 | if need > self.cap { |
| 532 | cov!(self); |
| 533 | return Err(WireRefusal::LengthOverCap { |
| 534 | at, |
| 535 | declared: need, |
| 536 | cap: self.cap, |
| 537 | }); |
| 538 | } |
| 539 | if need > self.remaining() as u64 { |
| 540 | cov!(self); |
| 541 | return Err(WireRefusal::Truncated { |
| 542 | at: self.at(), |
| 543 | need: need as usize - self.remaining(), |
| 544 | }); |
| 545 | } |
| 546 | cov!(self); |
| 547 | Ok(n as usize) |
| 548 | } |
| 549 | |
| 550 | fn repo(&mut self) -> Decoded<RepoId> { |
| 551 | let at = self.at(); |
| 552 | let s = self.str()?; |
| 553 | match RepoId::new(s) { |
| 554 | Ok(r) => { |
| 555 | cov!(self); |
| 556 | Ok(r) |
| 557 | } |
| 558 | Err(_) => { |
| 559 | cov!(self); |
| 560 | Err(WireRefusal::InvalidRepoId { at }) |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | /// `u32 count | digest*count`, strictly increasing. |
| 566 | fn digests(&mut self) -> Decoded<Vec<BlobDigest>> { |
| 567 | let n = self.count(32)?; |
| 568 | let mut out: Vec<BlobDigest> = Vec::with_capacity(n); |
| 569 | for _ in 0..n { |
| 570 | let at = self.at(); |
| 571 | let d = BlobDigest(self.array()?); |
| 572 | if out.last().is_some_and(|p| p.0 >= d.0) { |
| 573 | cov!(self); |
| 574 | return Err(WireRefusal::NotCanonical { |
| 575 | at, |
| 576 | field: "digest order", |
| 577 | }); |
| 578 | } |
| 579 | cov!(self); |
| 580 | out.push(d); |
| 581 | } |
| 582 | Ok(out) |
| 583 | } |
| 584 | |
| 585 | fn finish(&mut self) -> Decoded<()> { |
| 586 | if self.remaining() != 0 { |
| 587 | cov!(self); |
| 588 | return Err(WireRefusal::TrailingBytes { |
| 589 | at: self.at(), |
| 590 | count: self.remaining(), |
| 591 | }); |
| 592 | } |
| 593 | cov!(self); |
| 594 | Ok(()) |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | fn capability_from_tag(tag: u8) -> Option<Capability> { |
| 599 | match tag { |
| 600 | 1 => Some(Capability::Read), |
| 601 | 2 => Some(Capability::Propose), |
| 602 | 3 => Some(Capability::Evaluate), |
| 603 | 4 => Some(Capability::Review), |
| 604 | 5 => Some(Capability::Publish), |
| 605 | 6 => Some(Capability::Undo), |
| 606 | _ => None, |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | fn refusal_code_from_name(name: &str) -> Option<RefusalCode> { |
| 611 | if name.is_empty() || name.len() > MAX_REFUSAL_CODE_LEN { |
| 612 | return None; |
| 613 | } |
| 614 | if !name.bytes().all(|b| b.is_ascii_alphanumeric()) { |
| 615 | return None; |
| 616 | } |
| 617 | let code: RefusalCode = serde_json::from_value(serde_json::Value::String(name.into())).ok()?; |
| 618 | (refusal_code_name(code) == name).then_some(code) |
| 619 | } |
| 620 | |
| 621 | fn get_submit<P: Probe>(r: &mut Reader<'_, '_, P>) -> Decoded<ChainedRequest> { |
| 622 | let chain_at = r.at(); |
| 623 | let chain_bytes = { |
| 624 | let n = r.byte_len()?; |
| 625 | r.take(n)? |
| 626 | }; |
| 627 | let chain = match CapabilityChain::decode(chain_bytes) { |
| 628 | Ok(c) => c, |
| 629 | Err(e) => { |
| 630 | cov!(r); |
| 631 | return Err(WireRefusal::Chain { |
| 632 | at: chain_at, |
| 633 | code: e.code, |
| 634 | }); |
| 635 | } |
| 636 | }; |
| 637 | if chain.encode() != chain_bytes { |
| 638 | cov!(r); |
| 639 | return Err(WireRefusal::NotCanonical { |
| 640 | at: chain_at, |
| 641 | field: "capability chain", |
| 642 | }); |
| 643 | } |
| 644 | cov!(r); |
| 645 | let target_repo_id = r.repo()?; |
| 646 | let agent_key = r.array()?; |
| 647 | let cap_at = r.at(); |
| 648 | let cap_tag = r.u8()?; |
| 649 | let Some(required_capability) = capability_from_tag(cap_tag) else { |
| 650 | cov!(r); |
| 651 | return Err(WireRefusal::UnknownTag { |
| 652 | at: cap_at, |
| 653 | field: "capability", |
| 654 | tag: cap_tag, |
| 655 | }); |
| 656 | }; |
| 657 | cov!(r); |
| 658 | let paths_at = r.at(); |
| 659 | let n = r.count(4)?; |
| 660 | // Each path costs 4 wire bytes at least but a whole `String` in memory: bound the |
| 661 | // decoded size, not only the wire size, by the cap (found by the fuzzer). |
| 662 | let decoded = n as u64 * std::mem::size_of::<String>() as u64; |
| 663 | if decoded > r.cap { |
| 664 | cov!(r); |
| 665 | return Err(WireRefusal::LengthOverCap { |
| 666 | at: paths_at, |
| 667 | declared: decoded, |
| 668 | cap: r.cap, |
| 669 | }); |
| 670 | } |
| 671 | let mut paths = Vec::with_capacity(n); |
| 672 | for _ in 0..n { |
| 673 | paths.push(r.str()?); |
| 674 | } |
| 675 | let ref_at = r.at(); |
| 676 | let reference = match r.u8()? { |
| 677 | 0 => None, |
| 678 | 1 => Some(ReferenceKind::OwnDrafts), |
| 679 | 2 => Some(ReferenceKind::CanonicalViaPromotionQueue), |
| 680 | tag => { |
| 681 | cov!(r); |
| 682 | return Err(WireRefusal::UnknownTag { |
| 683 | at: ref_at, |
| 684 | field: "reference kind", |
| 685 | tag, |
| 686 | }); |
| 687 | } |
| 688 | }; |
| 689 | cov!(r); |
| 690 | let join_at = r.at(); |
| 691 | let join_change = match r.u8()? { |
| 692 | 0 => None, |
| 693 | 1 => Some(ChangeId(r.array()?)), |
| 694 | tag => { |
| 695 | cov!(r); |
| 696 | return Err(WireRefusal::UnknownTag { |
| 697 | at: join_at, |
| 698 | field: "join change option", |
| 699 | tag, |
| 700 | }); |
| 701 | } |
| 702 | }; |
| 703 | cov!(r); |
| 704 | let request_nonce = r.array()?; |
| 705 | let timestamp_ms = r.u64()?; |
| 706 | let payload = r.bytes()?; |
| 707 | let agent_signature = r.array()?; |
| 708 | cov!(r); |
| 709 | Ok(ChainedRequest { |
| 710 | chain, |
| 711 | target_repo_id, |
| 712 | agent_key, |
| 713 | required_capability, |
| 714 | scope: RequestScope { |
| 715 | paths, |
| 716 | reference, |
| 717 | join_change, |
| 718 | }, |
| 719 | request_nonce, |
| 720 | timestamp_ms, |
| 721 | payload, |
| 722 | agent_signature, |
| 723 | }) |
| 724 | } |
| 725 | |
| 726 | fn get_body<P: Probe>(r: &mut Reader<'_, '_, P>, kind: FrameKind) -> Decoded<FrameBody> { |
| 727 | let body = match kind { |
| 728 | FrameKind::Hello => { |
| 729 | cov!(r); |
| 730 | FrameBody::Hello(Hello { |
| 731 | max_frame_body: r.u32()?, |
| 732 | max_pending_chunk_bytes: r.u64()?, |
| 733 | }) |
| 734 | } |
| 735 | FrameKind::Have => { |
| 736 | cov!(r); |
| 737 | let repo_id = r.repo()?; |
| 738 | FrameBody::Have(Have { |
| 739 | repo_id, |
| 740 | digests: r.digests()?, |
| 741 | }) |
| 742 | } |
| 743 | FrameKind::Want => { |
| 744 | cov!(r); |
| 745 | FrameBody::Want(Want { |
| 746 | digests: r.digests()?, |
| 747 | }) |
| 748 | } |
| 749 | FrameKind::Chunk => { |
| 750 | cov!(r); |
| 751 | let digest = BlobDigest(r.array()?); |
| 752 | FrameBody::Chunk(Chunk { |
| 753 | digest, |
| 754 | bytes: r.bytes()?, |
| 755 | }) |
| 756 | } |
| 757 | FrameKind::Submit => { |
| 758 | cov!(r); |
| 759 | FrameBody::Submit(Box::new(get_submit(r)?)) |
| 760 | } |
| 761 | FrameKind::Accepted => { |
| 762 | cov!(r); |
| 763 | let wal_seq = WalSeq(r.u64()?); |
| 764 | let changeset_id = ChangesetId(r.array()?); |
| 765 | let at = r.at(); |
| 766 | let duplicate = match r.u8()? { |
| 767 | 0 => false, |
| 768 | 1 => true, |
| 769 | tag => { |
| 770 | cov!(r); |
| 771 | return Err(WireRefusal::UnknownTag { |
| 772 | at, |
| 773 | field: "duplicate", |
| 774 | tag, |
| 775 | }); |
| 776 | } |
| 777 | }; |
| 778 | FrameBody::Accepted(Accepted { |
| 779 | wal_seq, |
| 780 | changeset_id, |
| 781 | duplicate, |
| 782 | }) |
| 783 | } |
| 784 | FrameKind::Refused => { |
| 785 | cov!(r); |
| 786 | let at = r.at(); |
| 787 | let name = r.str()?; |
| 788 | let Some(code) = refusal_code_from_name(&name) else { |
| 789 | cov!(r); |
| 790 | return Err(WireRefusal::UnknownRefusalCode { at }); |
| 791 | }; |
| 792 | FrameBody::Refused(Refused { |
| 793 | code, |
| 794 | message: r.str()?, |
| 795 | }) |
| 796 | } |
| 797 | }; |
| 798 | r.finish()?; |
| 799 | Ok(body) |
| 800 | } |
| 801 | |
| 802 | fn header_probed<P: Probe>( |
| 803 | bytes: &[u8], |
| 804 | limits: &WireLimits, |
| 805 | probe: &mut P, |
| 806 | ) -> Decoded<FrameHeader> { |
| 807 | let mut r = Reader { |
| 808 | buf: bytes, |
| 809 | pos: 0, |
| 810 | base: 0, |
| 811 | cap: u64::from(limits.max_frame_body), |
| 812 | probe, |
| 813 | }; |
| 814 | let h: [u8; FRAME_HEADER_LEN] = r.array()?; |
| 815 | cov!(r); |
| 816 | let magic: [u8; 4] = h[0..4].try_into().expect("4 bytes"); |
| 817 | if magic != WIRE_MAGIC { |
| 818 | cov!(r); |
| 819 | return Err(WireRefusal::BadMagic { found: magic }); |
| 820 | } |
| 821 | if h[4] != WIRE_VERSION { |
| 822 | cov!(r); |
| 823 | return Err(WireRefusal::VersionUnsupported { found: h[4] }); |
| 824 | } |
| 825 | let Some(kind) = FrameKind::from_byte(h[5]) else { |
| 826 | cov!(r); |
| 827 | return Err(WireRefusal::UnknownKind { found: h[5] }); |
| 828 | }; |
| 829 | if h[6] != 0 { |
| 830 | cov!(r); |
| 831 | return Err(WireRefusal::FlagsNonZero { found: h[6] }); |
| 832 | } |
| 833 | if h[7] != 0 { |
| 834 | cov!(r); |
| 835 | return Err(WireRefusal::ReservedNonZero { found: h[7] }); |
| 836 | } |
| 837 | let request_id = u32::from_le_bytes(h[8..12].try_into().expect("4 bytes")); |
| 838 | let body_len = u32::from_le_bytes(h[12..16].try_into().expect("4 bytes")); |
| 839 | if body_len > limits.max_frame_body { |
| 840 | cov!(r); |
| 841 | return Err(WireRefusal::LengthOverCap { |
| 842 | at: 12, |
| 843 | declared: u64::from(body_len), |
| 844 | cap: u64::from(limits.max_frame_body), |
| 845 | }); |
| 846 | } |
| 847 | cov!(r); |
| 848 | Ok(FrameHeader { |
| 849 | kind, |
| 850 | request_id, |
| 851 | body_len, |
| 852 | }) |
| 853 | } |
| 854 | |
| 855 | /// Parse and check the 16-byte header (magic, version, kind, flags, reserved, and the |
| 856 | /// declared body length against `limits`). Reads at most [`FRAME_HEADER_LEN`] bytes. |
| 857 | pub fn decode_header(bytes: &[u8], limits: &WireLimits) -> Result<FrameHeader, WireRefusal> { |
| 858 | header_probed(bytes, limits, &mut NoProbe) |
| 859 | } |
| 860 | |
| 861 | /// Decode a body of exactly `header.body_len` bytes (as read from a stream after |
| 862 | /// [`decode_header`]). |
| 863 | pub fn decode_body( |
| 864 | header: &FrameHeader, |
| 865 | body: &[u8], |
| 866 | limits: &WireLimits, |
| 867 | ) -> Result<Frame, WireRefusal> { |
| 868 | body_probed(header, body, limits, &mut NoProbe) |
| 869 | } |
| 870 | |
| 871 | fn body_probed<P: Probe>( |
| 872 | header: &FrameHeader, |
| 873 | body: &[u8], |
| 874 | limits: &WireLimits, |
| 875 | probe: &mut P, |
| 876 | ) -> Decoded<Frame> { |
| 877 | if body.len() != header.body_len as usize { |
| 878 | return Err(WireRefusal::Truncated { |
| 879 | at: FRAME_HEADER_LEN + body.len().min(header.body_len as usize), |
| 880 | need: (header.body_len as usize).saturating_sub(body.len()), |
| 881 | }); |
| 882 | } |
| 883 | let mut r = Reader { |
| 884 | buf: body, |
| 885 | pos: 0, |
| 886 | base: FRAME_HEADER_LEN, |
| 887 | cap: u64::from(limits.max_frame_body), |
| 888 | probe, |
| 889 | }; |
| 890 | let body = get_body(&mut r, header.kind)?; |
| 891 | Ok(Frame { |
| 892 | request_id: header.request_id, |
| 893 | body, |
| 894 | }) |
| 895 | } |
| 896 | |
| 897 | /// Decode the first frame of `buf` (a stream buffer that may hold more frames after it). |
| 898 | /// Returns the frame and the number of bytes it occupies. Only the first |
| 899 | /// `16 + body_len` bytes are ever read. |
| 900 | pub fn decode_frame(buf: &[u8], limits: &WireLimits) -> Result<(Frame, usize), WireRefusal> { |
| 901 | decode_frame_probed(buf, limits, &mut NoProbe) |
| 902 | } |
| 903 | |
| 904 | /// [`decode_frame`] reporting decoder states and reads to `probe` (used by the fuzzer). |
| 905 | pub fn decode_frame_probed<P: Probe>( |
| 906 | buf: &[u8], |
| 907 | limits: &WireLimits, |
| 908 | probe: &mut P, |
| 909 | ) -> Result<(Frame, usize), WireRefusal> { |
| 910 | let header = header_probed(buf, limits, probe)?; |
| 911 | let end = header.frame_len(); |
| 912 | if buf.len() < end { |
| 913 | probe.site(line!()); |
| 914 | return Err(WireRefusal::Truncated { |
| 915 | at: buf.len(), |
| 916 | need: end - buf.len(), |
| 917 | }); |
| 918 | } |
| 919 | let frame = body_probed(&header, &buf[FRAME_HEADER_LEN..end], limits, probe)?; |
| 920 | Ok((frame, end)) |
| 921 | } |