Skip to content

Close the connection on an empty plaintext or a malformed JSON message - #280

Merged
kahrendt merged 2 commits into
mainfrom
malformed-json-close
Nov 19, 2026
Merged

kahrendt merged 2 commits into
mainfrom
malformed-json-close

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Spec #321 (messaging.md "Binary Message ID Structure"): "A binary message whose AEAD plaintext is empty is a protocol error: the receiver MUST close the connection. So is a message with ID 0 whose body is not a valid UTF-8 JSON object with a type string and a payload object." An empty plaintext closed only because decrypt() returned 0 for both it and an AEAD failure. An ID 0 frame with no body, an unparsable body, a non-object root, a missing or non-string type and a missing payload were logged and dropped, and nothing checked UTF-8.

Change

  • NoiseSession::decrypt() and NoiseTransport::decrypt_in_place() return std::optional<size_t>, so an authentic empty plaintext is reported as malformed instead of as an AEAD failure.
  • process_json_message() checks every ID 0 body, on admitted and nursery connections, pairing and in-band re-handshake alike: is_valid_utf8(), then ParsedJsonMessage::parse() (now JsonParseResult), which rejects a non-object root and anything but whitespace after it, then has_message_envelope(). A failure closes silently. A well-formed message of an unrecognized type is still ignored (messaging.md "Communication").
  • An object over the parser's own limits (NoMemory, TooDeep) is the client's limit, not the peer's error: logged and dropped, connection kept, as before. Server messages have no nesting cap, so closing there could reject valid JSON. A body whose first non-whitespace byte is not { is rejected before parsing, so a non-object root closes however deep it goes.
  • A malformed body closes through ConnectionManager::close_on_malformed_message(), which ends a pairing attempt in progress (not one already acked by pair-finalize) as UNKNOWN, so on_pairing_aborted() still fires for a pairing message whose envelope is broken.
  • An empty WebSocket message, single- or multi-frame, closes in any phase: it is never a valid handshake frame or Noise message.
  • The trailing-bytes reader is shared with normalize_support_object_json(). It also applies to the handshake text frames, so a server/init or noise/handshake with trailing non-whitespace now aborts the handshake; the server/init prologue is still the raw bytes.
  • Remaining leniency, named in the comment: ArduinoJson accepts single quotes and unquoted keys (and raw control bytes inside strings).

