Skip to content
This repository was archived by the owner on Jul 21, 2023. It is now read-only.

Commit ae42f76

Browse files
wemeetagainachingbrainmpetrunic
authored
fix: set min and max protocol length (#21)
* fix: set min and max protocol length * fix: import statement Co-authored-by: Alex Potsides <[email protected]> * chore: add tests * fix: 0-lnegth test error code Co-authored-by: Alex Potsides <[email protected]> Co-authored-by: Marin Petrunic <[email protected]>
1 parent 53883b1 commit ae42f76

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

src/constants.ts

+4
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11

22
export const PROTOCOL_ID = '/multistream/1.0.0'
3+
4+
// Conforming to go-libp2p
5+
// See https://github.com/multiformats/go-multistream/blob/master/multistream.go#L297
6+
export const MAX_PROTOCOL_LENGTH = 1024

src/multistream.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { AbortOptions } from '@libp2p/interfaces'
1212
import type { Source } from 'it-stream-types'
1313
import type { Reader } from 'it-reader'
1414
import type { MultistreamSelectInit } from '.'
15+
import { MAX_PROTOCOL_LENGTH } from './constants.js'
1516

1617
const NewLine = uint8ArrayFromString('\n')
1718

@@ -73,11 +74,11 @@ export async function read (reader: Reader, options?: AbortOptions): Promise<Uin
7374

7475
const buf = await pipe(
7576
input,
76-
lp.decode({ onLength }),
77+
lp.decode({ onLength, maxDataLength: MAX_PROTOCOL_LENGTH }),
7778
async (source) => await first(source)
7879
)
7980

80-
if (buf == null) {
81+
if (buf == null || buf.length === 0) {
8182
throw errCode(new Error('no buffer returned'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')
8283
}
8384

test/multistream.spec.ts

+25
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,31 @@ describe('Multistream', () => {
8787
.with.property('code', 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')
8888
})
8989

90+
it('should throw for a large message', async () => {
91+
const input = new Uint8Array(10000)
92+
input[input.length - 1] = '\n'.charCodeAt(0)
93+
94+
const source = reader([uint8ArrayConcat([
95+
Uint8Array.from(Varint.encode(input.length)),
96+
input
97+
])])
98+
99+
await expect(Multistream.read(source)).to.eventually.be.rejected()
100+
.with.property('code', 'ERR_MSG_DATA_TOO_LONG')
101+
})
102+
103+
it('should throw for a 0-length message', async () => {
104+
const input = new Uint8Array(0)
105+
106+
const source = reader([uint8ArrayConcat([
107+
Uint8Array.from(Varint.encode(input.length)),
108+
input
109+
])])
110+
111+
await expect(Multistream.read(source)).to.eventually.be.rejected()
112+
.with.property('code', 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')
113+
})
114+
90115
it('should be abortable', async () => {
91116
const input = uint8ArrayFromString(`TEST${Date.now()}`)
92117

0 commit comments

Comments
 (0)