Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/event-import-record-size-cap.md
Original file line number Diff line number Diff line change
@@ -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.
69 changes: 66 additions & 3 deletions src/services/event-import-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Transform, TransformCallback } from 'stream'
import fs from 'fs'
import readline from 'readline'

Expand Down Expand Up @@ -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
Expand All @@ -62,6 +75,7 @@ export interface EventImportLineError {

export interface EventImportOptions {
batchSize?: number
maxRecordBytes?: number
onLineError?: (lineError: EventImportLineError) => void
onProgress?: (stats: EventImportStats) => void
}
Expand Down Expand Up @@ -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<number>,
Expand All @@ -150,7 +201,7 @@ export class EventImportService {
input: NodeJS.ReadableStream,
options: EventImportOptions = {},
): Promise<EventImportStats> {
return this.importFromCandidates(this.readJsonlCandidatesFromStream(input), options)
return this.importFromCandidates(this.readJsonlCandidatesFromStream(input, options.maxRecordBytes), options)
}

public async importFromJsonl(filePath: string, options: EventImportOptions = {}): Promise<EventImportStats> {
Expand All @@ -165,10 +216,20 @@ export class EventImportService {
return this.importFromCandidates(this.readJsonArrayCandidates(filePath), options)
}

private async *readJsonlCandidatesFromStream(input: NodeJS.ReadableStream): AsyncGenerator<EventImportCandidate> {
private async *readJsonlCandidatesFromStream(
input: NodeJS.ReadableStream,
maxRecordBytes: number = DEFAULT_MAX_RECORD_BYTES,
): AsyncGenerator<EventImportCandidate> {
const limiter = createRecordSizeLimiter(maxRecordBytes, input)
const onSourceError = (err: Error) => {
limiter.destroy(err)
}
input.on('error', onSourceError)
const guardedStream = input.pipe(limiter)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

const lineReader = readline.createInterface({
crlfDelay: Infinity,
input,
input: guardedStream,
})

let lineNumber = 0
Expand All @@ -195,7 +256,9 @@ export class EventImportService {
}
}
} finally {
input.removeListener('error', onSourceError)
lineReader.close()
limiter.destroy()
if (isDestroyableStream(input)) {
input.destroy()
}
Expand Down
47 changes: 47 additions & 0 deletions test/unit/services/event-import-service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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()

Expand Down
Loading