Skip to content

Commit 7c853e0

Browse files
ss-dev-00baxen
andcommitted
broker: give every identity one spelling, and the result one wire door
Two P2 review findings on #6742, both reproduced from an out-of-crate consumer before being fixed, and each fix falsified by reverting it. 1. Identity spellings broke correlation (bugs-00, correlate.rs:42). `channel()` validated a UUID with `Uuid::parse_str` and returned the caller's spelling untouched, while `correlate_identities` compared the request's and the outcome's `channelId` as strings. An uppercase request against a host's canonical lowercase echo of the same channel therefore failed `validate_for` — a *correct* answer rejected, which is worse than the mismatch the check exists to catch, because it makes a working host unusable. Fixed as a class, not as a UUID case. The finding named case; the validator also admits the unhyphenated, `{braced}`, and `urn:uuid:` forms, and all four froze un-canonicalized. Hex has the same property. So: - Canonicalize where a value enters. `channel()` now returns the lowercase hyphenated form, and every member holding an identity canonicalizes on deserialize too (`channel_id`, `hex64_field`, `absent_or_valued_hex64`). The wire is the door no `validated()` covers: those fields are public `String`s, so a parsed payload reaches a caller without passing through any validator. Both doors delegate to the same function, so they cannot drift. - Compare parsed identities, not bytes. `correlate_identities` parses each `channelId` as a `Uuid`; pubkeys are compared as `PubkeyHex`, which lowercases in its only constructor and its serde path. The two guards are deliberately independent and asserted separately, so neither is the only thing holding. A genuinely different identity is still rejected. Coverage is derived as well as enumerated: one test walks the real fixtures, re-spells every identity-named member, and requires the canonical value back, so a member added later with the wrong `deserialize_with` fails without anyone extending a list. 2. `BrokerResult` was a second, lax wire door (bugs-00, mod.rs:586). The envelope's strict reader requires the exact key set the declared status admits, but the exported result type also derived its own reader, and that one accepted and dropped arbitrary siblings: `status: failed` beside an `error` and a `secretKey`, or a succeeded result beside an `error`. A consumer parsing the result type directly got an `Ok` value whose complete wire shape had never been vetted, from bytes that fail through the envelope. Decision: take the type off the wire — it is no longer `Deserialize`. The alternative, its own strict reader, would be a second copy of the per-status contradiction rules, and two copies of a strictness check drift; this hole exists precisely because one layer's strictness did not reach another's. Removing the door leaves one implementation and nothing to keep in sync. Nothing is lost: a bare `{"status": …}` object is not a payload this contract defines, and the whole module is new in this PR, so it had no consumers. `Serialize` is retained — it produces the envelope's flattened wire form — so the wire form is unchanged and this is a read-side restriction only. The absence is pinned at compile time, since a runtime test cannot call a `Deserialize` impl that does not exist: a probe resolves to an inherent method only when the bound holds, and it is first asserted against two types that *do* have readers, so a broken probe cannot pass silently. The contract docs gain a section on identity spelling, `validate_for`'s nine-row table records that comparison is on parsed identities, and the strictness section records the one-door rule. Also: adding the identity docs pushed mod.rs to 1,021 lines, past the repo's 1,000-line ceiling, so the strict response reader moved to `broker/wire.rs` (mod 913 / wire 121) — a pure move, same treatment `correlate.rs` already got. The derived-coverage test matches identity members case-insensitively. An earlier revision of it matched the suffix `"EventId"` exactly, which silently skipped the outcome member spelled `eventId` and left every response-side wire door unpinned — mutation testing caught it by removing the outcome `channelId` door and surviving. It now walks response fixtures as well as request ones, and floors the two directions separately, because a single combined floor would be satisfied by the request side alone. Validation: 299 tests pass in buzz-sdk (295 before), workspace clippy `-D warnings` clean, fmt clean, `cargo doc` warning-free with the new section anchor verified in the generated HTML, every touched file under 1,000 lines. Seven mutations, one per guard, each killed by a named test. `cargo test --workspace` is green except `test_120s_timeout` / `test_cancellation_immediate` in buzz-pair-relay, a pre-existing flake reproduced 2-in-8 on unmodified main at c5166f2 where no broker module exists. 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]> Signed-off-by: ss-dev-00 <a02c4e0850e5e612b4ddf95dbe2f5c56467cf27c6552203bc833ff438fb31971@buzz.block.builderlab.xyz>
1 parent 559eb30 commit 7c853e0

7 files changed

Lines changed: 746 additions & 137 deletions

File tree

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@
1111
use serde::{Deserialize, Serialize};
1212

