Repository navigation
fix: bound DISCONNECT/AUTH reason code by packet length, not buffer length - #162
Conversation
`_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
left a comment
There was a problem hiding this comment.
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
_parseConnackhas the identical bug and is left unfixed — the PR reads as "this bug class is handled" when it isn't._parsePropertiesis still bounded by the wire-declared length, notpacket.length, so DISCONNECT/AUTH with Remaining Length ≥ 2 still read the following packet's bytes — silently, no error._parseDisconnect's_emitErrorhas noreturn, so one malformed packet emits twoerrorevents.
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 strandedv4 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 ofVARBYTEINT_MAXbuffers up to 256 MiB before_parsePayloadruns. Pre-existing, not DISCONNECT/AUTH-specific. - Performance impact is nil: both operands are O(1) property reads (
bl's.lengthis incrementally maintained, not computed by walking_bufs), andbenchmarks/parse.jsonly 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.
…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.
|
Thanks for the deep review — genuinely useful. Pushed the two in-scope changes:
Full suite green (686/686, On the rest: you're right that the clean fix is pushing the |
|
@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.
|
Done in this PR. Pushed the Plus the three siblings, each with a pipelining regression test:
Boundary matrix extended to DISCONNECT/AUTH at RL 0/1/2/>2, each followed by a PINGREQ that must survive with |
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>
|
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,
758/758 green, The two Major items from your review went in on the 30 Jul push, in case those threads scrolled past — |
robertsLando
left a comment
There was a problem hiding this comment.
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
- A malformed property-length varint that used to error is now silently accepted as a clean packet (parser.js:679).
- A truncated v5 CONNACK now reports
reasonCode: 0(Success), and a new test locks that in (parser.js:289, test.js:921). - 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 += bytesskips 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 vsgranted:[]on master — the PR fabricates a granted code that master didn't. - Minor · operability —
parser.js:774: a truncated int16 property surfaces asCannot parse property code type(E0 04 00 02 21 00 | C0 00) because_parseNumreturns-1without 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 lengthtests assert one error and no packet, but nothing asserts the parser is still usable afterwards. It does recover; it's untested. The_posreset fix has such a test. - FYI —
parser.js:302: v5_parseConnackstill calls_parsePropertiesunconditionally; 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_parseDisconnectand_parseAuthnow 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—_parsePayloadwaits for_list.length >= packet.lengthwith no cap, so a header declaringFF FF FF 7Fpins up to 256 MB of heap per connection. AmaxRemainingLengthoption would be the natural home. - Pre-existing: after an error,
parse()returns a non-zero remaining count but_resetStatediscards 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.
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.
|
Round 2 pushed as The theme you named — "each stop returns
From the summary, not anchored to a line:
Still open, both about the same decision: parser.js:289 and test.js:921. Out of scope, as flagged: |
…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.
Review rounds 2-7 — done,
|
| 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. standardclean,testRandomerror 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:
_resetStatedid not clear_pos, so onmasterany 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.messageis not a stable contract. Every parser error now carrieserr.code('MALFORMED_PACKET') anderr.cmd, typed asParserErrorand documented in the README.
One small doc fix (a README / .d.ts wording mismatch, from round 7) is still local and not yet pushed.
|
Seen, and thank you — that is a lot more than I brought. The 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
Problem
_parseDisconnectand_parseAuthdecide whether a Reason Code and PropertyLength are present using
this._list.length— the number of bytes left in thewhole 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 bogusProperty Length), aborting the whole parse:
A standalone minimal packet works only because
_list.lengthhappens to equal 0when it is the last thing in the buffer, which is why
generate()round-trips(it always emits the longer
E0 02 00 00form) 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
0x00with no properties (Remaining Length 0), and "ifthe 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 > 0and the properties onpacket.length >= 2, in both methods — mirroring_parseConfirmation, whichalready bounds its reads with
packet.length._parseByteadvances the readposition without touching
packet.length, so it stays the packet's RemainingLength 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
errorand stop. Consumers such as MQTT.js tear down theconnection 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. ACONNACK always carries Connect Acknowledge Flags and a reason code (MQTT-5
§3.2.2), and defaulting the missing byte to
0tells the client anunauthenticated 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 isevery 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:
messageIdrunning past the packet orpast its property block - previously a silent
null/-1, or a value takenfrom the next packet;
an implied
reasonCode: 0;(MQTT-5 §3.3.2.3 / §3.9.2.1.1 / §3.11.2.1.1);
granted: []. Thisone 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;
[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.
_resetStateleft
_posstale, so onmasterany mid-packet error wedged the parserpermanently - the next packet's Remaining Length was computed from the stale
offset, and the stream never resynced. Measured on
dd17095: a malformedCONNECT 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 RemainingLength 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.messageis nolonger a stable contract. Every parser error now carries
err.codeanderr.cmd, declared asParserErrorintypes/index.d.ts- match on those.err.codeis one ofmqtt.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.