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. diff --git a/src/services/event-import-service.ts b/src/services/event-import-service.ts index 460ac4de9..050281973 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,43 @@ 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', 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() + } + callback(error) + return + } + } + } + + callback(null, chunk) + }, + }) +} + export class EventImportService { public constructor( private readonly persistBatch: (events: Event[]) => Promise, @@ -150,7 +201,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 +216,20 @@ 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 onSourceError = (err: Error) => { + limiter.destroy(err) + } + input.on('error', onSourceError) + const guardedStream = input.pipe(limiter) + const lineReader = readline.createInterface({ crlfDelay: Infinity, - input, + input: guardedStream, }) let lineNumber = 0 @@ -195,7 +256,9 @@ export class EventImportService { } } } finally { + input.removeListener('error', onSourceError) 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..f5d6c86bf 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,52 @@ 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('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()