From b84b5d1961d75871e96c34d12fdb463fbaa7ac5b Mon Sep 17 00:00:00 2001 From: Libby Date: Sat, 14 Nov 2026 04:43:27 +0000 Subject: [PATCH] cultmesh-rs: refuse a peer raw put whose storedAt is no stamp (raw-put-refuse-rs) Co-Authored-By: Claude Sonnet 5.5 --- packages/cultmesh-rs/src/lib.rs | 24 +++ .../cultmesh-rs/src/rudp_document_server.rs | 25 ++- .../cultmesh-rs/tests/rudp_document_server.rs | 174 ++++++++++++++++++ 3 files changed, 219 insertions(+), 4 deletions(-) diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index b1ee613b..e3132ece 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -1301,6 +1301,30 @@ mod tests { Ok(()) } + /// The node's store is the second owner of the stamp rule: a snapshot document whose `storedAt` is no stamp refuses + /// the whole pull, nothing is minted or stored, and the node stays writable. + #[test] + fn a_snapshot_document_whose_stored_at_is_no_stamp_refuses_the_pull_and_stores_nothing() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("m.cc"); + let mut node = CultMesh::create_node(&path, TestDocuments, Default::default())?; + let plain = |body: &str| rmp_serde::to_vec(&(body,)); + for bad in ["", "yesterday", "2026-01-01T00:00:00", "2026-01-01t00:00:00z", "2026-01-01T00:00:60Z"] { + let mut stampless = raw_note("bad", plain("bad")?); + stampless.stored_at = bad.to_string(); + let error = node + .apply_raw_snapshot_documents(vec![raw_note("good", plain("good")?), stampless]) + .unwrap_err(); + assert!(format!("{error:#}").contains("stored_at"), "{bad:?}: {error:#}"); + assert!(node.get::("good")?.is_none() && node.get::("bad")?.is_none(), "{bad:?}"); + } + assert_eq!(node.apply_raw_snapshot_documents(vec![raw_note("after", plain("after")?)])?, 1); + let reopened = CultMesh::create_node(&path, TestDocuments, Default::default())?; + assert_eq!(reopened.get_required::("after")?.body, "after"); + assert!(reopened.get::("good")?.is_none()); + Ok(()) + } + #[test] fn a_snapshot_applied_to_a_stale_node_keeps_the_records_another_writer_added() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 9aae5be9..1c440a14 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -69,7 +69,8 @@ pub struct CultMeshRudpSnapshotQuery { pub trait CultMeshRudpRawDocumentSink { /// Whether this put may be written, decided without writing it. A receipt-capable session asks it only /// the first time it sees a message id; a resend is answered from what the session remembers - /// (write-receipt.md, rule 5). The default admits everything and leaves the decision to + /// (write-receipt.md, rule 5). A legacy session asks it only for a put whose `storedAt` is no stamp, so the + /// authority's refusal comes before the stamp's. The default admits everything and leaves the decision to /// `accept_raw_document`. fn authorize_raw_document(&mut self, _receipt: &CultMeshRudpRawDocumentReceipt) -> Result<()> { Ok(()) @@ -293,6 +294,9 @@ pub enum CultMeshRudpRejectionReason { DocumentMissing, /// A receipt-capable session's put or delete has a null or missing `schemaId`. SchemaIdMissing, + /// A put's `storedAt` is not a stamp (`cultcache_rs::is_stored_at_stamp`). It is judged after the sink's + /// authorization and before the document is measured or the sink commits it: nothing is minted or stored. + StoredAtNotStamp, } impl std::fmt::Display for CultMeshRudpRejectionReason { @@ -307,6 +311,7 @@ impl std::fmt::Display for CultMeshRudpRejectionReason { Self::ChannelNotReliable => f.write_str("a receipt session's write arrived on an unreliable channel"), Self::DocumentMissing => f.write_str("the write has no document"), Self::SchemaIdMissing => f.write_str("the write has no schemaId"), + Self::StoredAtNotStamp => f.write_str("the document's storedAt is not a stamp"), Self::DocumentUnservable { response_bytes, max_snapshot_response_bytes, @@ -347,7 +352,7 @@ impl std::fmt::Display for CultMeshRudpRejectionReason { /// The texts a refused peer is sent, one per rejection variant. They are fixed: /// a sink's or source's error text can quote what a peer sent, so it stays with /// the caller that receives the rejection and never reaches the wire. -pub(crate) const REFUSAL_TEXTS: [&str; 17] = [ +pub(crate) const REFUSAL_TEXTS: [&str; 18] = [ "the catalog refused the document", "the document can never be served", "the snapshot source failed", @@ -365,6 +370,7 @@ pub(crate) const REFUSAL_TEXTS: [&str; 17] = [ "receipt sessions require the reliable channel", "document is required", "schemaId is required", + "document must carry a storedAt stamp", ]; impl CultMeshRudpRejectionReason { @@ -393,7 +399,8 @@ impl CultMeshRudpRejectionReason { 13 => Self::MessageIdTooLong, 14 => Self::ChannelNotReliable, 15 => Self::DocumentMissing, - _ => Self::SchemaIdMissing, + 16 => Self::SchemaIdMissing, + _ => Self::StoredAtNotStamp, } } @@ -416,6 +423,7 @@ impl CultMeshRudpRejectionReason { Self::ChannelNotReliable => 14, Self::DocumentMissing => 15, Self::SchemaIdMissing => 16, + Self::StoredAtNotStamp => 17, } } } @@ -498,6 +506,7 @@ impl CultMeshRudpApplicationRejection { (CultMeshRudpRejectionReason::MessageIdTooLong, _) => message_invalid_message("messageId", text), (CultMeshRudpRejectionReason::DocumentMissing, _) => message_invalid_message("document", text), (CultMeshRudpRejectionReason::SchemaIdMissing, _) => message_invalid_message("schemaId", text), + (CultMeshRudpRejectionReason::StoredAtNotStamp, _) => message_invalid_message("document", text), (CultMeshRudpRejectionReason::ChannelNotReliable, _) => message_invalid_message("channel", text), (CultMeshRudpRejectionReason::WriteLimitReached, _) => CultNetMessage::Error { error: format!("limit_reached: {text}"), @@ -1601,11 +1610,19 @@ where receipt: CultMeshRudpRawDocumentReceipt, authorize: bool, ) -> std::result::Result<(), CultMeshRudpRejectionReason> { - if authorize { + let stamped = cultcache_rs::is_stored_at_stamp(&receipt.document.stored_at); + // The authority speaks first. A legacy session's sink decides at `accept_raw_document`, so it is asked here + // only when the stamp is bad: an ungranted peer is refused `write_not_authorized`, not told its stamp is wrong. + if authorize || !stamped { if let Err(error) = self.sink.authorize_raw_document(&receipt) { return Err(CultMeshRudpRejectionReason::SinkRefused(format!("{error:#}"))); } } + // A peer's put is stored under the stamp it carries, so one that is no stamp is refused before anything is + // measured, minted or handed to the sink. + if !stamped { + return Err(CultMeshRudpRejectionReason::StoredAtNotStamp); + } let document = &receipt.document; // Admit only what some snapshot request can return: the smallest // response that could carry this document is the record the snapshot diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 45a232d6..3f4d391a 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -3630,3 +3630,177 @@ fn an_unreadable_frame_on_a_receipt_connection_is_sent_exactly_the_fixed_text() ); Ok(()) } + +// ---- A peer's `storedAt` must be a stamp (variants:ruling:raw-put-without-stamp-refused) ---- +// +// `tests/vectors/stored-at-stamp/stamps.msgpack`: `[text, parses]` rows. Every row that is no stamp is refused and +// nothing reaches the sink. A blank text names nothing, so it is refused as a frame that does not read (field +// "message", write-receipt.md, Required fields); any other text that is no stamp is refused field "document". + +fn stamp_rows() -> Vec<(String, bool)> { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/vectors/stored-at-stamp/stamps.msgpack"); + rmp_serde::from_slice(&std::fs::read(path).unwrap()).unwrap() +} + +fn is_blank(text: &str) -> bool { + text.chars().all(char::is_whitespace) +} + +/// A put of `key` whose `storedAt` is `stamp` as it would arrive: a blank one is swapped into the bytes, since the +/// encoder refuses it. +fn put_stamped_bytes(id: &str, key: &str, payload: Vec, stamp: &str) -> Result> { + let mut record = document(key, payload); + record.stored_at = if is_blank(stamp) { "zz-stamp-zz".into() } else { stamp.into() }; + let bytes = encode_cultnet_message_to_vec( + &CultNetMessage::DocumentPutRaw { message_id: id.into(), document: record }, + CultNetWireContract::CultNetSchemaV0, + )?; + Ok(if is_blank(stamp) { swap_fixstr(&bytes, "zz-stamp-zz", stamp) } else { bytes }) +} + +#[test] +fn a_receipt_session_put_that_is_no_stamp_is_refused_for_every_vector_row_and_the_store_stays_writable() -> Result<()> { + let rows = stamp_rows(); + assert!(rows.len() > 30); + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, 700)?; + connect(&mut server, &mut [&mut peer])?; + send_reliable(&mut peer, &receipt_hello())?; + assert_eq!(frames_after(&mut server, &mut peer, 1)?, vec![server_hello()]); + let mut expected = Vec::new(); + let mut answers = Vec::new(); + for (index, (text, parses)) in rows.iter().enumerate() { + let id = format!("r{index}"); + peer.send_reliable("schema", put_stamped_bytes(&id, &format!("note:{index}"), vec![1, 2, 3], text)?)?; + expected.push((id, text.clone(), *parses)); + // One write in flight at a time: the answer arrives before the next row is sent. + answers.extend(frames_after(&mut server, &mut peer, 1)?); + } + peer.send_reliable("schema", valid_put("after"))?; + answers.extend(frames_after(&mut server, &mut peer, 1)?); + for (answer, (id, text, parses)) in answers.iter().zip(&expected) { + if *parses { + assert_eq!(*answer, admitted(id, &id.replace('r', "note:")), "{text:?}"); + continue; + } + assert_eq!(refusal_of(answer), (Some(CultNetErrorCode::MessageInvalid), Some(id.clone())), "{text:?}"); + let field = if is_blank(text) { "message" } else { "document" }; + assert_eq!(error_text_and_field(answer).1, Some(field.into()), "{text:?}"); + } + // Every stamp row was stored exactly as sent; no refused row was stored; the put after them all was. + let state = sink.0.lock().unwrap(); + let stored: Vec<&str> = state.receipts.iter().map(|receipt| receipt.document.stored_at.as_str()).collect(); + let stamps: Vec<&str> = rows.iter().filter(|(_, parses)| *parses).map(|(text, _)| text.as_str()).collect(); + assert_eq!(&stored[..stamps.len()], &stamps[..]); + assert_eq!(stored.len(), stamps.len() + 1, "only the stamped puts and the final put were stored"); + assert_eq!(answers.last(), Some(&admitted("put-after", "after"))); + Ok(()) +} + +#[test] +fn a_put_with_no_storedat_key_is_refused_and_a_resend_replays_the_refusal() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, 701)?; + connect(&mut server, &mut [&mut peer])?; + send_reliable(&mut peer, &receipt_hello())?; + let missing = swap_fixstr(&valid_put("a"), "storedAt", "storedAx"); + peer.send_reliable("schema", missing)?; + // The same garbage stamp twice under one id: the refusal is remembered (by index) and replays as it was. + peer.send_reliable("schema", put_stamped_bytes("g1", "note:g", vec![1], "yesterday")?)?; + peer.send_reliable("schema", put_stamped_bytes("g1", "note:g", vec![1], "yesterday")?)?; + let answers = answers_after(&mut server, &mut peer, 3)?; + assert_eq!(error_text_and_field(&answers[0]).1, Some("message".into())); + assert_eq!(refusal_of(&answers[1]), (Some(CultNetErrorCode::MessageInvalid), Some("g1".into()))); + assert_eq!(error_text_and_field(&answers[1]).1, Some("document".into())); + assert_eq!(answers[2], answers[1]); + assert!(sink.0.lock().unwrap().receipts.is_empty()); + Ok(()) +} + +#[test] +fn a_legacy_session_put_that_is_no_stamp_is_refused_for_every_vector_row_and_nothing_is_stored() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut connection_id = 800; + for (text, parses) in stamp_rows() { + if parses { + continue; + } + connection_id += 1; + let mut peer = client(server.local_addr()?, connection_id)?; + connect(&mut server, &mut [&mut peer])?; + let receipt = peer.send_reliable("schema", put_stamped_bytes("bad", "note:bad", vec![1, 2, 3], &text)?)?; + let reason = poll_until_rejected_or_stored(&mut server, &mut peer, &sink, 1)?; + if is_blank(&text) { + assert!(matches!(reason, Some(CultMeshRudpRejectionReason::MessageUnreadable(_))), "{text:?}: {reason:?}"); + } else { + assert_eq!(reason, Some(CultMeshRudpRejectionReason::StoredAtNotStamp), "{text:?}"); + let (error, code, details) = typed_refusal_seen_by(&mut peer, &receipt, Some(&mut server))?; + assert_eq!(code, Some(CultNetErrorCode::MessageInvalid), "{text:?}: {error}"); + assert_eq!(details.and_then(|d| d.field), Some("document".into()), "{text:?}"); + } + assert!(sink.0.lock().unwrap().receipts.is_empty(), "{text:?} reached the sink"); + } + // The server and its sink are still writable. + connection_id += 1; + let mut peer = client(server.local_addr()?, connection_id)?; + connect(&mut server, &mut [&mut peer])?; + stored_after_poll(&mut server, &mut peer, &sink, 1)?; + Ok(()) +} + +/// The size gate measures the document as a snapshot would serve it: a put over the bound that is also no stamp is +/// refused for its stamp first, and nothing is measured for one that is. +#[test] +fn the_stamp_is_judged_before_the_size_limit() -> Result<()> { + let over = document("big", vec![7; 101]); + let options = CultMeshRudpDocumentServerOptions { + max_snapshot_response_bytes: served_alone_bytes(&over)? - 1, + ..Default::default() + }; + let sink = Sink::default(); + let mut server = server(options, Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, 900)?; + connect(&mut server, &mut [&mut peer])?; + peer.send_reliable("schema", put_stamped_bytes("o1", "big", vec![7; 101], "yesterday")?)?; + assert_eq!( + poll_until_rejected_or_stored(&mut server, &mut peer, &sink, 1)?, + Some(CultMeshRudpRejectionReason::StoredAtNotStamp) + ); + let mut stamped = client(server.local_addr()?, 901)?; + connect(&mut server, &mut [&mut stamped])?; + stamped.send_reliable("schema", put_stamped_bytes("o2", "big", vec![7; 101], "2026-06-25T00:00:00Z")?)?; + assert!(matches!( + poll_until_rejected_or_stored(&mut server, &mut stamped, &sink, 1)?, + Some(CultMeshRudpRejectionReason::DocumentUnservable { .. }) + )); + assert!(sink.0.lock().unwrap().receipts.is_empty()); + Ok(()) +} + +/// An ungranted peer is refused `write_not_authorized` before its stamp is judged, on a receipt session and on a +/// legacy one, and the authority is asked about the write. +#[test] +fn an_ungranted_peer_is_refused_for_authority_before_its_stamp_is_judged() -> Result<()> { + let sink = Sink::denying(&["secret"]); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut receipt_peer = client(server.local_addr()?, 950)?; + connect(&mut server, &mut [&mut receipt_peer])?; + send_reliable(&mut receipt_peer, &receipt_hello())?; + receipt_peer.send_reliable("schema", put_stamped_bytes("a1", "secret", vec![1], "yesterday")?)?; + let answers = answers_after(&mut server, &mut receipt_peer, 1)?; + assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::WriteNotAuthorized), Some("a1".into()))); + assert_eq!(sink.0.lock().unwrap().authorized, vec!["a1".to_string()]); + + let mut legacy_peer = client(server.local_addr()?, 951)?; + connect(&mut server, &mut [&mut legacy_peer])?; + legacy_peer.send_reliable("schema", put_stamped_bytes("a2", "secret", vec![1], "yesterday")?)?; + assert!(matches!( + poll_until_rejected_or_stored(&mut server, &mut legacy_peer, &sink, 1)?, + Some(CultMeshRudpRejectionReason::SinkRefused(_)) + )); + assert!(sink.0.lock().unwrap().receipts.is_empty()); + Ok(()) +}