Skip to content

Commit 5e2879a

Browse files
ss-dev-00baxen
andcommitted
broker: make the contract's strictness hold at every layer it claims to
Four bug-pass findings on #6742, all one shape: a rule the contract states in prose but does not enforce at some layer, so the layer above it decides. **status/code contradictions.** `Indeterminate` carrying a known pre-dispatch code passed validation, so `execute` returned Ok for a response contradicting itself: `unauthenticated` means the host refused before running anything — a known fate — while `indeterminate` means the fate is unknown. A caller reading the status would reconcile side effects that provably never happened. We already rejected the mirror case, `outcome_unknown` under `failed`. Rather than add the reverse one-off check, the pairing is now a closed table. `BrokerErrorCode::may_be_failed` and `may_be_indeterminate` are exhaustive matches with no wildcard, so a new code cannot inherit an answer — it forces a decision at both ends. `indeterminate` admits only `outcome_unknown` and `internal`; a host fault mid-execution is the one legitimate "I don't know", and every other code names a fate the host knows. The rationale lives once, in the `BrokerErrorCode` docs, and `BrokerResponse::validate` consults the predicates instead of restating them. **A read page bounded only by the protocol cap.** `ActionOutcome::validate` never sees the request, so it could only check `MAX_PAGE_LIMIT`: a host could answer a one-message read with five hundred, within the cap and still an overrun of what was asked. `validate_for` now applies the request's own number, the one place both halves are in scope. An absent `limit` is held to the new `DEFAULT_PAGE_LIMIT` (100) rather than treated as consent to an unbounded page — the cap is what a host may ever send, the default is what it may send unasked, so the two constants are deliberately different numbers. **A response envelope that was silently non-strict.** `#[serde(flatten)]` disables `deny_unknown_fields` — serde cannot combine them — and the note saying so concluded strictness was enforced elsewhere. It was not: the envelope accepted and discarded an unknown top-level key, and accepted an `error` beside a succeeded outcome or an `outcome` beside a failure, dropping whichever half it could not represent. Deserialization now routes through a private strict wire form with an exact key set per status; serialization is untouched, so the wire format does not change. The request envelope has the same `flatten` and was checked for the same hole: it does not have one, because `ActionArgs` is adjacently tagged and contributes exactly `action` and `args`, leaving `deny_unknown_fields` in force. That is now pinned by test rather than assumed. **Events could smuggle members past the schema.** `nostr`'s `Event` deserializer accepts and discards unknown members, so a genuinely signed event could carry an extra `secretKey` and parse clean — the no-secret rule stopping at the envelope instead of reaching inside it. `BrokerMessage` now deserializes through a `deny_unknown_fields` intermediary with exactly the seven canonical NIP-01 members, and the module docs state that the invariant extends inside event objects. The exact-key-set table now covers both envelopes and the error payload, not just args and outcomes: a key set nobody pins is a key set a field can be added to. A new test parses raw bytes through a transport, because the strict-envelope and strict-event guards live in `Deserialize` and the typed test double could never reach them — it hands back a value that was never on a wire. Each guard was falsified separately against 5116ca2, since one passing guard is no evidence for the others: reverting the limit check, the strict envelope, the strict event, collapsing `DEFAULT_PAGE_LIMIT` onto the cap, dropping `deny_unknown_fields` from the request envelope, and adding a field to the response envelope each fail a different named test. Reported by ss-bugs-02 on #6742. Addresses the interface half of #6467. Signed-off-by: ss-dev-00 <a02c4e0850e5e612b4ddf95dbe2f5c56467cf27c6552203bc833ff438fb31971@buzz.block.builderlab.xyz> Co-authored-by: Bradley Axen <[email protected]> Signed-off-by: Bradley Axen <[email protected]>
1 parent 5116ca2 commit 5e2879a

6 files changed

Lines changed: 919 additions & 64 deletions

File tree

‎crates/buzz-sdk/src/broker/actions/args.rs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use serde::{Deserialize, Serialize};
1010

1111
use super::{
1212
channel, content, cursor, event_id, is_false, limit, mentions, optional, required, respond_to,
13-
validate_slug, Action, PubkeyHex, MAX_ABOUT_CHARS, MAX_EMOJI_CHARS, MAX_NAME_CHARS,
14-
MAX_PROMPT_CHARS, MAX_SCALAR_CHARS,
13+
validate_slug, Action, PubkeyHex, DEFAULT_PAGE_LIMIT, MAX_ABOUT_CHARS, MAX_EMOJI_CHARS,
14+
MAX_NAME_CHARS, MAX_PROMPT_CHARS, MAX_SCALAR_CHARS,
1515
};
1616
use crate::SdkError;
1717

@@ -49,11 +49,26 @@ pub struct ChannelReadArgs {
4949
#[serde(default, skip_serializing_if = "Option::is_none")]
5050
pub cursor: Option<String>,
5151
/// Maximum events to return, capped at [`super::MAX_PAGE_LIMIT`].
52+
///
53+
/// Absent means [`super::DEFAULT_PAGE_LIMIT`], not "unbounded": see
54+
/// [`Self::effective_limit`].
5255
#[serde(default, skip_serializing_if = "Option::is_none")]
5356
pub limit: Option<u32>,
5457
}
5558

5659
impl ChannelReadArgs {
60+
/// The page size a response to these arguments is held to.
61+
///
62+
/// Explicit `limit` when set, otherwise [`super::DEFAULT_PAGE_LIMIT`].
63+
/// Omitting a limit asks the host to choose a sensible page, not to send an
64+
/// unbounded one, so there is always a number a response can be checked
65+
/// against — which is what
66+
/// [`crate::broker::BrokerResponse::validate_for`] does.
67+
#[must_use]
68+
pub fn effective_limit(&self) -> u32 {
69+
self.limit.unwrap_or(DEFAULT_PAGE_LIMIT)
70+
}
71+
5772
/// Read a whole channel from the host's default window.
5873
#[must_use]
5974
pub fn channel(channel_id: impl Into<String>) -> Self {

‎crates/buzz-sdk/src/broker/actions/mod.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ pub const MAX_MENTIONS: usize = 50;
5353
/// Maximum events a single read may return.
5454
pub const MAX_PAGE_LIMIT: u32 = 500;
5555

56+
/// Events a read returns when the request sets no explicit `limit`.
57+
///
58+
/// A caller that omits `limit` is not agreeing to an unbounded page, so this is
59+
/// the number a response is held to in that case — see
60+
/// [`crate::broker::BrokerResponse::validate_for`]. It is deliberately well
61+
/// under [`MAX_PAGE_LIMIT`]: the cap is what a host may ever send, this is what
62+
/// it may send unasked.
63+
pub const DEFAULT_PAGE_LIMIT: u32 = 100;
64+
5665
/// Maximum accepted length of a read cursor, in bytes.
5766
pub const MAX_CURSOR_LEN: usize = 256;
5867

‎crates/buzz-sdk/src/broker/actions/outcomes.rs‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,30 @@ use super::{
1212
channel, cursor, event_id, required, Action, PubkeyHex, MAX_NAME_CHARS, MAX_PAGE_LIMIT,
1313
};
1414
use crate::SdkError;
15-
use nostr::Event;
15+
use nostr::{Event, EventId, Kind, PublicKey, Tags, Timestamp};
16+
17+
/// The seven canonical members of a Nostr event object, and nothing else.
18+
///
19+
/// `nostr`'s own `Event` deserializer accepts and *discards* unknown members, so
20+
/// deserializing straight into it would put read results outside the strict-wire
21+
/// rule that every other payload in this contract obeys: a host could ship an
22+
/// extra `secretKey` member inside an event and nothing would object. Routing
23+
/// through a `deny_unknown_fields` intermediary restores the rule at the one
24+
/// place the contract does not own the type.
25+
///
26+
/// Field names are the wire names from NIP-01 (`created_at`, not `createdAt`) —
27+
/// this is the event's own encoding, not ours to rename.
28+
#[derive(Deserialize)]
29+
#[serde(deny_unknown_fields)]
30+
struct StrictEvent {
31+
id: EventId,
32+
pubkey: PublicKey,
33+
created_at: Timestamp,
34+
kind: Kind,
35+
tags: Tags,
36+
content: String,
37+
sig: nostr::secp256k1::schnorr::Signature,
38+
}
1639

1740
/// One message returned by a read: the signed Nostr event, verbatim.
1841
///
@@ -27,10 +50,34 @@ use nostr::Event;
2750
/// The wire form is the event's own JSON, so this adds no envelope of its own.
2851
/// Ancestry and mentions are exposed as derived accessors rather than sibling
2952
/// fields, so there is nothing that can disagree with the signed bytes.
30-
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53+
///
54+
/// Deserialization is **strict**, via a private `deny_unknown_fields`
55+
/// intermediary: an event object carrying any member beyond the canonical seven
56+
/// is rejected rather than quietly trimmed, which is what keeps read results
57+
/// inside the same no-secret rule as every other payload here. Serialization is
58+
/// the event's own, so the wire form is unchanged.
59+
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3160
#[serde(transparent)]
3261
pub struct BrokerMessage(pub Event);
3362

63+
impl<'de> Deserialize<'de> for BrokerMessage {
64+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
65+
where
66+
D: serde::Deserializer<'de>,
67+
{
68+
let strict = StrictEvent::deserialize(deserializer)?;
69+
Ok(Self(Event::new(
70+
strict.id,
71+
strict.pubkey,
72+
strict.created_at,
73+
strict.kind,
74+
strict.tags,
75+
strict.content,
76+
strict.sig,
77+
)))
78+
}
79+
}
80+
3481
impl BrokerMessage {
3582
/// The signed event.
3683
#[must_use]

‎crates/buzz-sdk/src/broker/client.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,8 @@ pub enum BrokerTransportError {
8686
detail: String,
8787
},
8888
/// An envelope arrived but did not validate against the request that was
89-
/// sent — wrong `requestId`, wrong action, or a malformed outcome.
89+
/// sent — wrong `requestId`, wrong action, a malformed outcome, or a status
90+
/// contradicting its own error code.
9091
///
9192
/// Produced by [`ValidatedResponse::validate`], which every
9293
/// [`BrokerClientExt::execute`] call runs. A host that answers something
@@ -127,9 +128,10 @@ impl ValidatedResponse {
127128
/// # Errors
128129
///
129130
/// Returns [`BrokerTransportError::MalformedResponse`] when the response
130-
/// does not correlate, carries an outcome for a different action, or asserts
131-
/// a malformed identifier. A response that fails here is not a host verdict
132-
/// — nothing can be concluded about side effects from it.
131+
/// does not correlate, carries an outcome for a different action, asserts a
132+
/// malformed identifier, or pairs a status with a code that contradicts it.
133+
/// A response that fails here is not a host verdict — nothing can be
134+
/// concluded about side effects from it.
133135
pub fn validate(
134136
response: BrokerResponse,
135137
request: &PreparedRequest,

0 commit comments

Comments
 (0)