mirror of
https://github.com/block/buzz.git
synced 2026-11-25 18:52:52 +00:00
broker: reject explicit null so absence has exactly one spelling
The strict response envelope could be walked straight past with JSON `null`.
`deny_unknown_fields` constrains *which* members may appear, not what they may
hold, and `#[serde(default)] Option<T>` maps an explicit `null` to `None` --
which is indistinguishable from absent. The per-status match reads absence as
"this status does not carry that member", so
{"status":"failed","action":null,"outcome":null}
and a succeeded response with `"error":null` both parsed as well-formed and
skipped the contradiction check entirely. `validate()` returned Ok on an
envelope that contradicts itself. The previous commit closed the value-shaped
version of this hole and left the null-shaped one open, which is the same class
of bug one spelling short.
The fix is a rule rather than three checks: **no optional member anywhere in
this contract accepts `null`.** Nothing here emits one -- `skip_serializing_if`
omits the member instead -- so `null` was never a value this contract defined,
only one serde happened to accept. A shared `absent_or_valued` deserializer
rejects it, applied to all 17 optional members across the response envelope,
every args type, and `MessagePage::next_cursor`.
Rejecting outright beats tracking presence beside the value, which was the other
option. Presence tracking preserves the ambiguity and moves the decision to
every reader: each one then has to answer what a present-but-null member meant,
and the answer only has to be gotten wrong once. With one spelling of absence
there is no such question -- and a host implementer never has to guess whether
`{"limit": null}` means the default or no limit, because it means neither.
Two members did not need the helper and are documented as such rather than
changed: `mentionsOnly` and `replayed` are plain `bool`, and `null` already
fails as a type error. Both rejections are pinned by test anyway, so the doc
cannot drift and a later change to `Option<bool>` -- which would need the guard
-- fails loudly.
Audited the other two strict layers for the same path, both clean: the request
envelope's flattened `ActionArgs` is adjacently tagged, so `action` and `args`
are required and reject `null` as a type error; `StrictEvent`'s seven canonical
members are all required, and each rejects `null` on type. Reported either way
per the review request.
Coverage is derived, not listed. `no_member_of_any_payload_accepts_an_explicit_null`
walks every JSON-pointer path in the real serialized fixtures -- every action,
every outcome, nested members and array elements included -- and nulls each in
turn, so an optional field added later is covered without anyone remembering to.
It asserts the untouched fixture parses first, since a probe that rejects for the
wrong reason proves nothing.
`a_status_incompatible_member_is_rejected_as_null_not_only_as_a_value` carries
the original repro, which the fixtures structurally cannot reach: a serialized
response never contains the member its own status forbids. Both assert on the
parse rather than on `validate()` -- a malformed envelope should never become a
value that some caller has to remember to check.
Falsified four ways against 5e2879a72, since one passing guard is no evidence
for the others: reverting the response envelope, the args optionals, or
`nextCursor` each fails a named test, and neutering the helper to accept `null`
fails both.
Reported by ss-bugs-00 on #6742. Addresses the interface half of #6467.
Signed-off-by: ss-dev-00 <a02c4e0850e5e612b4ddf95dbe2f5c56467cf27c6552203bc833ff438fb31971@buzz.block.builderlab.xyz>
Co-authored-by: Bradley Axen <baxen@squareup.com>
Signed-off-by: Bradley Axen <baxen@squareup.com>
This commit is contained in:
@@ -3,15 +3,17 @@
|
||||
//!
|
||||
//! Every type here is `deny_unknown_fields`, so a credential or environment map
|
||||
//! smuggled into a payload fails to deserialize rather than reaching an
|
||||
//! executor. Each carries a `validated()` returning a normalized copy; the
|
||||
//! shared validators live in the [parent module](super).
|
||||
//! executor. Optional members mean absent by being **omitted**: an explicit
|
||||
//! `null` is rejected, so there is one spelling of absence and no member can be
|
||||
//! present-but-empty. Each carries a `validated()` returning a normalized copy;
|
||||
//! the shared validators live in the [parent module](super).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
channel, content, cursor, event_id, is_false, limit, mentions, optional, required, respond_to,
|
||||
validate_slug, Action, PubkeyHex, DEFAULT_PAGE_LIMIT, MAX_ABOUT_CHARS, MAX_EMOJI_CHARS,
|
||||
MAX_NAME_CHARS, MAX_PROMPT_CHARS, MAX_SCALAR_CHARS,
|
||||
absent_or_valued, channel, content, cursor, event_id, is_false, limit, mentions, optional,
|
||||
required, respond_to, validate_slug, Action, PubkeyHex, DEFAULT_PAGE_LIMIT, MAX_ABOUT_CHARS,
|
||||
MAX_EMOJI_CHARS, MAX_NAME_CHARS, MAX_PROMPT_CHARS, MAX_SCALAR_CHARS,
|
||||
};
|
||||
use crate::SdkError;
|
||||
|
||||
@@ -29,12 +31,19 @@ pub struct ChannelReadArgs {
|
||||
/// Channel to read.
|
||||
pub channel_id: String,
|
||||
/// Narrow to one thread by its root event.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub root_event_id: Option<String>,
|
||||
/// Narrow to messages mentioning the requester — the wake path.
|
||||
///
|
||||
/// The requester is never named; see [`crate::broker::BrokerRequest`] on why no body
|
||||
/// names its own subject.
|
||||
///
|
||||
/// A plain `bool`, so it needs no explicit null guard: `null` already fails
|
||||
/// as a type error rather than defaulting to `false`.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub mentions_only: bool,
|
||||
/// Opaque position to resume from, as returned in [`super::outcomes::MessagePage::next_cursor`].
|
||||
@@ -46,13 +55,21 @@ pub struct ChannelReadArgs {
|
||||
/// second, and it would commit every future host to one relay ordering
|
||||
/// strategy. The host defines ordering and cursor stability, including
|
||||
/// whether a cursor stays valid across restarts.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub cursor: Option<String>,
|
||||
/// Maximum events to return, capped at [`super::MAX_PAGE_LIMIT`].
|
||||
///
|
||||
/// Absent means [`super::DEFAULT_PAGE_LIMIT`], not "unbounded": see
|
||||
/// [`Self::effective_limit`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -209,13 +226,25 @@ impl ReactionAddArgs {
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ProfileSetArgs {
|
||||
/// Replacement display name.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub display_name: Option<String>,
|
||||
/// Replacement bio.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub about: Option<String>,
|
||||
/// Replacement avatar URL.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub picture: Option<String>,
|
||||
}
|
||||
|
||||
@@ -312,16 +341,32 @@ pub struct AgentsCreateArgs {
|
||||
/// Instructions the new agent runs with.
|
||||
pub system_prompt: String,
|
||||
/// Preferred harness id; the host refuses a runtime it cannot resolve.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub runtime: Option<String>,
|
||||
/// Inference provider.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub provider: Option<String>,
|
||||
/// Model identifier, interpreted relative to the runtime.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub model: Option<String>,
|
||||
/// Inbound author gate mode; absent = the host's owner-only default.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub respond_to: Option<String>,
|
||||
}
|
||||
|
||||
@@ -352,22 +397,46 @@ pub struct AgentsUpdateArgs {
|
||||
/// Which agent to patch.
|
||||
pub target: AgentTarget,
|
||||
/// Rename the agent.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub display_name: Option<String>,
|
||||
/// Replacement instructions.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub system_prompt: Option<String>,
|
||||
/// Harness id to pin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub runtime: Option<String>,
|
||||
/// Inference provider.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub provider: Option<String>,
|
||||
/// Model identifier.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub model: Option<String>,
|
||||
/// Inbound author gate mode.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub respond_to: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,54 @@ fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
}
|
||||
|
||||
/// Deserialize an optional member that may be **absent but never `null`**.
|
||||
///
|
||||
/// Every optional member in this contract means "absent" by being absent. JSON
|
||||
/// `null` is a second spelling of the same thing that no serializer here emits —
|
||||
/// `skip_serializing_if` omits the member instead — so accepting it would define
|
||||
/// a wire value the contract does not.
|
||||
///
|
||||
/// That is not merely untidy. `#[serde(default)] Option<T>` maps an explicit
|
||||
/// `null` to `None`, which is *indistinguishable from absent* to any code
|
||||
/// downstream. A reader that decides something from absence — the status match in
|
||||
/// [`crate::broker::BrokerResponse`], or
|
||||
/// [`args::ChannelReadArgs::effective_limit`] choosing [`DEFAULT_PAGE_LIMIT`] —
|
||||
/// then silently treats a member the sender did supply as one it did not. In the
|
||||
/// response envelope that was a real hole: `{"status":"failed","outcome":null}`
|
||||
/// parsed as a plain failure, so the per-status contradiction check never fired.
|
||||
///
|
||||
/// Rejecting `null` outright is stronger than tracking presence beside the value
|
||||
/// and cheaper to reason about: there is then exactly one way to say "absent",
|
||||
/// and no layer has to decide what a present-but-empty member meant. Applied
|
||||
/// uniformly, it also means a host implementer never has to guess whether
|
||||
/// `{"limit": null}` means the default or no limit — it means neither, it is a
|
||||
/// malformed request.
|
||||
///
|
||||
/// Used with `#[serde(default, deserialize_with = "…")]`: serde calls this only
|
||||
/// when the key is present, so reaching the `None` arm below means the member was
|
||||
/// present and `null`. `deny_unknown_fields` stays in force alongside it.
|
||||
///
|
||||
/// Not every member needs this. A required member of a non-`Option` type already
|
||||
/// rejects `null` as a type error — which covers the request envelope's flattened
|
||||
/// `action`/`args` (adjacently tagged, both required), every canonical member of
|
||||
/// the strict event intermediary, and the two `bool` members here. The guard is
|
||||
/// only load-bearing where `Option` plus `default` would otherwise make `null`
|
||||
/// and absent the same value.
|
||||
pub(super) fn absent_or_valued<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
use serde::de::Error as _;
|
||||
|
||||
match Option::<T>::deserialize(deserializer)? {
|
||||
Some(value) => Ok(Some(value)),
|
||||
None => Err(D::Error::custom(
|
||||
"must not be null; omit the member to mean absent",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn required(value: &str, label: &str, max: usize) -> Result<String, SdkError> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
//! event-publishing actions all return [`EventPublished`]. Every type is
|
||||
//! `deny_unknown_fields` with its exact wire key set pinned by test, which is
|
||||
//! what enforces the no-secret rule — see the [contract docs](crate::broker).
|
||||
//! Optional members are absent by omission; an explicit `null` is rejected.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
channel, cursor, event_id, required, Action, PubkeyHex, MAX_NAME_CHARS, MAX_PAGE_LIMIT,
|
||||
absent_or_valued, channel, cursor, event_id, required, Action, PubkeyHex, MAX_NAME_CHARS,
|
||||
MAX_PAGE_LIMIT,
|
||||
};
|
||||
use crate::SdkError;
|
||||
use nostr::{Event, EventId, Kind, PublicKey, Tags, Timestamp};
|
||||
@@ -141,7 +143,11 @@ pub struct MessagePage {
|
||||
/// Absent when the host has nothing further, which is how a caller learns
|
||||
/// to stop rather than by comparing lengths against a limit it may not have
|
||||
/// set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "absent_or_valued",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,15 @@
|
||||
//! inside each event object — a host cannot ship a `secretKey` beside `sig` and
|
||||
//! have it silently trimmed.
|
||||
//!
|
||||
//! A third hole was subtler and is closed the same way: `deny_unknown_fields`
|
||||
//! constrains *which* members may appear, not what they may hold, and
|
||||
//! `#[serde(default)] Option<T>` accepts an explicit `null` as `None` —
|
||||
//! indistinguishable from absent. An envelope that decides its shape from absence
|
||||
//! therefore accepted `{"status":"failed","outcome":null}` as a plain failure. So
|
||||
//! **no optional member anywhere in this contract accepts `null`**: nothing here
|
||||
//! emits one, absence is spelled by omission, and a `null` is a malformed payload
|
||||
//! rather than a second spelling with its own interpretation.
|
||||
//!
|
||||
//! Two limits are worth stating. A `String` field can physically hold secret
|
||||
//! text, so keeping secrets out of message content and error messages is host
|
||||
//! policy this contract cannot enforce. And nothing stops a host from *holding*
|
||||
@@ -109,6 +118,7 @@ use crate::SdkError;
|
||||
pub mod actions;
|
||||
pub mod client;
|
||||
|
||||
use actions::absent_or_valued;
|
||||
pub use actions::{
|
||||
Action, ActionArgs, ActionOutcome, AgentTarget, AgentsCreateArgs, AgentsCreateOutcome,
|
||||
AgentsDeleteArgs, AgentsDeleteOutcome, AgentsUpdateArgs, AgentsUpdateOutcome, BrokerMessage,
|
||||
@@ -601,6 +611,9 @@ pub struct BrokerResponse {
|
||||
#[serde(flatten)]
|
||||
pub result: BrokerResult,
|
||||
/// True when this response replays a previously recorded outcome.
|
||||
///
|
||||
/// A plain `bool`, so it needs no explicit null guard: `null` already fails
|
||||
/// as a type error rather than defaulting to `false`.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub replayed: bool,
|
||||
}
|
||||
@@ -614,6 +627,15 @@ pub struct BrokerResponse {
|
||||
/// missing `outcome` under `succeeded` — is a parse failure rather than a field
|
||||
/// nobody reads.
|
||||
///
|
||||
/// Those members deserialize through [`absent_or_valued`] rather than plain
|
||||
/// `#[serde(default)]`, because the status match below reads `None` as *absent*
|
||||
/// and `#[serde(default)] Option<T>` also produces `None` for an explicit
|
||||
/// `null`. Without it, `{"status":"failed","action":null,"outcome":null}` — or a
|
||||
/// succeeded response with `"error":null` — parsed as well-formed and skipped the
|
||||
/// contradiction check entirely. `null` is now rejected for these members whether
|
||||
/// or not the declared status admits them, so there is exactly one way for a
|
||||
/// member to be absent.
|
||||
///
|
||||
/// `outcome` is held as a `serde_json::Value` and re-deserialized under its
|
||||
/// action tag, so this reader is JSON-specific. That is not a narrowing: the HTTP
|
||||
/// binding in [`client`] declares `application/json`, and JSON is the only
|
||||
@@ -625,11 +647,11 @@ struct WireResponse {
|
||||
protocol_version: u16,
|
||||
request_id: String,
|
||||
status: String,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "absent_or_valued")]
|
||||
action: Option<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "absent_or_valued")]
|
||||
outcome: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "absent_or_valued")]
|
||||
error: Option<BrokerError>,
|
||||
#[serde(default)]
|
||||
replayed: bool,
|
||||
|
||||
@@ -461,6 +461,213 @@ fn a_request_envelope_rejects_anything_outside_its_exact_key_set() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every JSON-pointer path to an object member reachable in `value`, including
|
||||
/// members nested inside arrays, so a null-injection table cannot miss one.
|
||||
fn member_paths(value: &serde_json::Value, prefix: &str, out: &mut Vec<String>) {
|
||||
match value {
|
||||
serde_json::Value::Object(map) => {
|
||||
for (key, child) in map {
|
||||
// Escape per RFC 6901, so a key containing `/` or `~` still
|
||||
// addresses the member it names.
|
||||
let escaped = key.replace('~', "~0").replace('/', "~1");
|
||||
let path = format!("{prefix}/{escaped}");
|
||||
out.push(path.clone());
|
||||
member_paths(child, &path, out);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(items) => {
|
||||
for (index, child) in items.iter().enumerate() {
|
||||
member_paths(child, &format!("{prefix}/{index}"), out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bug this guards: `#[serde(default)] Option<T>` maps an explicit `null` to
|
||||
/// `None`, which is indistinguishable from *absent*. The response envelope decides
|
||||
/// its shape from absence, so `{"status":"failed","action":null,"outcome":null}`
|
||||
/// and a succeeded response with `"error":null` both parsed as well-formed and
|
||||
/// skipped the per-status contradiction check entirely — a malformed envelope
|
||||
/// validating `Ok`.
|
||||
///
|
||||
/// The rule adopted in response is uniform and therefore checkable: **no member
|
||||
/// anywhere in this contract accepts an explicit `null`.** Nothing here emits one
|
||||
/// (`skip_serializing_if` omits instead), so `null` is a second spelling of
|
||||
/// "absent" that the contract simply does not define. One spelling means no layer
|
||||
/// has to decide what a present-but-null member meant.
|
||||
///
|
||||
/// This walks the real fixtures rather than a hand-written list of members, so an
|
||||
/// optional field added later is covered without anyone remembering to add it
|
||||
/// here.
|
||||
#[test]
|
||||
fn no_member_of_any_payload_accepts_an_explicit_null() {
|
||||
let keys = Keys::generate();
|
||||
|
||||
// Requests: every action, with every optional member populated.
|
||||
for args in action_fixtures() {
|
||||
let request = BrokerRequest::new("req-1", args).expect("fixture request builds");
|
||||
let valid = serde_json::to_value(&request).expect("request serializes");
|
||||
// The untouched fixture must parse, or nulling members below would
|
||||
// "reject" for a reason that has nothing to do with null.
|
||||
assert_eq!(
|
||||
serde_json::from_value::<BrokerRequest>(valid.clone()).expect("fixture parses"),
|
||||
request,
|
||||
);
|
||||
|
||||
let mut paths = Vec::new();
|
||||
member_paths(&valid, "", &mut paths);
|
||||
assert!(
|
||||
paths.len() > 1,
|
||||
"fixture should expose several members: {valid}"
|
||||
);
|
||||
for path in paths {
|
||||
let mut json = valid.clone();
|
||||
*json.pointer_mut(&path).expect("path addresses a member") = serde_json::Value::Null;
|
||||
assert!(
|
||||
serde_json::from_value::<BrokerRequest>(json.clone()).is_err(),
|
||||
"request with null at \"{path}\" must not deserialize: {json}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Responses: every outcome, plus both error-carrying statuses.
|
||||
let mut results: Vec<BrokerResult> = outcome_fixtures(&keys)
|
||||
.into_iter()
|
||||
.map(BrokerResult::succeeded)
|
||||
.collect();
|
||||
results.push(BrokerResult::failed(BrokerError::new(
|
||||
BrokerErrorCode::ActionFailed,
|
||||
"runtime not installed",
|
||||
)));
|
||||
results.push(BrokerResult::indeterminate(BrokerError::new(
|
||||
BrokerErrorCode::OutcomeUnknown,
|
||||
"host restarted mid-execution",
|
||||
)));
|
||||
|
||||
for result in results {
|
||||
let response = BrokerResponse::new("req-1", result).replayed();
|
||||
let valid = serde_json::to_value(&response).expect("response serializes");
|
||||
assert_eq!(
|
||||
serde_json::from_value::<BrokerResponse>(valid.clone()).expect("fixture parses"),
|
||||
response,
|
||||
);
|
||||
|
||||
let mut paths = Vec::new();
|
||||
member_paths(&valid, "", &mut paths);
|
||||
for path in paths {
|
||||
let mut json = valid.clone();
|
||||
*json.pointer_mut(&path).expect("path addresses a member") = serde_json::Value::Null;
|
||||
assert!(
|
||||
serde_json::from_value::<BrokerResponse>(json.clone()).is_err(),
|
||||
"response with null at \"{path}\" must not deserialize: {json}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// The two `bool` members carry no explicit guard, because `null` already
|
||||
// fails as a type error rather than defaulting to `false`. Pin that, so the
|
||||
// docs saying so cannot drift and so a later change to `Option<bool>` — which
|
||||
// *would* need the guard — fails here.
|
||||
let mut json = serde_json::json!({
|
||||
"type": BROKER_REQUEST_TYPE,
|
||||
"protocolVersion": 1,
|
||||
"requestId": "req-1",
|
||||
"actionVersion": 1,
|
||||
"action": "channel.read",
|
||||
"args": { "channelId": CHANNEL, "mentionsOnly": serde_json::Value::Null },
|
||||
});
|
||||
assert!(
|
||||
serde_json::from_value::<BrokerRequest>(json.clone()).is_err(),
|
||||
"a null mentionsOnly must not deserialize: {json}"
|
||||
);
|
||||
json = serde_json::json!({
|
||||
"type": BROKER_RESULT_TYPE,
|
||||
"protocolVersion": 1,
|
||||
"requestId": "req-1",
|
||||
"status": "failed",
|
||||
"error": { "code": "action_failed", "message": "no" },
|
||||
"replayed": serde_json::Value::Null,
|
||||
});
|
||||
assert!(
|
||||
serde_json::from_value::<BrokerResponse>(json.clone()).is_err(),
|
||||
"a null replayed must not deserialize: {json}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The exact repro that reached `Ok`: a member the declared status does not admit,
|
||||
/// supplied as `null` rather than as a value. The fixtures above cannot cover this
|
||||
/// — a serialized response never contains the member its status forbids — so each
|
||||
/// status-incompatible member is injected here by name.
|
||||
///
|
||||
/// This is the case that makes the null hole a contract bug rather than a
|
||||
/// tidiness one: these envelopes contradict themselves, and before the fix
|
||||
/// `validate()` returned `Ok(())` on all of them.
|
||||
#[test]
|
||||
fn a_status_incompatible_member_is_rejected_as_null_not_only_as_a_value() {
|
||||
let succeeded = || {
|
||||
serde_json::json!({
|
||||
"type": BROKER_RESULT_TYPE,
|
||||
"protocolVersion": 1,
|
||||
"requestId": "req-1",
|
||||
"status": "succeeded",
|
||||
"action": "agents.delete",
|
||||
"outcome": { "agentPubkey": PUBKEY, "displayName": "Gone" },
|
||||
})
|
||||
};
|
||||
let failed = || {
|
||||
serde_json::json!({
|
||||
"type": BROKER_RESULT_TYPE,
|
||||
"protocolVersion": 1,
|
||||
"requestId": "req-1",
|
||||
"status": "failed",
|
||||
"error": { "code": "action_failed", "message": "no" },
|
||||
})
|
||||
};
|
||||
|
||||
let mut cases: Vec<(String, serde_json::Value)> = Vec::new();
|
||||
|
||||
// `error` is the member a success does not admit.
|
||||
let mut json = succeeded();
|
||||
json["error"] = serde_json::Value::Null;
|
||||
cases.push(("null error beside a success".into(), json));
|
||||
|
||||
// `action` and `outcome` are the members the two failure statuses do not
|
||||
// admit — individually and together, since the original report showed both.
|
||||
for status in ["failed", "indeterminate"] {
|
||||
let base = || {
|
||||
let mut json = failed();
|
||||
json["status"] = serde_json::json!(status);
|
||||
if status == "indeterminate" {
|
||||
json["error"] = serde_json::json!({ "code": "outcome_unknown", "message": "?" });
|
||||
}
|
||||
json
|
||||
};
|
||||
for member in ["action", "outcome"] {
|
||||
let mut json = base();
|
||||
json[member] = serde_json::Value::Null;
|
||||
cases.push((format!("null {member} beside a {status}"), json));
|
||||
}
|
||||
let mut json = base();
|
||||
json["action"] = serde_json::Value::Null;
|
||||
json["outcome"] = serde_json::Value::Null;
|
||||
cases.push((format!("null action and outcome beside a {status}"), json));
|
||||
}
|
||||
|
||||
for (what, json) in cases {
|
||||
let parsed = serde_json::from_value::<BrokerResponse>(json.clone());
|
||||
// Assert on the parse, not on `validate()`: a response that parses and
|
||||
// then fails validation would still have to be *reported* by a caller
|
||||
// that remembered to validate. Rejecting at the boundary means a
|
||||
// malformed envelope never becomes a value at all.
|
||||
assert!(
|
||||
parsed.is_err(),
|
||||
"{what} must not deserialize, but parsed as {:?} which validates {:?}: {json}",
|
||||
parsed.as_ref().ok(),
|
||||
parsed.as_ref().map(BrokerResponse::validate).ok(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Envelope rejection ──────────────────────────────────────────────────────
|
||||
|
||||
/// Unknown names must not resolve, and neither must the *mechanism* names this
|
||||
|
||||
Reference in New Issue
Block a user