From 0d11e6bb32711b959baba13d4a47bd342d8c2130 Mon Sep 17 00:00:00 2001 From: Tirthraj Chavan Date: Sun, 29 Nov 2026 13:39:51 +0530 Subject: [PATCH 1/3] fix(event-import): cap decoded record size before readline buffers (#1255) --- src/services/event-import-service.ts | 61 ++++++++++++++++++- .../services/event-import-service.spec.ts | 33 ++++++++++ 2 files changed, 91 insertions(+), 3 deletions(-) diff --git a/src/services/event-import-service.ts b/src/services/event-import-service.ts index 460ac4de9..deb546f01 100644 --- a/src/services/event-import-service.ts +++ b/src/services/event-import-service.ts @@ -1,3 +1,4 @@ +import { Transform, TransformCallback } from 'stream' import fs from 'fs' import readline from 'readline' @@ -48,6 +49,18 @@ const enrichEventMetadata = (event: Event): Event => { const DEFAULT_BATCH_SIZE = 1000 +export const DEFAULT_MAX_RECORD_BYTES = 1024 * 1024 // 1 MB default ceiling + +export class RecordSizeLimitExceededError extends Error { + public constructor( + public readonly limit: number, + public readonly recordNumber: number, + ) { + super(`Record ${recordNumber} exceeded maximum allowed decoded size of ${limit} bytes`) + this.name = 'RecordSizeLimitExceededError' + } +} + export interface EventImportStats { errors: number inserted: number @@ -62,6 +75,7 @@ export interface EventImportLineError { export interface EventImportOptions { batchSize?: number + maxRecordBytes?: number onLineError?: (lineError: EventImportLineError) => void onProgress?: (stats: EventImportStats) => void } @@ -141,6 +155,40 @@ export const createEventBatchPersister = return inserted } +export const createRecordSizeLimiter = ( + maxRecordBytes: number, + sourceStream?: NodeJS.ReadableStream, +): Transform => { + let currentRecordBytes = 0 + let currentRecordNumber = 1 + + return new Transform({ + transform(chunk: Buffer | string, encoding: BufferEncoding, callback: TransformCallback) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) + + for (let i = 0; i < buffer.length; i++) { + // 0x0A is newline '\n' + if (buffer[i] === 0x0a) { + currentRecordBytes = 0 + currentRecordNumber += 1 + } else { + currentRecordBytes += 1 + if (currentRecordBytes > maxRecordBytes) { + const error = new RecordSizeLimitExceededError(maxRecordBytes, currentRecordNumber) + if (sourceStream && isDestroyableStream(sourceStream)) { + sourceStream.destroy(error) + } + callback(error) + return + } + } + } + + callback(null, chunk) + }, + }) +} + export class EventImportService { public constructor( private readonly persistBatch: (events: Event[]) => Promise, @@ -150,7 +198,7 @@ export class EventImportService { input: NodeJS.ReadableStream, options: EventImportOptions = {}, ): Promise { - return this.importFromCandidates(this.readJsonlCandidatesFromStream(input), options) + return this.importFromCandidates(this.readJsonlCandidatesFromStream(input, options.maxRecordBytes), options) } public async importFromJsonl(filePath: string, options: EventImportOptions = {}): Promise { @@ -165,10 +213,16 @@ export class EventImportService { return this.importFromCandidates(this.readJsonArrayCandidates(filePath), options) } - private async *readJsonlCandidatesFromStream(input: NodeJS.ReadableStream): AsyncGenerator { + private async *readJsonlCandidatesFromStream( + input: NodeJS.ReadableStream, + maxRecordBytes: number = DEFAULT_MAX_RECORD_BYTES, + ): AsyncGenerator { + const limiter = createRecordSizeLimiter(maxRecordBytes, input) + const guardedStream = input.pipe(limiter) + const lineReader = readline.createInterface({ crlfDelay: Infinity, - input, + input: guardedStream, }) let lineNumber = 0 @@ -196,6 +250,7 @@ export class EventImportService { } } finally { lineReader.close() + limiter.destroy() if (isDestroyableStream(input)) { input.destroy() } diff --git a/test/unit/services/event-import-service.spec.ts b/test/unit/services/event-import-service.spec.ts index 8aa91870f..de36e79aa 100644 --- a/test/unit/services/event-import-service.spec.ts +++ b/test/unit/services/event-import-service.spec.ts @@ -9,6 +9,7 @@ import { EventImportLineError, EventImportService, EventImportStats, + RecordSizeLimitExceededError, } from '../../../src/services/event-import-service' import { EventDeduplicationMetadataKey, EventKinds, EventTags } from '../../../src/constants/base' import { Event } from '../../../src/@types/event' @@ -157,6 +158,38 @@ describe('EventImportService', () => { expect(progressUpdates[progressUpdates.length - 1]).to.deep.equal(stats) }) + it('aborts and destroys the stream with RecordSizeLimitExceededError when a single record exceeds maxRecordBytes', async () => { + const hugeLine = '{"content":"' + 'a'.repeat(300) + '"}' + const stream = Readable.from([hugeLine]) + + const importer = new EventImportService(async () => 0) + + let errorThrown: unknown + try { + await importer.importFromReadable(stream, { maxRecordBytes: 100 }) + } catch (error) { + errorThrown = error + } + + expect(errorThrown).to.be.instanceOf(RecordSizeLimitExceededError) + const limitError = errorThrown as RecordSizeLimitExceededError + expect(limitError.limit).to.equal(100) + expect(limitError.recordNumber).to.equal(1) + expect(stream.destroyed).to.be.true + }) + + it('successfully imports normal records when all are within maxRecordBytes limit', async () => { + const [event] = getEvents() + const jsonlContent = `${JSON.stringify(event)}\n${JSON.stringify(event)}\n` + const stream = Readable.from([jsonlContent]) + + const importer = new EventImportService(async (events) => events.length) + + const stats = await importer.importFromReadable(stream, { maxRecordBytes: 1024 * 1024 }) + expect(stats.inserted).to.equal(2) + expect(stats.errors).to.equal(0) + }) + it('counts malformed and invalid events as errors and keeps importing', async () => { const [event] = getEvents() From 25040a97a39286e06ea61296a83c7e97877db18f Mon Sep 17 00:00:00 2001 From: Tirthraj Chavan Date: Sun, 29 Nov 2026 13:59:08 +0530 Subject: [PATCH 2/3] fix(event-import): handle CRLF and forward source stream errors --- src/services/event-import-service.ts | 12 ++++++++++-- test/unit/services/event-import-service.spec.ts | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/services/event-import-service.ts b/src/services/event-import-service.ts index deb546f01..050281973 100644 --- a/src/services/event-import-service.ts +++ b/src/services/event-import-service.ts @@ -167,16 +167,19 @@ export const createRecordSizeLimiter = ( const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) for (let i = 0; i < buffer.length; i++) { - // 0x0A is newline '\n' + // 0x0A is newline '\n', 0x0D is carriage return '\r' if (buffer[i] === 0x0a) { currentRecordBytes = 0 currentRecordNumber += 1 + } else if (buffer[i] === 0x0d) { + // Exclude CRLF carriage return from record content count + continue } else { currentRecordBytes += 1 if (currentRecordBytes > maxRecordBytes) { const error = new RecordSizeLimitExceededError(maxRecordBytes, currentRecordNumber) if (sourceStream && isDestroyableStream(sourceStream)) { - sourceStream.destroy(error) + sourceStream.destroy() } callback(error) return @@ -218,6 +221,10 @@ export class EventImportService { maxRecordBytes: number = DEFAULT_MAX_RECORD_BYTES, ): AsyncGenerator { const limiter = createRecordSizeLimiter(maxRecordBytes, input) + const onSourceError = (err: Error) => { + limiter.destroy(err) + } + input.on('error', onSourceError) const guardedStream = input.pipe(limiter) const lineReader = readline.createInterface({ @@ -249,6 +256,7 @@ export class EventImportService { } } } finally { + input.removeListener('error', onSourceError) lineReader.close() limiter.destroy() if (isDestroyableStream(input)) { diff --git a/test/unit/services/event-import-service.spec.ts b/test/unit/services/event-import-service.spec.ts index de36e79aa..f5d6c86bf 100644 --- a/test/unit/services/event-import-service.spec.ts +++ b/test/unit/services/event-import-service.spec.ts @@ -190,6 +190,20 @@ describe('EventImportService', () => { expect(stats.errors).to.equal(0) }) + it('does not count CRLF carriage return toward the byte limit', async () => { + const [event] = getEvents() + const eventJson = JSON.stringify(event) + // Stream with CRLF \r\n line ending + const stream = Readable.from([`${eventJson}\r\n`]) + + const importer = new EventImportService(async (events) => events.length) + + // Limit set to exact length of JSON payload (excluding \r\n) + const stats = await importer.importFromReadable(stream, { maxRecordBytes: Buffer.byteLength(eventJson) }) + expect(stats.inserted).to.equal(1) + expect(stats.errors).to.equal(0) + }) + it('counts malformed and invalid events as errors and keeps importing', async () => { const [event] = getEvents() From b308bf960cbc555348896e00e7228228bdbb7269 Mon Sep 17 00:00:00 2001 From: Tirthraj Chavan Date: Sun, 29 Nov 2026 17:40:30 +0530 Subject: [PATCH 3/3] chore(changeset): add changeset for #1255 --- .changeset/event-import-record-size-cap.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changeset/event-import-record-size-cap.md diff --git a/.changeset/event-import-record-size-cap.md b/.changeset/event-import-record-size-cap.md new file mode 100644 index 000000000..e5df3c405 --- /dev/null +++ b/.changeset/event-import-record-size-cap.md @@ -0,0 +1,7 @@ +--- +"nostream": patch +--- + +fix(event-import): cap decoded record size before readline buffers it (#1255) + +Enforces a configurable record size limit (`maxRecordBytes`, defaulting to 1MB) via a streaming Transform guard before `readline` buffers an incoming record into memory, mitigating CWE-409 Denial of Service.