synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-auth / src / digest.rs
| 1 | //! Request payload digest (issue #92). |
| 2 | //! |
| 3 | //! `payload_sha256` is defined as SHA-256 over the payload's compact `serde_json` encoding, and |
| 4 | //! `payload_bytes_len` is at least that encoding's length. The agent signs both through |
| 5 | //! `AuthenticatedRequest::canonical_signable_bytes`, so the definition is part of the protocol |
| 6 | //! and does not change here. What changes is only how the bytes reach the hash: the serializer |
| 7 | //! writes them through a small fixed staging buffer straight into SHA-256 instead of first |
| 8 | //! collecting the whole JSON text in one growing `Vec` (`serde_json::to_vec`) and hashing that. |
| 9 | //! |
| 10 | //! Equivalence with `SHA-256(serde_json::to_vec(payload))`: |
| 11 | //! * `serde_json::to_vec(v)` is `v.serialize(&mut Serializer::new(Vec::with_capacity(128)))`, |
| 12 | //! and `Serializer::new` is `Serializer::with_formatter(_, CompactFormatter)`, where |
| 13 | //! `CompactFormatter` overrides nothing (`impl Formatter for CompactFormatter {}`): every |
| 14 | //! byte comes from the `Formatter` trait's default methods. |
| 15 | //! * [`DigestFormatter`] also takes every default method except `write_u8`, which it answers |
| 16 | //! from a table instead of `itoa`. The table's 256 entries are checked against |
| 17 | //! `serde_json::to_vec(&v)` for every `u8` value in the unit tests below. |
| 18 | //! * The serializer drives the formatter the same way whatever the writer is, so the byte |
| 19 | //! sequence is identical; the writer only decides where the bytes go. SHA-256 depends only |
| 20 | //! on that sequence, not on how it is split across `update` calls, and the counted length is |
| 21 | //! the number of bytes written. Writes never fail, so a serialization error comes only from |
| 22 | //! the payload's `Serialize` impl, the same error with the same message as before. |
| 23 | //! |
| 24 | //! The parity tests in `crates/synapse-api/tests/payload_digest_parity.rs` check the result |
| 25 | //! against the old computation over the A1 malformed corpus and recorded requests. |
| 26 | |
| 27 | use serde::Serialize; |
| 28 | use serde_json::ser::Formatter; |
| 29 | use sha2::{Digest, Sha256}; |
| 30 | use std::io; |
| 31 | use synapse_core::{RefusalCode, SynapseError, SynapseResult}; |
| 32 | |
| 33 | /// Size of the staging buffer between the JSON serializer and SHA-256. |
| 34 | pub(crate) const DIGEST_STAGING_BYTES: usize = 8 * 1024; |
| 35 | |
| 36 | /// `io::Write` sink that hashes everything written to it and counts the bytes. |
| 37 | struct DigestWriter { |
| 38 | staged: Vec<u8>, |
| 39 | hasher: Sha256, |
| 40 | hashed: u64, |
| 41 | } |
| 42 | |
| 43 | impl DigestWriter { |
| 44 | fn new() -> Self { |
| 45 | Self { |
| 46 | staged: Vec::with_capacity(DIGEST_STAGING_BYTES), |
| 47 | hasher: Sha256::new(), |
| 48 | hashed: 0, |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | fn drain(&mut self) { |
| 53 | self.hasher.update(&self.staged); |
| 54 | self.hashed += self.staged.len() as u64; |
| 55 | self.staged.clear(); |
| 56 | } |
| 57 | |
| 58 | /// The staging buffer cannot take `data`: hash what is staged, then stage `data`, or hash |
| 59 | /// it directly when it is at least a buffer long. |
| 60 | #[cold] |
| 61 | #[inline(never)] |
| 62 | fn spill(&mut self, data: &[u8]) { |
| 63 | self.drain(); |
| 64 | if data.len() >= DIGEST_STAGING_BYTES { |
| 65 | self.hasher.update(data); |
| 66 | self.hashed += data.len() as u64; |
| 67 | } else { |
| 68 | self.staged.extend_from_slice(data); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn finish(mut self) -> ([u8; 32], u64) { |
| 73 | self.drain(); |
| 74 | (self.hasher.finalize().into(), self.hashed) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | impl io::Write for DigestWriter { |
| 79 | #[inline] |
| 80 | fn write(&mut self, data: &[u8]) -> io::Result<usize> { |
| 81 | self.write_all(data)?; |
| 82 | Ok(data.len()) |
| 83 | } |
| 84 | |
| 85 | #[inline(always)] |
| 86 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> { |
| 87 | // The buffer never grows past its initial capacity: what does not fit spills. |
| 88 | if self.staged.capacity() - self.staged.len() >= data.len() { |
| 89 | self.staged.extend_from_slice(data); |
| 90 | } else { |
| 91 | self.spill(data); |
| 92 | } |
| 93 | Ok(()) |
| 94 | } |
| 95 | |
| 96 | fn flush(&mut self) -> io::Result<()> { |
| 97 | Ok(()) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Decimal text of every `u8` (`[digits.., len]`), built at compile time. |
| 102 | const fn decimal_u8_table() -> [[u8; 4]; 256] { |
| 103 | let mut table = [[0u8; 4]; 256]; |
| 104 | let mut i = 0; |
| 105 | while i < 256 { |
| 106 | let v = i as u8; |
| 107 | table[i] = if v >= 100 { |
| 108 | [b'0' + v / 100, b'0' + v / 10 % 10, b'0' + v % 10, 3] |
| 109 | } else if v >= 10 { |
| 110 | [b'0' + v / 10, b'0' + v % 10, 0, 2] |
| 111 | } else { |
| 112 | [b'0' + v, 0, 0, 1] |
| 113 | }; |
| 114 | i += 1; |
| 115 | } |
| 116 | table |
| 117 | } |
| 118 | |
| 119 | static DECIMAL_U8: [[u8; 4]; 256] = decimal_u8_table(); |
| 120 | |
| 121 | /// `CompactFormatter` with a table lookup for `u8` (blob bytes are `Vec<u8>`, one JSON number |
| 122 | /// per byte, so this is the hot path). Every other method is the trait default, exactly as in |
| 123 | /// `CompactFormatter`. |
| 124 | struct DigestFormatter; |
| 125 | |
| 126 | impl Formatter for DigestFormatter { |
| 127 | #[inline] |
| 128 | fn write_u8<W>(&mut self, writer: &mut W, value: u8) -> io::Result<()> |
| 129 | where |
| 130 | W: ?Sized + io::Write, |
| 131 | { |
| 132 | let entry = &DECIMAL_U8[value as usize]; |
| 133 | writer.write_all(&entry[..entry[3] as usize]) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// SHA-256 of `payload`'s compact `serde_json` encoding, and that encoding's length in bytes. |
| 138 | /// |
| 139 | /// Byte-for-byte the same result as hashing `serde_json::to_vec(payload)` and taking its |
| 140 | /// length, without ever holding the encoding in memory. A serialization failure is refused with |
| 141 | /// `IoFailure` and the same message the old code used. |
| 142 | pub fn payload_digest<T: Serialize + ?Sized>(payload: &T) -> SynapseResult<([u8; 32], u64)> { |
| 143 | let mut sink = DigestWriter::new(); |
| 144 | payload |
| 145 | .serialize(&mut serde_json::Serializer::with_formatter( |
| 146 | &mut sink, |
| 147 | DigestFormatter, |
| 148 | )) |
| 149 | .map_err(|e| { |
| 150 | SynapseError::new(RefusalCode::IoFailure, format!("serialize payload: {e}")) |
| 151 | })?; |
| 152 | Ok(sink.finish()) |
| 153 | } |
| 154 | |
| 155 | #[cfg(test)] |
| 156 | mod tests { |
| 157 | use super::*; |
| 158 | |
| 159 | #[test] |
| 160 | fn decimal_table_matches_serde_json_for_every_u8() { |
| 161 | for v in 0..=u8::MAX { |
| 162 | let entry = &DECIMAL_U8[v as usize]; |
| 163 | assert_eq!( |
| 164 | &entry[..entry[3] as usize], |
| 165 | serde_json::to_vec(&v).unwrap().as_slice(), |
| 166 | "{v}" |
| 167 | ); |
| 168 | // Also as a map key, where serde_json quotes the number. |
| 169 | let key = std::collections::BTreeMap::from([(v, ())]); |
| 170 | let mut out = Vec::new(); |
| 171 | key.serialize(&mut serde_json::Serializer::with_formatter( |
| 172 | &mut out, |
| 173 | DigestFormatter, |
| 174 | )) |
| 175 | .unwrap(); |
| 176 | assert_eq!(out, serde_json::to_vec(&key).unwrap(), "key {v}"); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | #[test] |
| 181 | fn every_write_size_around_the_staging_buffer_hashes_the_same_bytes() { |
| 182 | use std::io::Write; |
| 183 | // Byte strings written in pieces of every size from 1 to past two buffers. |
| 184 | let data: Vec<u8> = (0..3 * DIGEST_STAGING_BYTES) |
| 185 | .map(|i| (i * 31 % 251) as u8) |
| 186 | .collect(); |
| 187 | for piece in [ |
| 188 | 1, |
| 189 | 7, |
| 190 | DIGEST_STAGING_BYTES - 1, |
| 191 | DIGEST_STAGING_BYTES, |
| 192 | DIGEST_STAGING_BYTES + 1, |
| 193 | 2 * DIGEST_STAGING_BYTES + 3, |
| 194 | ] { |
| 195 | let mut w = DigestWriter::new(); |
| 196 | for chunk in data.chunks(piece) { |
| 197 | w.write_all(chunk).unwrap(); |
| 198 | } |
| 199 | assert!(w.staged.capacity() <= DIGEST_STAGING_BYTES, "piece {piece}"); |
| 200 | let want: [u8; 32] = Sha256::digest(&data).into(); |
| 201 | assert_eq!(w.finish(), (want, data.len() as u64), "piece {piece}"); |
| 202 | } |
| 203 | } |
| 204 | } |