Tests

  • EncryptedLifecycle.AMalformedJsonBodyClosesTheConnection: one row per broken condition (empty, invalid UTF-8, not JSON, truncated, array and null roots, an array root past the nesting limit, no or non-string type, no or non-object payload, trailing bytes, a second value); controls for a known type, an unknown type with multi-byte UTF-8, trailing whitespace, and a too-deep payload that is dropped but keeps the connection.
  • PairingStateMachineTest.AMalformedMessageEndsThePairingAttemptItCloses: a malformed body sent through process_json_message() during an attempt reports UNKNOWN; controls with no attempt and after the pair-finalize ack report none.
  • NoiseTransport.AnEmptyPlaintextClosesSilently and InboundReceive.AnEmptyMultiFrameMessageClosesTheConnection, each with a one-byte control; the pre-admission zero-length row now expects a close.
  • Mutants: dropping the empty-plaintext, empty-message, UTF-8, type, payload or trailing-bytes check, treating TooDeep as malformed, dropping instead of closing, dropping the leading-{ check, closing directly instead of through close_on_malformed_message(), or reporting an abort after the finalize ack each fails a test. Two survivors are equivalent: decrypt mapping an empty plaintext to an AEAD failure (both close silently), and parse() accepting a non-object root (the envelope check rejects it).

Not covered: NoMemory has no host test (it needs heap exhaustion); stack budgets were not re-derived; not built for ESP.

messaging.md "Binary Message ID Structure" makes an empty AEAD plaintext,
and an ID 0 message whose body is not a valid UTF-8 JSON object with a type
string and a payload object, a protocol error the receiver MUST close on.
An empty plaintext closed only because decrypt() returned 0 for both it and
an AEAD failure; an empty, unparsable, non-object or envelope-less JSON body
was logged and dropped, and nothing checked UTF-8.

- decrypt() returns std::optional<size_t>, so an authentic empty plaintext
  is reported as malformed rather than as an AEAD failure.
- process_json_message() checks every ID 0 body: UTF-8, then a parse that
  rejects a non-object root and anything but whitespace after it, then the
  type and payload envelope. A failure closes silently; a well-formed
  message of an unrecognized type is still ignored.
- A body over the parser's own limits (allocator exhausted, nesting limit)
  is the client's limit, not the peer's error: dropped, connection kept.
- An empty WebSocket message, single- or multi-frame, closes in any phase.
- The trailing-bytes check is shared with the application role's support
  object normalizer, and also applies to the handshake text frames.
@kahrendt
kahrendt marked this pull request as ready for review November 19, 2026 12:07
@kahrendt
kahrendt requested an adaptive review from Copilot November 19, 2026 12:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Raw control characters remain accepted in JSON strings, deeply nested array roots evade connection closure, and malformed pairing envelopes can suppress the required pairing-aborted notification.

7 open issues
What changed in this PR

Hardens Sendspin’s receive path so empty messages and malformed ID-0 JSON bodies close the connection, while parser resource-limit failures remain drop-only.

Changes:

  • Distinguishes authentic empty plaintext from decryption failure.
  • Validates UTF-8, JSON envelopes, and trailing bytes using shared parsing infrastructure.
  • Adds malformed-message coverage and updates receive-path documentation.
File Description
tests/​test_noise_transport.cpp Covers empty plaintext and empty WebSocket messages.
tests/​test_noise_rehandshake.cpp Adapts decryption assertions to optional lengths.
tests/​test_json_arena.cpp Uses explicit JSON parse results.
tests/​test_encrypted_lifecycle.cpp Adds malformed-body rejection and accepting controls.
src/​protocol.cpp Adds message-envelope validation.
src/​protocol_messages.h Declares the envelope validator.
src/​platform/​json_arena.h Adds a shared reader and classified parse results.
src/​noise_transport.h Updates decryption and malformed-message contracts.
src/​noise_transport.cpp Marks empty plaintext as malformed.
src/​noise_session.h Changes decryption to return an optional length.
src/​noise_session.cpp Separates authentication failure from empty plaintext.
src/​noise_handshake.cpp Adopts stricter shared parsing.
src/​connection.h Removes obsolete empty-JSON dispatch documentation.
src/​connection.cpp Closes empty messages and dispatches empty JSON for validation.
src/​client_dispatch.cpp Validates JSON bodies and closes malformed messages.
src/​application_role.h Reuses the shared trailing-byte reader.
docs/​internals.md Documents receive-path validation and close behavior.

Review effort: Max (adaptive)

Comment thread src/client_dispatch.cpp Resolved
Comment thread src/platform/json_arena.h Resolved
Comment thread src/platform/json_arena.h Resolved
Comment thread docs/internals.md Resolved
Comment thread src/client_dispatch.cpp Resolved
Comment thread src/connection.cpp Resolved
Comment thread src/noise_transport.cpp Resolved
…tempt a malformed message closes

- ParsedJsonMessage::parse() rejects a body whose first non-whitespace
  byte is not '{' before parsing, so a deeply nested array or other
  non-object root closes rather than being dropped as over the limits.
- A malformed JSON body closes through
  ConnectionManager::close_on_malformed_message(), which ends a pairing
  attempt in progress (not one already acked by pair-finalize) as UNKNOWN,
  so on_pairing_aborted() still fires; the close stays silent.
- An empty plaintext resets the reassembly state like every other
  malformed exit.
- Docs: route_inbound_message() names the empty-message close, the
  internals receive diagram points at process_json_message() instead of
  restating its rules, and on_pairing_aborted()'s UNKNOWN covers any
  malformed message during the attempt.
- Drops the payload-less server/pair-init parser test; that shape now
  closes at the envelope check.
@kahrendt
kahrendt enabled auto-merge (squash) November 19, 2026 14:44
@kahrendt
kahrendt merged commit fc7efc2 into main Nov 19, 2026
16 checks passed
@kahrendt
kahrendt deleted the malformed-json-close branch November 19, 2026 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants