Skip to content

fix: bound DISCONNECT/AUTH reason code by packet length, not buffer length - #162

Merged
robertsLando merged 11 commits into
mqttjs:masterfrom
spokodev:fix/disconnect-auth-packet-boundary
Nov 19, 2026
Merged

robertsLando merged 11 commits into
mqttjs:masterfrom
spokodev:fix/disconnect-auth-packet-boundary

Conversation

@spokodev

@spokodev spokodev commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

_parseDisconnect and _parseAuth decide whether a Reason Code and Property
Length are present using this._list.length — the number of bytes left in the
whole running parse buffer, which includes any following pipelined packet —
instead of this.packet.length, the current packet's Remaining Length.

So a spec-valid minimal DISCONNECT/AUTH that is not the last packet in the
parse() buffer reads the next packet's bytes as its reason code (then a bogus
Property Length), aborting the whole parse:

const parser = mqtt.parser({ protocolVersion: 5 })
parser.parse(Buffer.from([0xE0, 0x00, 0xC0, 0x00])) // DISCONNECT (len 0) + PINGREQ
// throws "Invalid disconnect reason code"  — should emit [disconnect rc=0, pingreq]

parser.parse(Buffer.from([0xE0, 0x01, 0x80, 0xC0, 0x00])) // DISCONNECT rc=0x80 + PINGREQ
// throws "Cannot parse property code type"

parser.parse(Buffer.from([0xF0, 0x00, 0xC0, 0x00])) // AUTH (len 0) + PINGREQ
// throws "Invalid auth reason code"

A standalone minimal packet works only because _list.length happens to equal 0
when it is the last thing in the buffer, which is why generate() round-trips
(it always emits the longer E0 02 00 00 form) and existing tests never caught it.

Per MQTT 5.0 §3.14.2.2.1 (DISCONNECT) and §3.15.2.2.1 (AUTH): the Reason Code may
be omitted when it is 0x00 with no properties (Remaining Length 0), and "if
the Remaining Length is less than 2, then there is no Property Length and the
value of 0 is used."

Fix

Gate the Reason Code on packet.length > 0 and the properties on
packet.length >= 2, in both methods — mirroring _parseConfirmation, which
already bounds its reads with packet.length. _parseByte advances the read
position without touching packet.length, so it stays the packet's Remaining
Length throughout. Standalone minimal packets (where the two lengths coincide)
are unchanged.

Test

Added a parser test feeding a minimal DISCONNECT (len 0 and len 1) and AUTH
followed by a PINGREQ, asserting both packets are emitted. Fails on main,
passes with the fix; the full suite is green (994 passing).

Behaviour changes (release note)

Inside a packet the whole payload is already buffered, so a read past the
Remaining Length - or past a declared Property Length - is a Malformed Packet
(MQTT-5 §4.13), never "wait for more data". Inputs that previously parsed by
borrowing bytes from the next pipelined packet, or from the packet's own body,
now emit an error and stop. Consumers such as MQTT.js tear down the
connection on a parser error, so this is not a patch-level change.

Knowingly reverses #101. That PR added the implied reason code for a v5
CONNACK with Remaining Length 1, pinned by Version 5 CONNACK test 1. A
CONNACK always carries Connect Acknowledge Flags and a reason code (MQTT-5
§3.2.2), and defaulting the missing byte to 0 tells the client an
unauthenticated connection was accepted - so Remaining Length below 2 is
now rejected. The 2-byte v4-format CONNACK a v4-only server sends when it
refuses a v5 CONNECT is unchanged (Version 4 CONACK in Version 5 mode), as is
every CONNACK at Remaining Length 3 or more. A broker emitting the 1-byte form
connects today and will be disconnected after this.

Other inputs that used to parse and now error:

  • a Property Length, property value, or messageId running past the packet or
    past its property block - previously a silent null / -1, or a value taken
    from the next packet;
  • a truncated property-length varint - previously an empty property block with
    an implied reasonCode: 0;
  • a v5 PUBLISH, SUBACK or UNSUBACK omitting the mandatory Property Length byte
    (MQTT-5 §3.3.2.3 / §3.9.2.1.1 / §3.11.2.1.1);
  • a SUBACK carrying no reason codes - previously emitted as granted: []. This
    one applies to 3.1.1 as well as 5.0: §3.9.3 requires a return code per
    subscription in both, and the guard sits outside the version branch. The
    matching UNSUBACK guard is 5.0 only, because a 3.1.1 UNSUBACK has no payload;
  • a SUBSCRIBE or UNSUBSCRIBE carrying no topic filters ([MQTT-3.8.3-3],
    [MQTT-3.10.3-2]), all versions - previously emitted with an empty list.

