interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-auth / tests / payload_digest_streaming.rs

213 lines · 6440 bytes Raw Blame History
1//! Issue #92: the request payload digest is computed by streaming the payload's compact JSON
2//! straight into SHA-256, without first materializing the whole JSON text in memory.
3//!
4//! The digest definition does not change (SHA-256 of the compact `serde_json` encoding, which
5//! the agent signs through `payload_sha256`); this file proves the memory shape of the check:
6//! the largest single heap allocation made while signing or authorizing a large payload stays a
7//! small fixed size, far below the payload's JSON length. Before #92 both paths built the JSON
8//! text in one growing `Vec`, so the largest allocation was at least the JSON length.
9//!
10//! Byte-for-byte parity of the new digest with the old one is proven separately, over the A1
11//! malformed corpus and recorded requests, in `crates/synapse-api/tests/payload_digest_parity.rs`.
12
13use ed25519_dalek::SigningKey;
14use sha2::{Digest, Sha256};
15use std::alloc::{GlobalAlloc, Layout, System};
16use std::cell::Cell;
17use synapse_auth::{
18 payload_digest, AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability,
19 PolicyEnforcer,
20};
21use synapse_core::{encode_did_key_ed25519, RepoId};
22
23/// Records the largest single allocation made on the measuring thread while a window is open.
24struct PeakAlloc;
25
26thread_local! {
27 static MEASURING: Cell<bool> = const { Cell::new(false) };
28 static PEAK: Cell<usize> = const { Cell::new(0) };
29}
30
31fn note(size: usize) {
32 let _ = MEASURING.try_with(|m| {
33 if m.get() {
34 let _ = PEAK.try_with(|p| p.set(p.get().max(size)));
35 }
36 });
37}
38
39unsafe impl GlobalAlloc for PeakAlloc {
40 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
41 note(layout.size());
42 unsafe { System.alloc(layout) }
43 }
44 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
45 unsafe { System.dealloc(ptr, layout) }
46 }
47 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
48 note(layout.size());
49 unsafe { System.alloc_zeroed(layout) }
50 }
51 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
52 note(new_size);
53 unsafe { System.realloc(ptr, layout, new_size) }
54 }
55}
56
57#[global_allocator]
58static GLOBAL: PeakAlloc = PeakAlloc;
59
60/// Largest single allocation made by `f` on this thread.
61fn peak_alloc<R>(f: impl FnOnce() -> R) -> (R, usize) {
62 PEAK.with(|p| p.set(0));
63 MEASURING.with(|m| m.set(true));
64 let r = f();
65 MEASURING.with(|m| m.set(false));
66 (r, PEAK.with(|p| p.get()))
67}
68
69/// Ceiling for any single allocation during digesting: a fixed staging buffer plus slack.
70const SMALL_ALLOC_CEILING: usize = 64 * 1024;
71/// Blob size: its compact JSON (decimal byte values with commas) is several times larger.
72const BLOB_LEN: usize = 256 * 1024;
73
74fn derived(label: &str, counter: u64) -> [u8; 32] {
75 let mut h = Sha256::new();
76 h.update(b"SYNAPSE_AUTH_PAYLOAD_DIGEST_TEST_V1\0");
77 h.update(label.as_bytes());
78 h.update(counter.to_le_bytes());
79 h.finalize().into()
80}
81
82fn key(label: &str) -> SigningKey {
83 SigningKey::from_bytes(&derived(label, 0))
84}
85
86/// A blob whose bytes cover every value, so the JSON mixes one-, two- and three-digit numbers.
87fn blob() -> Vec<u8> {
88 (0..BLOB_LEN)
89 .map(|i| derived("blob", (i / 32) as u64)[i % 32])
90 .collect()
91}
92
93type Payload = (String, Vec<(String, Vec<u8>)>);
94
95fn payload() -> Payload {
96 ("submit".to_string(), vec![("blob-0".to_string(), blob())])
97}
98
99struct Fixture {
100 repo: RepoId,
101 authority: SigningKey,
102 agent: SigningKey,
103}
104
105fn fixture() -> Fixture {
106 Fixture {
107 repo: RepoId::new("payload-digest-repo").unwrap(),
108 authority: key("authority"),
109 agent: key("agent"),
110 }
111}
112
113fn grant(f: &Fixture, max_bytes_per_op: u64) -> AgentCapabilityGrant {
114 AgentCapabilityGrant::issue(
115 &f.authority,
116 derived("grant", 0),
117 f.repo.clone(),
118 encode_did_key_ed25519(&f.agent.verifying_key().to_bytes()),
119 vec![Capability::Propose],
120 max_bytes_per_op,
121 100,
122 60_000,
123 1_000,
124 1_000_000,
125 )
126}
127
128fn enforcer(f: &Fixture) -> PolicyEnforcer {
129 let mut e = PolicyEnforcer::new();
130 e.register_repo_authority(
131 f.repo.clone(),
132 encode_did_key_ed25519(&f.authority.verifying_key().to_bytes()),
133 );
134 e
135}
136
137#[test]
138fn signing_a_large_payload_never_materializes_its_json() {
139 let f = fixture();
140 let p = payload();
141 let json_len = serde_json::to_vec(&p).unwrap().len();
142 assert!(
143 json_len > 3 * BLOB_LEN,
144 "JSON must dwarf the blob: {json_len}"
145 );
146 let g = grant(&f, u64::MAX);
147 let (req, peak) = peak_alloc(|| {
148 AuthenticatedRequest::sign_new(
149 &f.agent,
150 g,
151 f.repo.clone(),
152 Capability::Propose,
153 derived("nonce", 0),
154 2_000,
155 0,
156 p,
157 )
158 });
159 let req = req.unwrap();
160 assert_eq!(req.payload_bytes_len, json_len as u64);
161 assert!(
162 peak <= SMALL_ALLOC_CEILING,
163 "sign_new made a {peak} byte allocation for a {json_len} byte JSON payload"
164 );
165}
166
167#[test]
168fn authorizing_a_large_payload_never_materializes_its_json() {
169 let f = fixture();
170 let p = payload();
171 let json_len = serde_json::to_vec(&p).unwrap().len();
172 let req = AuthenticatedRequest::sign_new(
173 &f.agent,
174 grant(&f, u64::MAX),
175 f.repo.clone(),
176 Capability::Propose,
177 derived("nonce", 1),
178 2_000,
179 0,
180 p,
181 )
182 .unwrap();
183 let mut e = enforcer(&f);
184 let (r, peak) = peak_alloc(|| {
185 e.authorize(
186 BoundaryKind::Api,
187 "submit",
188 &f.repo,
189 Capability::Propose,
190 &req,
191 2_000,
192 )
193 });
194 r.unwrap();
195 assert!(
196 peak <= SMALL_ALLOC_CEILING,
197 "authorize made a {peak} byte allocation for a {json_len} byte JSON payload"
198 );
199}
200
201#[test]
202fn payload_digest_streams_and_matches_the_materialized_json() {
203 let p = payload();
204 let json = serde_json::to_vec(&p).unwrap();
205 let want: [u8; 32] = Sha256::digest(&json).into();
206 let (got, peak) = peak_alloc(|| payload_digest(&p).unwrap());
207 assert_eq!(got, (want, json.len() as u64));
208 assert!(
209 peak <= SMALL_ALLOC_CEILING,
210 "payload_digest made a {peak} byte allocation for a {} byte JSON payload",
211 json.len()
212 );
213}