1313
use super::{
14-
absent_or_valued, channel, content, cursor, event_id, is_false, limit, mentions, optional,
15-
required, respond_to, validate_slug, Action, PubkeyHex, DEFAULT_PAGE_LIMIT, MAX_ABOUT_CHARS,
16-
MAX_EMOJI_CHARS, MAX_NAME_CHARS, MAX_PROMPT_CHARS, MAX_SCALAR_CHARS,
14+
absent_or_valued, absent_or_valued_hex64, channel, channel_id, content, cursor, event_id,
15+
hex64_field, is_false, limit, mentions, optional, required, respond_to, validate_slug, Action,
16+
PubkeyHex, DEFAULT_PAGE_LIMIT, MAX_ABOUT_CHARS, MAX_EMOJI_CHARS, MAX_NAME_CHARS,
17+
MAX_PROMPT_CHARS, MAX_SCALAR_CHARS,
1718
};
1819
use crate::SdkError;
1920

@@ -29,11 +30,12 @@ use crate::SdkError;
2930
#[serde(rename_all = "camelCase", deny_unknown_fields)]
3031
pub struct ChannelReadArgs {
3132
/// Channel to read.
33+
#[serde(deserialize_with = "channel_id")]
3234
pub channel_id: String,
3335
/// Narrow to one thread by its root event.
3436
#[serde(
3537
default,
36-
deserialize_with = "absent_or_valued",
38+
deserialize_with = "absent_or_valued_hex64",
3739
skip_serializing_if = "Option::is_none"
3840
)]
3941
pub root_event_id: Option<String>,
@@ -124,6 +126,7 @@ impl ChannelReadArgs {
124126
#[serde(rename_all = "camelCase", deny_unknown_fields)]
125127
pub struct MessagePostArgs {
126128
/// Channel to post in.
129+
#[serde(deserialize_with = "channel_id")]
127130
pub channel_id: String,
128131
/// Message body.
129132
pub content: String,
@@ -154,8 +157,10 @@ impl MessagePostArgs {
154157
#[serde(rename_all = "camelCase", deny_unknown_fields)]
155158
pub struct MessageReplyArgs {
156159
/// Channel containing the parent.
160+
#[serde(deserialize_with = "channel_id")]
157161
pub channel_id: String,
158162
/// Event being replied to.
163+
#[serde(deserialize_with = "hex64_field")]
159164
pub reply_to_event_id: String,
160165
/// Reply body.
161166
pub content: String,
@@ -187,8 +192,10 @@ impl MessageReplyArgs {
187192
#[serde(rename_all = "camelCase", deny_unknown_fields)]
188193
pub struct ReactionAddArgs {
189194
/// Channel containing the target.
195+
#[serde(deserialize_with = "channel_id")]
190196
pub channel_id: String,
191197
/// Event being reacted to.
198+
#[serde(deserialize_with = "hex64_field")]
192199
pub target_event_id: String,
193200
/// Reaction payload — an emoji or a `:shortcode:`.
194201
pub reaction: String,
@@ -335,6 +342,7 @@ impl AgentTarget {
335342
#[serde(rename_all = "camelCase", deny_unknown_fields)]
336343
pub struct AgentsCreateArgs {
337344
/// Channel the new agent is attached to.
345+
#[serde(deserialize_with = "channel_id")]
338346
pub channel_id: String,
339347
/// Name for the new agent.
340348
pub display_name: String,

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

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,11 +278,45 @@ fn optional(value: Option<&String>, label: &str, max: usize) -> Result<Option<St
278278
value.map(|value| required(value, label, max)).transpose()
279279
}
280280

281+
/// Validate a channel id and return its **canonical** spelling.
282+
///
283+
/// A UUID has several legal spellings — `Uuid::parse_str` accepts uppercase, the
284+
/// unhyphenated 32-character form, `{braced}`, and `urn:uuid:` — and they all
285+
/// name the same channel. Returning the caller's spelling would freeze a request
286+
/// body that disagrees with the host's canonical echo of the same identity, and
287+
/// the response correlation in
288+
/// [`crate::broker::BrokerResponse::validate_for`] would then reject a correct
289+
/// answer. So this returns the lowercase hyphenated form and nothing else: one
290+
/// identity, one spelling, chosen at the only point that sees the value before it
291+
/// is frozen.
292+
///
293+
/// This is the same treatment [`PubkeyHex::parse`] gives the other identity in
294+
/// this contract, and it is applied at both doors — the validators, and the
295+
/// [`channel_id`] deserializer — so a value cannot reach a caller
296+
/// un-canonicalized whether it was built or parsed.
281297
fn channel(value: &str) -> Result<String, SdkError> {
282298
let value = required(value, "channel", 128)?;
283299
uuid::Uuid::parse_str(&value)
284-
.map_err(|_| SdkError::InvalidInput(format!("invalid channel UUID: {value}")))?;
285-
Ok(value)
300+
.map(|id| id.as_hyphenated().to_string())
301+
.map_err(|_| SdkError::InvalidInput(format!("invalid channel UUID: {value}")))
302+
}
303+
304+
/// Deserialize a `channelId`, canonicalizing it and rejecting a non-UUID.
305+
///
306+
/// The wire is the one door a validator cannot cover: every args and outcome
307+
/// field holding a channel id is a public `String`, so a payload parsed from
308+
/// JSON reaches a caller without passing through any `validated()`. Delegating
309+
/// to [`channel`] means the wire form and the constructed form are canonicalized
310+
/// by the same code, so the two cannot drift, and a malformed channel id never
311+
/// becomes a value at all — the same rule the no-null guard follows.
312+
pub(super) fn channel_id<'de, D>(deserializer: D) -> Result<String, D::Error>
313+
where
314+
D: serde::Deserializer<'de>,
315+
{
316+
use serde::de::Error as _;
317+
318+
let raw = String::deserialize(deserializer)?;
319+
channel(&raw).map_err(D::Error::custom)
286320
}
287321

288322
fn event_id(value: &str, label: &str) -> Result<String, SdkError> {
@@ -295,6 +329,47 @@ fn event_id(value: &str, label: &str) -> Result<String, SdkError> {
295329
Ok(value.to_ascii_lowercase())
296330
}
297331

332+
/// Deserialize a 64-hex identifier (`eventId`, `dTag`), lowercasing it and
333+
/// rejecting anything that is not 64 hex characters.
334+
///
335+
/// Hex admits two spellings of one identifier, so this is the [`channel_id`] rule
336+
/// applied to the contract's other multi-spelling identities. See that function
337+
/// for why the wire needs a door of its own.
338+
///
339+
/// The label is generic because serde reports which member failed; naming the
340+
/// member here as well would be a second copy to keep true.
341+
pub(super) fn hex64_field<'de, D>(deserializer: D) -> Result<String, D::Error>
342+
where
343+
D: serde::Deserializer<'de>,
344+
{
345+
use serde::de::Error as _;
346+
347+
let raw = String::deserialize(deserializer)?;
348+
event_id(&raw, "identifier").map_err(D::Error::custom)
349+
}
350+
351+
/// [`hex64_field`] for an optional member: `null` is still rejected.
352+
///
353+
/// A dedicated function rather than a composition of the two guards, because
354+
/// `deserialize_with` takes one function and both rules — reject `null`,
355+
/// canonicalize the value — apply to the same member. Reaching the `None` arm
356+
/// means the key was present and `null`; see [`absent_or_valued`].
357+
pub(super) fn absent_or_valued_hex64<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
358+
where
359+
D: serde::Deserializer<'de>,
360+
{
361+
use serde::de::Error as _;
362+
363+
match Option::<String>::deserialize(deserializer)? {
364+
Some(raw) => Ok(Some(
365+
event_id(&raw, "identifier").map_err(D::Error::custom)?,
366+
)),
367+
None => Err(D::Error::custom(
368+
"must not be null; omit the member to mean absent",
369+
)),
370+
}
371+
}
372+
298373
fn content(value: &str) -> Result<String, SdkError> {
299374
if value.trim().is_empty() {
300375
return Err(SdkError::InvalidInput("content must not be empty".into()));

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

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

1212
use super::{
13-
absent_or_valued, channel, cursor, event_id, required, Action, PubkeyHex, MAX_NAME_CHARS,
14-
MAX_PAGE_LIMIT,
13+
absent_or_valued, channel, channel_id, cursor, event_id, hex64_field, required, Action,
14+
PubkeyHex, MAX_NAME_CHARS, MAX_PAGE_LIMIT,
1515
};
1616
use crate::SdkError;
1717
use nostr::{Event, EventId, Kind, PublicKey, Tags, Timestamp};
@@ -156,6 +156,7 @@ pub struct MessagePage {
156156
#[serde(rename_all = "camelCase", deny_unknown_fields)]
157157
pub struct EventPublished {
158158
/// The published event's id (hex).
159+
#[serde(deserialize_with = "hex64_field")]
159160
pub event_id: String,
160161
/// The published event's kind.
161162
pub kind: u32,
@@ -175,6 +176,7 @@ pub struct StorageAddress {
175176
/// Event kind holding the record.
176177
pub kind: u32,
177178
/// Derived `d` tag (64 hex characters).
179+
#[serde(deserialize_with = "hex64_field")]
178180
pub d_tag: String,
179181
}
180182

@@ -192,6 +194,7 @@ pub struct AgentsCreateOutcome {
192194
/// The new agent's name as stored.
193195
pub display_name: String,
194196
/// Channel the agent was attached to.
197+
#[serde(deserialize_with = "channel_id")]
195198
pub channel_id: String,
196199
}
197200

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

Lines changed: 51 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,64 @@ use super::{ActionArgs, ActionOutcome, AgentTarget, PubkeyHex, SdkError};
1313
/// public entry point a host author reads. It is documented there rather than
1414
/// here so there is one copy to keep true.
1515
///
16+
/// # Identities are compared parsed, never as strings
17+
///
18+
/// Both identities in this contract have more than one legal spelling: a UUID
19+
/// may be uppercase, unhyphenated, braced, or `urn:uuid:`-prefixed, and hex may
20+
/// be either case. A byte comparison would therefore reject a *correct* answer
21+
/// whenever the caller and the host spelled the same identity differently —
22+
/// which is a worse failure than the one this function exists to catch, because
23+
/// it makes a working host unusable.
24+
///
25+
/// Canonicalization at the validators and at the wire doors (see
26+
/// [`channel_id`][super::actions::channel_id]) means both sides normally arrive
27+
/// canonical already. This function does not rely on that: it parses each side
28+
/// into the identity's own type and compares those, so a spelling variant that
29+
/// reached here by any route still correlates. The two guards are deliberately
30+
/// independent — neither is load-bearing alone.
31+
///
1632
/// The match below is exhaustive over [`ActionArgs`], so adding an action is a
1733
/// compile error here rather than a silent default to "not compared".
1834
pub(super) fn correlate_identities(
1935
args: &ActionArgs,
2036
outcome: &ActionOutcome,
2137
) -> Result<(), SdkError> {
22-
/// Compare one echoed identity, naming the field in the error.
23-
fn same(field: &str, requested: &str, returned: &str) -> Result<(), SdkError> {
38+
/// Compare two channel ids as UUIDs, so two spellings of one channel match.
39+
///
40+
/// An unparseable id on either side is a mismatch rather than an error:
41+
/// `validate`/`validated` already reject a malformed channel id with a
42+
/// precise message, and duplicating that verdict here would report a
43+
/// correlation failure for what is really a malformed payload.
44+
fn same_channel(requested: &str, returned: &str) -> Result<(), SdkError> {
45+
let parse = |value: &str| uuid::Uuid::parse_str(value).ok();
46+
match (parse(requested), parse(returned)) {
47+
(Some(requested_id), Some(returned_id)) if requested_id == returned_id => Ok(()),
48+
_ => Err(mismatch("channelId", requested, returned)),
49+
}
50+
}
51+
52+
/// Compare two pubkeys.
53+
///
54+
/// [`PubkeyHex`] lowercases in [`PubkeyHex::parse`], which is its only
55+
/// constructor and also its `Deserialize` path, so a value of this type is
56+
/// already canonical however it was built. Comparing the typed values is
57+
/// therefore the parsed comparison, not a string one.
58+
fn same_pubkey(requested: &PubkeyHex, returned: &PubkeyHex) -> Result<(), SdkError> {
2459
if requested == returned {
2560
return Ok(());
2661
}
27-
Err(SdkError::InvalidInput(format!(
62+
Err(mismatch(
63+
"agentPubkey",
64+
requested.as_str(),
65+
returned.as_str(),
66+
))
67+
}
68+
69+
/// The error every mismatch reports, naming the field and both spellings.
70+
fn mismatch(field: &str, requested: &str, returned: &str) -> SdkError {
71+
SdkError::InvalidInput(format!(
2872
"response {field} \"{returned}\" does not match the requested \"{requested}\""
29-
)))
73+
))
3074
}
3175

3276
/// The pubkey a target names immutably, if it names one.
@@ -39,25 +83,17 @@ pub(super) fn correlate_identities(
3983

4084
match (args, outcome) {
4185
(ActionArgs::AgentsCreate(args), ActionOutcome::AgentsCreate(outcome)) => {
42-
same("channelId", &args.channel_id, &outcome.channel_id)
86+
same_channel(&args.channel_id, &outcome.channel_id)
4387
}
4488
(ActionArgs::AgentsUpdate(args), ActionOutcome::AgentsUpdate(outcome)) => {
4589
match targeted(&args.target) {
46-
Some(requested) => same(
47-
"agentPubkey",
48-
requested.as_str(),
49-
outcome.agent_pubkey.as_str(),
50-
),
90+
Some(requested) => same_pubkey(requested, &outcome.agent_pubkey),
5191
None => Ok(()),
5292
}
5393
}
5494
(ActionArgs::AgentsDelete(args), ActionOutcome::AgentsDelete(outcome)) => {
5595
match targeted(&args.target) {
56-
Some(requested) => same(
57-
"agentPubkey",
58-
requested.as_str(),
59-
outcome.agent_pubkey.as_str(),
60-
),
96+
Some(requested) => same_pubkey(requested, &outcome.agent_pubkey),
6197
None => Ok(()),
6298
}
6399
}

0 commit comments

Comments
 (0)