Going the other way, the pipelined DISCONNECT/AUTH/CONNACK forms this PR is
named for now parse instead of failing with Invalid <cmd> reason code.

The parser also recovers after an error for the first time. _resetState
left _pos stale, so on master any mid-packet error wedged the parser
permanently - the next packet's Remaining Length was computed from the stale
offset, and the stream never resynced. Measured on dd17095: a malformed
CONNECT followed by a valid PUBLISH yields 2 errors, 0 packets, and 11 bytes
stuck in the buffer forever. That is fixed here.

Error messages: new failures use Malformed <cmd>, <reason>, and the Remaining
Length varint error joins them. Messages that existed before and are not part of
this bug class keep their text.

Because this PR rewrites several error strings, matching on err.message is no
longer a stable contract. Every parser error now carries err.code and
err.cmd, declared as ParserError in types/index.d.ts - match on those.
err.code is one of mqtt.parserErrorCodes: 'UNSUPPORTED_PROTOCOL_VERSION'
for a CONNECT with an unknown protocol version (a v5 server may answer CONNACK
0x84), 'MALFORMED_PACKET' for every other protocol violation.

`_parseDisconnect` and `_parseAuth` decided whether a Reason Code and
Property Length were present using `this._list.length` — the bytes left
in the whole parse buffer, which includes any following pipelined packet
— instead of `this.packet.length`, the current packet's Remaining Length.

So a spec-valid minimal DISCONNECT/AUTH that is not the last packet in the
`parse()` buffer read the next packet's bytes as its reason code (and then
a bogus Property Length), aborting the whole parse:

  parser({ protocolVersion: 5 }).parse(Buffer.from([0xE0, 0x00, 0xC0, 0x00]))
  // disconnect (remaining length 0) + pingreq
  // threw "Invalid disconnect reason code" instead of emitting both packets

Per MQTT 5.0 §3.14 / §3.15 the Reason Code may be omitted when it is 0x00
with no properties (Remaining Length 0), and "if the Remaining Length is
less than 2, there is no Property Length". Gate the reason code on
`packet.length > 0` and the properties on `packet.length >= 2`, mirroring
`_parseConfirmation`, which already bounds its reads by `packet.length`.
Standalone minimal packets (where the two lengths coincide) are unchanged.
@robertsLando robertsLando changed the title Bound DISCONNECT/AUTH reason code by packet length, not buffer length fix: bound DISCONNECT/AUTH reason code by packet length, not buffer length Jul 27, 2026

@robertsLando robertsLando left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Review summary

Verdict: ship with minor changes. The fix is correct and uses the codebase's own idiom — _parseConfirmation (parser.js:502,524) already bounds the same decision with packet.length > 2 / > 3. Four lines, no new abstraction, thresholds match MQTT-5 §3.14.2.2.1 / §3.15.2.2.1, and it ships with a regression test. 680/680 tests pass on the branch.

Everything below is either "extend the fix to its siblings" or pre-existing bugs this PR sits next to.

Top 3 risks

  1. _parseConnack has the identical bug and is left unfixed — the PR reads as "this bug class is handled" when it isn't.
  2. _parseProperties is still bounded by the wire-declared length, not packet.length, so DISCONNECT/AUTH with Remaining Length ≥ 2 still read the following packet's bytes — silently, no error.
  3. _parseDisconnect's _emitError has no return, so one malformed packet emits two error events.

Theme — one root cause behind almost every finding

The parser has two length concepts: _list.length (bytes left in the whole running buffer, spanning pipelined packets) and packet.length (this packet's Remaining Length). _parseString:612 and _parseBuffer:632 already bound by both. _parseByte, _parseNum, _parse4ByteNum, _parseVarByteNum and _parseProperties bound by _list.length only — so every caller has to re-open-code its own guard (> 2, > 3, and now > 0, >= 2 twice). This PR patches two call sites correctly; the primitive is still wrong, which is why the siblings below are still broken. Pushing the packet.length clamp down into those primitives would close the whole class at once.


Findings outside the diff

Major — parser.js:284-291,297 — _parseConnack has the same bug, unfixed. Uses the same this._list.length conflation, then calls _parseProperties() unconditionally. Verified at this PR's head:

// v5 CONNACK, remaining length 1, followed by PINGREQ
parser.parse(Buffer.from([0x20, 0x01, 0x00, 0xC0, 0x00]))
// -> connack.reasonCode === 192  — that's the PINGREQ's header byte

parser.parse(Buffer.from([0x20, 0x02, 0x00, 0x00, 0xC0, 0x00]))
// -> error 'Cannot parse property code type', stream dies, 4 bytes stranded

v4 returnCode is affected the same way. Consistency argues for folding it in, since the title describes the bug class rather than one function — otherwise worth a line in the description saying CONNACK is out of scope.

Major — parser.js:29-35 — _resetState() does not reset _pos. Only _parsePayload:97 and _newPacket:805 do. After any mid-packet error the stale _pos is used as padding in the next packet's _parseVarByteNum. Verified: after an error leaving _pos === 3, a following valid PUBLISH [48,10,0,4,'test','test'] computes packet.length === 116 — silently swallowed, then wedged waiting for bytes that never arrive. Pre-existing, and it is the answer to "can the parser recover for the next parse() call": no.

Minor — parser.js:167,182 — _parseConnect, same class. Gates on this._pos >= this._list.length, so a truncated CONNECT followed by pipelined data reads the next packet's bytes as protocolVersion/flags instead of erroring Packet too short.


Back-compat — clean

Single-packet buffers are byte-identical before/after (verified DISCONNECT/AUTH at RL 0/1/2). Previously-erroring inputs now parse; nothing that parsed before now errors; reasonCode presence is unchanged. Semver-patch is defensible — the old output was bytes stolen from the next packet, not a shape anyone could depend on.

FYI

  • No maximum packet size is enforced anywhere in parser.js; a declared Remaining Length of VARBYTEINT_MAX buffers up to 256 MiB before _parsePayload runs. Pre-existing, not DISCONNECT/AUTH-specific.
  • Performance impact is nil: both operands are O(1) property reads (bl's .length is incrementally maintained, not computed by walking _bufs), and benchmarks/parse.js only exercises PUBLISH.

Coverage

Specialists run: correctness, security, DRY/codebase-fit, design/API/back-compat, tests, performance. Clean on: performance. Not run: operability, readability (no files in their lanes). Reviewed against a worktree at 3dd49ba; all reproductions above were executed there, not inferred.

Comment thread parser.js Resolved
Comment thread parser.js Resolved
Comment thread parser.js Resolved
Comment thread test.js Resolved
Comment thread test.js Resolved
…operty length to packet boundary

- _parseDisconnect: return after the invalid-reason-code error so it no
  longer falls through and emits a second error (mirrors _parseAuth).
- _parseProperties: accept an optional packet boundary; DISCONNECT/AUTH
  pass their remaining length so a declared property length that overruns
  the packet errors instead of reading the following pipelined packet.
@spokodev

Copy link
Copy Markdown
Contributor Author

Thanks for the deep review — genuinely useful. Pushed the two in-scope changes:

  • _parseDisconnect now returns on the invalid reason code, so it no longer falls through into the property block and emits a second error. Matches _parseAuth.
  • _parseProperties takes an optional boundary; _parseDisconnect/_parseAuth pass their remaining length, so a declared property length that overruns the packet now errors (Property length exceeds packet length) instead of reading the next pipelined packet. That closes the RL ≥ 2 over-read for both DISCONNECT and AUTH.

Full suite green (686/686, standard clean). Two new tests cover the single-error and the boundary cases. One existing test used an over-long DISCONNECT property length to reach Cannot parse property code type; it now hits the boundary guard first, so I nudged its input to stay within remaining length and keep exercising that path.

On the rest: you're right that the clean fix is pushing the packet.length clamp down into the primitives (_parseByte/_parseNum/_parseProperties) rather than re-guarding at each call site — that would also cover _parseConnack, _parseConnect, and the _resetState _pos recovery you found. I kept this PR to DISCONNECT/AUTH to match its title. Happy to open a separate follow-up PR for the primitive-level clamp + the CONNACK/CONNECT/_pos items (with your repros as tests) if you'd like — just say the word.

@robertsLando

Copy link
Copy Markdown
Member

@spokodev please do it here and not in a follow up

Extends the DISCONNECT/AUTH boundary fix to the whole over-read class, as the
review asked. The primitives (_parseByte, _parseNum, _parse4ByteNum,
_parseVarByteNum, _parseProperties) bounded reads by _list.length — the whole
running buffer across pipelined packets — so every caller had to re-open-code a
packet.length guard. Push the clamp down into the primitives (payload phase
only; header phase is detected by packet.length === -1), matching what
_parseString/_parseBuffer already do.

Also fixes the siblings the review flagged:
- _parseConnack read reasonCode/properties by _list.length, so a pipelined
  packet's byte leaked in as the reason code (e.g. reasonCode === 192 from a
  following PINGREQ). Bound by packet.length.
- _parseConnect gated the version and connect-flags reads on _list.length,
  reading a following packet's bytes on a truncated CONNECT instead of erroring
  'Packet too short'. Bound by packet.length.
- _resetState did not reset _pos, so after a mid-packet error the stale _pos
  corrupted the next packet's _parseVarByteNum. Reset it.

_parseProperties now self-clamps on packet.length, dropping the explicit
boundary parameter the DISCONNECT/AUTH sites passed. Single-packet buffers stay
byte-identical; only boundary-crossing over-reads change (they now error or read
0). Adds pipelining regression tests for CONNACK, CONNECT, the _pos recovery,
and a DISCONNECT/AUTH boundary matrix, each asserting the trailing packet
survives with no bytes left over.
@spokodev

Copy link
Copy Markdown
Contributor Author

Done in this PR. Pushed the packet.length clamp down into the primitives (_parseByte/_parseNum/_parse4ByteNum/_parseVarByteNum/_parseProperties), payload-phase only — header phase is detected by packet.length === -1, so parsing the Remaining Length itself is untouched. _parseProperties now self-clamps and the DISCONNECT/AUTH boundary argument is gone.

Plus the three siblings, each with a pipelining regression test:

  • _parseConnack — bound reasonCode/properties by packet.length. [0x20,0x01,0x00,0xC0,0x00] now yields connack rc=0 + PINGREQ instead of rc=192.
  • _parseConnect — version/flags gates use packet.length; a truncated CONNECT before a pipelined packet errors Packet too short.
  • _resetState — resets _pos, so a mid-packet error no longer strands it into the next packet's _parseVarByteNum.

Boundary matrix extended to DISCONNECT/AUTH at RL 0/1/2/>2, each followed by a PINGREQ that must survive with parse() === 0. Single-packet buffers stay byte-identical; 732/732 green, standard clean. Added the MQTT-5 §3.14.2.2.1 / §3.15.2.2.1 citations too.

Extends the pipelining cases from 3 to all 8 cells (DISCONNECT and AUTH at
remaining length 0, 1, 2 and above) and asserts the parse() return value, so
a case that leaves the trailing packet unconsumed fails.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@spokodev

spokodev commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Pushed the two remaining test items in 9ab9880.

Boundary matrix — 3 cells to 8. DISCONNECT and AUTH at remaining length 0, 1, 2 and above, each followed by a PINGREQ. Against upstream master, rl0 and rl1 fail for both packet types (Invalid disconnect reason code, Cannot parse property code type) while rl2 and rl7 pass — so the first four cells are the regression and the last four are guards on the packet.length >= 2 branch this PR newly gates, which is the part you flagged as riskiest.

parse() return value is now asserted per case, so a cell that leaves the trailing packet unconsumed fails instead of passing quietly.

758/758 green, standard clean.

The two Major items from your review went in on the 30 Jul push, in case those threads scrolled past — _parseProperties self-clamps at parser.js:766 (Property length exceeds packet length), and the primitives are bounded at 650/660/679. The MQTT-5 §3.14.2.2.1 / §3.15.2.2.1 citations are at parser.js:556 and 587.

@robertsLando robertsLando left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code review — bound DISCONNECT/AUTH by packet length

Verdict: Needs work — the approach is right, but two regressions against master (dd17095) block it.

The underlying bug is real and well-diagnosed, the fix direction is correct, and the new tests are genuine regression tests rather than tautologies — 33+ assertions verifiably fail against unfixed code. All five earlier review threads were addressed, with spec citations added. Full suite passes 758/758.

Theme (root cause of most findings)

The PR converts over-read into the next packet into stop at the packet boundary — but each stop returns false / -1 / null into a caller that doesn't test for it. Over-read became silent-accept. One fix at the signalling layer closes most of the list below.

Top 3 risks

  1. A malformed property-length varint that used to error is now silently accepted as a clean packet (parser.js:679).
  2. A truncated v5 CONNACK now reports reasonCode: 0 (Success), and a new test locks that in (parser.js:289, test.js:921).
  3. Every new boundary stop returns a sentinel no caller checks (parser.js:650, :768).

Findings not anchorable to a diff line

  • Minor · correctness — parser.js:701: if (padding) this._pos += bytes skips the advance when _pos === 0, so after a failed messageId the property-length byte is re-read as payload. Now reachable because of the new bound: B0 01 00 | C0 00 → unsuback{granted:[0]} on this PR vs granted:[] on master — the PR fabricates a granted code that master didn't.
  • Minor · operability — parser.js:774: a truncated int16 property surfaces as Cannot parse property code type (E0 04 00 02 21 00 | C0 00) because _parseNum returns -1 without consuming and the loop re-reads. Points the reader at the identifier byte, not the short value.
  • Minor · operability — the new Property length exceeds packet length tests assert one error and no packet, but nothing asserts the parser is still usable afterwards. It does recover; it's untested. The _pos reset fix has such a test.
  • FYI — parser.js:302: v5 _parseConnack still calls _parseProperties unconditionally; spec says remaining length < 3 has no Property Length. Inconsistent with the gates added to DISCONNECT/AUTH.
  • FYI — _parseConfirmation (:504-536) is a third copy of the reason-code-plus-properties block that _parseDisconnect and _parseAuth now duplicate; the offset (0 vs 2) is the only real variance.

FYI — out of scope, worth knowing

  • Blast radius: packets that previously parsed (by over-reading the next pipelined packet) now emit errors, and MQTT.js tears down the connection on a parser error. The repo has no CHANGELOG and the README documents no error contract — worth a release note.
  • Pre-existing, untouched: parser.js:96 — _parsePayload waits for _list.length >= packet.length with no cap, so a header declaring FF FF FF 7F pins up to 256 MB of heap per connection. A maxRemainingLength option would be the natural home.
  • Pre-existing: after an error, parse() returns a non-zero remaining count but _resetState discards those bytes on the next call. The PR's new error paths make it reachable more often.

Coverage

Reviewed for correctness, security, DRY/codebase fit, tests, operability and readability. Performance and API/back-compat lanes had no files. Every blocker and major claim was re-verified against pristine checkouts of 9ab9880 and dd17095.

Comment thread parser.js Resolved
Comment thread parser.js Resolved
Comment thread test.js Resolved
Comment thread parser.js Resolved
Comment thread parser.js Resolved
Comment thread test.js Resolved
Comment thread test.js Resolved
Comment thread test.js Resolved
Comment thread test.js Resolved
Comment thread test.js Resolved
Address review on mqttjs#162. The previous round bounded every payload read by
packet.length, but each stop returned a sentinel (-1, null, false) into a
caller that did not test for it, so over-read became silent-accept.

parser.js:
- _overruns(n) is the single boundary check, used by _parseByte, _parseNum,
  _parse4ByteNum, _parseString, _parseBuffer and _parseVarByteNum, replacing
  seven open-coded spellings and the two pre-existing ones.
- Inside a packet the whole payload is buffered, so a read past the remaining
  length is a Malformed Packet (MQTT-5 1.5.5), never "wait for more data".
  A truncated property-length varint now errors instead of yielding {}, and a
  property value that straddles the boundary errors instead of becoming null.
- _parseMessageId tests -1, the value _parseNum actually returns, so a
  truncated ack is rejected rather than emitted with messageId -1. The
  packet-length checks in subscribe/suback/unsubscribe/unsuback move ahead of
  it so their existing messages still win.
- _readProperties() reads the property block and returns false on failure;
  all eleven call sites now stop instead of running on past the error.
- _parseConnack rejects a CONNACK with no flags byte rather than emitting an
  empty packet, and gates properties on remaining length >= 3. The 1- and
  2-byte forms stay accepted: they are documented by 'Version 5 CONNACK test 1'
  and 'Version 4 CONACK in Version 5 mode'.
- Property errors name the packet type, matching 'Invalid <cmd> reason code'.
- _parseVarByteNum advances _pos in the payload phase even from 0, so a
  property length read at offset 0 is no longer re-read as payload.

test.js:
- One annotated table covers DISCONNECT, AUTH and CONNACK at every remaining
  length, pipelined before a PINGREQ, replacing the two overlapping tables.
- The hand-rolled error counters collapse to testParseError, which already
  proves exactly one error and no packet.
- New coverage for the _parseNum/_parse4ByteNum boundary (truncated PUBACK and
  SUBACK messageId, int16/int32/binary/string/pair property values), and for
  the parser still being usable after each new error.
@robertsLando

Copy link
Copy Markdown
Member

Round 2 pushed as 0cc2666. 765/765 pass, standard clean, testRandom error rate unchanged (90.19% vs 90.03% before — same noise floor, exit 0).

The theme you named — "each stop returns false / -1 / null into a caller that does not test for it" — is the thing that got fixed, at the signalling layer:

  • _overruns(n) is the single boundary check, replacing five new open-coded spellings and the two pre-existing ones in _parseString/_parseBuffer.
  • Inside a packet the payload is fully buffered, so a read past the remaining length is a Malformed Packet (MQTT-5 §1.5.5), never "wait for more data". Truncated property-length varints and truncated property values now error instead of yielding {} or null.
  • _readProperties() reads the block and returns false on failure; all eleven call sites stop on it.
  • _parseMessageId tests -1.

From the summary, not anchored to a line:

  • parser.js:701 — if (padding) this._pos += bytes is now if (this.packet.length !== -1). It advances from offset 0 in the payload phase, and still does not advance during the header phase, which re-runs from 0 until the whole varint arrives. Your B0 01 00 | C0 00 case is rejected with Cannot parse messageId rather than fabricating granted: [0].
  • parser.js:774 — E0 04 00 02 21 00 | C0 00 now says Property receiveMaximum exceeds disconnect packet length instead of pointing at the identifier byte.
  • The recovery gap — the parser stays usable after a packet-boundary error runs three malformed inputs (mid-packet CONNECT error, property length past the boundary, property value past the boundary) and asserts a valid PUBLISH parses after each.
  • parser.js:302 — v5 CONNACK properties are gated on remaining length >= 3 now.
  • _parseConfirmation as a third copy — the properties half is shared via _readProperties; the reason-code half still differs by offset in all three, so I left it.

Still open, both about the same decision: parser.js:289 and test.js:921. master has two tests that deliberately accept v5 CONNACK at remaining length 1 and 2 (Version 5 CONNACK test 1, Version 4 CONACK in Version 5 mode), so the strict < 3 rejection would delete documented behaviour inside a fix PR. Details and the exact before/after on those threads — your call.

Out of scope, as flagged: maxRemainingLength, and parse() returning a non-zero remaining count that _resetState then discards.

…NACK

Round 2 of review on mqttjs#162.

parser.js:
- A CONNACK always carries ack flags and a reason/return code (MQTT-5 3.2.2).
  Remaining length below 2 is now rejected instead of reporting reasonCode 0 —
  a truncated or tampered CONNACK was telling the client the connection was
  accepted, with the property block (authenticationMethod, serverReference)
  skipped. The 2-byte v4-format answer a v4-only server sends stays accepted;
  properties are gated at remaining length 3.
- A packet has two nested boundaries, the packet and the property block.
  `_overruns` only knew the outer one, so a property value could read past its
  declared length into the packet's own body: `82 0d 0001 01 01 FF 0005 612f622f63 00`
  emitted a valid SUBSCRIBE, and a PUBLISH payload was silently truncated.
  `_blockEnd` makes the open block the active bound while it is being read.
- `_parseVarByteNum` now drives its loop off `_overruns` instead of re-deriving
  the bound, so it stops at the block, sets `_truncated` like every sibling, and
  its dead `_list.length <= bytes` break is gone.
- `_parseProperties` bails when a reader has already emitted, so one malformed
  packet no longer raises two `error` events
  (`E0 08 00 06 0B 80 80 80 80 99` raised two).
- Errors follow the file's `Malformed <cmd>, <reason>` shape and name the packet
  type, including the payload-phase varint error, which had become the message
  for a whole new failure class while saying nothing about the packet.
- `_readProperties` is `_parsePropertiesInto`, matching the `_parse*` convention;
  `_parseConnack` and `_parseConnect` read through the shared helpers rather than
  hand-rolling the same bound; spec citations corrected (1.5.5 is Variable Byte
  Integer, 4.13 is Malformed Packet).

test.js:
- `Version 5 CONNACK test 1` asserted the implied-Success behaviour above; it now
  asserts the error.
- A property-length overrun case per packet type — connect (packet and will),
  publish, subscribe, suback, unsubscribe, unsuback, puback — covering all
  eleven `_parsePropertiesInto` call sites, which previously had coverage at
  three.
- Property values that overrun the block, and the v5 publish/suback/unsuback
  forms that omit the mandatory property length: both classes used to parse.
…stable

Round 3 of review on mqttjs#162.

parser.js:
- A SUBACK/UNSUBACK carries one reason code per subscription (MQTT-5 3.9.3 /
  3.11.3). `90 03 00 01 00` emitted `granted: []` with no error, silently losing
  the subscribe result; it is now rejected. Last silent accept in the packet
  types this PR touches.
- The Remaining Length varint error names the packet type too. It was the one
  error left with no context, in the same expression as the payload-phase branch
  that already had it.
- `_resetState` logs how many buffered bytes it drops. `parse()` returns that
  count before the reset, so this was the only place the loss was visible, and
  it now fires more often than it used to.
- `_overruns` and the property loop emit `debug()` lines, saying which boundary
  stopped the read - block, packet or buffer - which the trace could not
  distinguish before.
- `_blockEnd` clears rather than restores: property blocks never nest, since
  CONNECT reads its will and packet properties in sequence. `_parsePropertyList`
  reads the field instead of taking a duplicate parameter.

test.js:
- The eleven `_parsePropertiesInto` guards survived mutation at every site,
  because `parse()` refuses to emit while `this.error` is set, so a dropped
  guard changed nothing observable. Failing the read *without* setting the error
  isolates them: seven sites now die under mutation, asserting the fields after
  the property block are never assigned and no error is raised past the failure.
  CONNACK, PUBACK, DISCONNECT and AUTH read properties last, so their guards
  have nothing to stop and no test can pin them - said so in the test.
- Verified by mutation: dropping any of the seven guards, `_readEnd`'s
  `_blockEnd` branch, the `_blockEnd` assignment, the `this.error` bail, or
  loosening the CONNACK gate all fail the suite.
- `_readProperties` is gone from the comments too (`grep` is clean), the §1.5.5
  citation follows parser.js to §4.13, and the new citations use §.
…loads

Round 4 of review on mqttjs#162.

parser.js:
- Parser errors carry `err.code = 'MALFORMED_PACKET'` and `err.cmd`. The message
  text was the only thing a consumer could match on, and this change rewrote
  several of them, so it is the wrong thing to depend on. Typed in
  types/index.d.ts as `ParserError`.
- A SUBSCRIBE/UNSUBSCRIBE carries at least one topic filter ([MQTT-3.8.3-3],
  [MQTT-3.10.3-2]). `82 03 00 01 00` parsed as `subscriptions: []` with no
  error, the same silent accept the empty-`granted` guard closed for SUBACK.
- The discard log moves from `_resetState` to `_emitError`. `_resetState` only
  runs on the next `parse()`, which a consumer that tears down on `error` never
  makes, so the count was unreachable where it was asked for.
- `_parseDisconnect` and `_parseAuth` were byte-identical apart from the reason
  code table; they share `_parseReasonCodeAndProperties(codes)` now. The bug in
  the title was this same defect in both, so it had to be fixed twice.
- The varint error drops its unreachable bare-message branch: `_parseHeader`
  sets `packet.cmd` before `_parseLength` runs, and `constants.types` covers
  all sixteen indices.

test.js:
- The empty-`granted` guards shipped last round with no test at all: three
  fixtures now cover them, including the v5 SUBACK whose property block eats the
  reason codes and the v4 form. Plus the two new topic-filter guards and the
  error code/cmd.
- Verified by mutation: dropping any of the four payload guards, the reason-code
  validation, or `err.code` fails the suite.

Note: the empty-`granted` rejection applies to v3.1.1 as well as v5 - the guard
sits outside the version branch, and §3.9.3 requires a return code there too.
Round 5 of review on mqttjs#162. Correctness, security and the mutation matrix came
back clean; this is the reporting and documentation half.

- `testParseError` asserts `err.code` as well as the message, so the contract the
  PR asks consumers to match on is covered at all 96 error sites instead of the
  one bespoke test. Dropping `err.code` now fails 97 assertions.
- README documents `err.code` and `err.cmd` under `mqtt.parser([opts])`. The PR
  body says to match on them, but that text does not survive the merge and this
  repo has no changelog.
- `ParserError.cmd` is `PacketCmd | 'reserved'`: packet type 0 and 15 are
  `constants.types[0] === 'reserved'`, so `parse([0x00, 0x00])` really does emit
  `cmd: 'reserved'`, and `code` is the literal type rather than `string`.
- `err.code || ...` and `err.cmd || ...` were dead - all 30 call sites pass a
  fresh `new Error()`.
- The SUBACK/UNSUBACK reason-code loops read through `_parseByte`/`_overruns`
  like everything else, so "every read goes through `_overruns`" is now true by
  grep rather than by inspection.
- `_parsePayload` logged `%O` of the BufferListStream - about 35 lines of stream
  internals per packet, which buried the boundary traces it sits above. It logs
  the two numbers that matter. `_resetState` gets its values back, since the
  discard count moved to `_emitError` last round.
- The empty-payload comments cited the v5 property block, but both guards sit
  outside the version branch and fire on 3.1.1 too - they cite the requirement
  now, which is the same correction the PR body needed.
Round 6 of review on mqttjs#162. Correctness, security and the mutation matrix came
back clean; these are the remaining accuracy fixes.

- `testParseError` derives the expected `cmd` from the fixture's fixed header
  and asserts it, so `err.cmd` is pinned at all 97 error sites rather than the
  one bespoke test. Dropping it now fails 97 assertions.
- `err.cmd` is assigned unconditionally and typed as required: `_parseHeader`
  sets `packet.cmd` before anything can fail, and `constants.types` covers all
  sixteen indices, so the `if` was dead and the `?` was wrong. The doc comment
  said `'reserved'` was "packet type 0 or 15" - type 15 is `auth`.
- The CONNACK comment claimed §3.2.2.3 only requires a property length from
  remaining length 3 on. It does not: the property length is unconditional
  there, unlike §3.14.2.2.1 for DISCONNECT. Accepting the 2-byte v4-format
  answer is this parser's choice, and the comment says so now.
- `_parseSubscribe` and `_parseUnsubscribe` loop on `_overruns` like their
  SUBACK/UNSUBACK siblings; four sibling loops had two spellings. With one byte
  left the loop must still enter and fail on the truncated filter rather than
  report an empty list, which is now a test - the bound was otherwise free to
  move.

PR body corrected alongside: the suite count, the empty-`granted` note (the
UNSUBACK half is 5.0 only - a 3.1.1 UNSUBACK has no payload), and the `_pos`
reset, which is a second real fix the release note had omitted - on master any
mid-packet error wedges the parser permanently.
@robertsLando

Copy link
Copy Markdown
Member

Review rounds 2-7 — done, dd17095 → cc2a98f

All 14 threads from the first review are resolved, and five further review rounds ran on top. Rounds 6 and 7 came back with no blockers and no majors, which is where I stopped.

The theme

Every round found the same shape of bug: the fix converted over-read into stop at the boundary, but each stop returned a sentinel (-1, null, false) into a caller that never tested it. Over-read became silent-accept. All the work was at the signalling layer, not at the individual call sites.

What each round closed

Round Found Landed
2 1 blocker, 6 majors _overruns as the single boundary check, replacing seven spellings. Truncated property-length varints and property values error instead of yielding {} / null. _parsePropertiesInto used at all 11 call sites. A CONNACK with no reason-code byte is rejected instead of reporting Success.
3 1 blocker, 6 majors A packet has two nested bounds; _overruns only knew the outer one, so a property value could read past its declared Property Length into the packet's own body — 82 0d 0001 01 01 FF 0005 612f622f63 00 emitted a valid SUBSCRIBE. _blockEnd fixes it. Also: one packet could emit two error events; and all 11 property guards were surviving mutation testing at every site.
4 1 major Empty SUBSCRIBE / SUBACK payloads were accepted silently. err.code / err.cmd added. _parseDisconnect and _parseAuth extracted — they were byte-identical apart from the code table, which is why the bug in the title had to be fixed twice.
5 1 major err.code was asserted at 1 of 96 error sites; now all of them.
6, 7 none Minors only — documentation accuracy, err.cmd coverage, loop uniformity.

On the two CONNACK threads

I pushed back on those initially, then a later security pass found a gate better than either position: packet.length < 2. It removes the fabricated reasonCode: 0 that the review objected to, and keeps the 2-byte v4-format CONNACK that Version 4 CONACK in Version 5 mode documents. Version 5 CONNACK test 1 asserted the old behaviour and now asserts the error. Details are on the threads.

Verification

  • 1000 tests, up from 680. Every new mechanism dies under mutation — the matrix was re-run after each round, not assumed.
  • Differential fuzzing: 3135 alone-vs-pipelined divergences on master, 0 on this head. Round 7 ran 2.9M structured cases against the previous head with 0 divergences.
  • standard clean, testRandom error rate unchanged from master (~90%, i.e. no over-rejection of valid packets).
  • generate() → parse() round-trips for every packet type × v3/v4/v5 × whole / chunked / pipelined: no legal packet regressed.

Worth a maintainer's eye before merge

  • Not semver-patch. The PR body carries the full back-compat matrix. It knowingly reverses Fix reason code missing #101 (the implied reason code for a 1-byte v5 CONNACK): a broker emitting that form connects today and will be disconnected after this.
  • A second real fix the original description omitted: _resetState did not clear _pos, so on master any mid-packet error wedges the parser permanently — the next packet's Remaining Length is computed from the stale offset and the stream never resyncs.
  • Error messages changed, so err.message is not a stable contract. Every parser error now carries err.code ('MALFORMED_PACKET') and err.cmd, typed as ParserError and documented in the README.

One small doc fix (a README / .d.ts wording mismatch, from round 7) is still local and not yet pushed.

@spokodev

Copy link
Copy Markdown
Contributor Author

Seen, and thank you — that is a lot more than I brought.

The _resetState / _pos one is the part I would not have found. I was looking at a single over-read, not at the parser being wedged permanently afterwards. Same for the nested bound: I had the outer one and stopped there.

Nothing open from my side, and the way you settled the two CONNACK threads reads right to me. Yours to merge whenever the second pair of eyes is free.

…hunked tests)

- UNSUPPORTED_PROTOCOL_VERSION code for an unknown CONNECT protocol version,
  exported with MALFORMED_PACKET as mqtt.parserErrorCodes
- bound property reads by packet.length plus a per-property block-end check,
  dropping _blockEnd/_readEnd and the try/finally
- PUBACK family shares _parseReasonCodeAndProperties with DISCONNECT/AUTH
- pipelined-packet cases also run split at every byte offset
- remove redundant tests, trim history comments
@robertsLando
robertsLando merged commit 521bf5c into mqttjs:master Nov 19, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants