From 40014da6e8d1264ac1cedc8ea2ebe03e7d7849d1 Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Mon, 30 Nov 2026 14:10:29 +0800 Subject: [PATCH] refactor(audit): share byte framing for offline audit logs (#15162) --- src/domain/linux/auditLogLines.test.ts | 56 ++++++++++++++ src/domain/linux/auditLogLines.ts | 63 +++++++++++++++ src/domain/linux/auditdLog.ts | 102 ++++++------------------- src/domain/linux/kubernetesAuditLog.ts | 72 ++++------------- 4 files changed, 157 insertions(+), 136 deletions(-) create mode 100644 src/domain/linux/auditLogLines.test.ts create mode 100644 src/domain/linux/auditLogLines.ts diff --git a/src/domain/linux/auditLogLines.test.ts b/src/domain/linux/auditLogLines.test.ts new file mode 100644 index 00000000000..37e7a6450a8 --- /dev/null +++ b/src/domain/linux/auditLogLines.test.ts @@ -0,0 +1,56 @@ +import { expect, it } from "vitest"; +import { createAuditdLogDecoder } from "./auditdLog.js"; +import { createKubernetesAuditLogDecoder } from "./kubernetesAuditLog.js"; + +const limit = 64 * 1024; + +it.each([ + { + name: "auditd", + line: "type=SYSCALL msg=audit(1748451600.321:7): pid=1", + create: createAuditdLogDecoder, + counts: { record_count: 2, malformed_line_count: 1 }, + }, + { + name: "Kubernetes", + line: '{"auditID":"one","stage":"ResponseComplete","verb":"get"}', + create: (size: number) => createKubernetesAuditLogDecoder(size, limit), + counts: { + event_count: 2, + oversized_line_count: 1, + malformed_line_count: 0, + }, + }, +])( + "$name frames raw chunks at the line limit and flushes a final line once", + ({ line, create, counts }) => { + const chunks = [ + Buffer.from("\n"), + Buffer.from(line.padEnd(limit - 1)), + Buffer.from("\r\n"), + Buffer.from(line.padEnd(limit)), + Buffer.from("\r\n"), + Buffer.from(line), + ]; + const decoder = create( + chunks.reduce((size, chunk) => size + chunk.length, 0), + ); + if (!decoder.ok) throw new Error(decoder.error.message); + for (const chunk of chunks) { + expect(decoder.value.write(chunk).ok).toBe(true); + chunk.fill(0); + } + const image = structuredClone(decoder.value.finish()); + expect(image).toMatchObject({ + ok: true, + value: { + metadata: { + line_count: 4, + trailing_bytes: Buffer.byteLength(line), + ...counts, + }, + }, + }); + expect(decoder.value.finish()).toEqual(image); + }, +); diff --git a/src/domain/linux/auditLogLines.ts b/src/domain/linux/auditLogLines.ts new file mode 100644 index 00000000000..cd4037f8dfa --- /dev/null +++ b/src/domain/linux/auditLogLines.ts @@ -0,0 +1,63 @@ +import { ok, type Result } from "../result.js"; + +/** Frame LF-delimited records without decoding or retaining an oversized line. */ +export abstract class AuditLogLines { + readonly #segments: Buffer[] = []; + // not-an-allowance: the observed line length includes bytes discarded after overflow. + #pendingBytes = 0; + #lineNumber = 0; + // not-an-allowance: observed length of the final unterminated record. + #trailingBytes = 0; + + constructor(protected readonly maxLineBytes: number) {} + + protected get lineNumber(): number { + return this.#lineNumber; + } + + protected get trailingBytes(): number { + return this.#trailingBytes; + } + + protected abstract acceptLine(line: Buffer): void; + protected abstract skipOversizedLine(length: number): void; + + write(chunk: Uint8Array): Result { + const bytes = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + let start = 0; + for (let index = 0; index < bytes.length; index += 1) { + if (bytes[index] !== 0x0a) continue; + this.#append(bytes.subarray(start, index)); + this.#finishLine(); + start = index + 1; + } + if (start < bytes.length) this.#append(bytes.subarray(start)); + return ok(undefined); + } + + protected finishPendingLine(): void { + if (this.#pendingBytes > 0) { + this.#trailingBytes = this.#pendingBytes; + this.#finishLine(); + } + } + + #append(segment: Buffer): void { + this.#pendingBytes += segment.length; + if (this.#pendingBytes > this.maxLineBytes) this.#segments.length = 0; + else if (segment.length > 0) this.#segments.push(Buffer.from(segment)); + } + + #finishLine(): void { + this.#lineNumber += 1; + const length = this.#pendingBytes; + this.#pendingBytes = 0; + if (length > this.maxLineBytes) { + this.skipOversizedLine(length); + return; + } + const line = Buffer.concat(this.#segments, length); + this.#segments.length = 0; + this.acceptLine(line); + } +} diff --git a/src/domain/linux/auditdLog.ts b/src/domain/linux/auditdLog.ts index 2d805fa2511..e1dee555bfc 100644 --- a/src/domain/linux/auditdLog.ts +++ b/src/domain/linux/auditdLog.ts @@ -1,3 +1,4 @@ +import { AuditLogLines } from "./auditLogLines.js"; import { createHash } from "node:crypto"; import { boundedList } from "../boundedList.js"; @@ -295,16 +296,7 @@ const failure = (message: string): RegionDecodeFailure => ({ * out-of-order and interleaved writes are reported rather than silently * reordered into a tidy timeline. */ -class AuditdLogScanner { - readonly #fileBytes: number; - #pendingLine: Buffer[] = []; - // not-an-allowance: pending bytes of the line being assembled, bounded by a fixed line ceiling rather than charged from a resource budget. - #pendingBytes = 0; - // not-an-allowance: bytes of the line being assembled that were dropped after it overflowed the fixed line ceiling; only fed to the trailing-byte tally, never charged from a resource budget. - #pendingFlushedBytes = 0; - #lineNumber = 0; - // not-an-allowance: bytes of a final line that ended without a newline, a tally of what the file held rather than a budget. - #trailingBytes = 0; +class AuditdLogScanner extends AuditLogLines { #recordCount = 0; // not-an-allowance: observed per-type record totals for the whole file; admitted at most AUDITD_RETAINED_TYPE_LIMIT distinct labels, which the scanner tallies rather than refuses. readonly #typeCounts = new Map(); @@ -367,42 +359,19 @@ class AuditdLogScanner { */ #orderingNodeOmitted = false; #lastEventKey: string | null = null; - #lineOverflow = false; - constructor(fileBytes: number) { - this.#fileBytes = fileBytes; - } - - write(chunk: Uint8Array): Result { - const bytes = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); - let start = 0; - for (let index = 0; index < chunk.length; index += 1) { - if (chunk[index] !== 0x0a) continue; - this.#acceptSegment(bytes.subarray(start, index)); - this.#finishLine(); - start = index + 1; - } - if (start < bytes.length) this.#acceptSegment(bytes.subarray(start)); - return ok(undefined); + constructor() { + super(MAX_RECORD_LINE_BYTES); } finish(): Result { - if (this.#pendingBytes > 0 || this.#pendingFlushedBytes > 0) { - this.#trailingBytes = this.#pendingBytes + this.#pendingFlushedBytes; - this.#finishLine(); - } - if (this.#lineOverflow) - return err( - failure( - `the file declares ${String(this.#fileBytes)} bytes but more were supplied`, - ), - ); - if (this.#lineNumber === 0) + this.finishPendingLine(); + if (this.lineNumber === 0) return err(failure("file holds no audit records")); if (this.#recordCount === 0) return err( failure( - `${String(this.#lineNumber)} line(s) were read but none is an auditd record`, + `${String(this.lineNumber)} line(s) were read but none is an auditd record`, ), ); @@ -417,7 +386,7 @@ class AuditdLogScanner { return ok({ metadata: { kind: "auditd-log", - line_count: this.#lineNumber, + line_count: this.lineNumber, record_count: this.#recordCount, event_count: this.#windowEventCount + this.#beyondWindowEventCount, // Past the window an event is counted once per run of its records, so a @@ -442,7 +411,7 @@ class AuditdLogScanner { events, omitted_events: this.#windowEventCount + this.#beyondWindowEventCount - events.length, - trailing_bytes: this.#trailingBytes, + trailing_bytes: this.trailingBytes, }, limitations, }); @@ -502,42 +471,15 @@ class AuditdLogScanner { return limitations; } - #acceptSegment(segment: Buffer): void { - if (this.#lineOverflow) { - this.#pendingFlushedBytes += segment.length; - return; - } - if (this.#pendingBytes + segment.length > MAX_RECORD_LINE_BYTES) { - this.#lineOverflow = true; - this.#pendingFlushedBytes = this.#pendingBytes + segment.length; - this.#pendingBytes = 0; - this.#pendingLine = []; - return; - } - if (segment.length > 0) this.#pendingLine.push(Buffer.from(segment)); - this.#pendingBytes += segment.length; + protected override skipOversizedLine(): void { + this.#diagnose( + this.lineNumber, + `line exceeds the fixed ${String(MAX_RECORD_LINE_BYTES)}-byte record ceiling`, + "", + ); } - #finishLine(): void { - this.#lineNumber += 1; - const lineBytes = Buffer.concat(this.#pendingLine); - this.#pendingBytes = 0; - this.#pendingFlushedBytes = 0; - this.#pendingLine = []; - - if (this.#lineOverflow) { - this.#lineOverflow = false; - this.#diagnose( - this.#lineNumber, - `line exceeds the fixed ${String(MAX_RECORD_LINE_BYTES)}-byte record ceiling`, - "", - ); - return; - } - this.#acceptLine(lineBytes); - } - - #acceptLine(lineBytes: Buffer): void { + protected override acceptLine(lineBytes: Buffer): void { // The header is printable ASCII, so it must decode exactly: a lossy decode // maps different invalid bytes to the same U+FFFD and two distinct `node=` // or `type=` values would then share an identity. Decoding the header's raw @@ -550,7 +492,7 @@ class AuditdLogScanner { if (match?.groups === undefined) { const reference = AUDIT_REFERENCE.exec(line); this.#diagnose( - this.#lineNumber, + this.lineNumber, reference === null ? "line is not a `type=… msg=audit(.:):` record" : "record header is malformed around its audit event identity", @@ -566,7 +508,7 @@ class AuditdLogScanner { const type = match.groups["type"]!; if (![seconds, millis, serial].every(Number.isSafeInteger)) { this.#diagnose( - this.#lineNumber, + this.lineNumber, "audit event identity exceeds the safe integer range", line, ); @@ -644,8 +586,8 @@ class AuditdLogScanner { omittedTypeLabels: new Set(), omittedTypeLabelsSaturated: false, seenRecords: new Set(), - firstLine: this.#lineNumber, - lastLine: this.#lineNumber, + firstLine: this.lineNumber, + lastLine: this.lineNumber, duplicateCount: 0, interleaved: false, } satisfies PendingEvent); @@ -683,7 +625,7 @@ class AuditdLogScanner { // record not tallied, because it repeats one already counted here. if (!duplicate) this.#tallyEventType(event, type); event.recordCount += 1; - event.lastLine = this.#lineNumber; + event.lastLine = this.lineNumber; } /** @@ -793,7 +735,7 @@ export const createAuditdLogDecoder = ( Number.isSafeInteger(fileBytes) && fileBytes >= 0 && fileBytes <= AUDITD_LOG_MAX_FILE_BYTES - ? ok(new AuditdLogScanner(fileBytes)) + ? ok(new AuditdLogScanner()) : err({ kind: "limit", message: `file is ${String(fileBytes)} bytes, exceeding the fixed ${String(AUDITD_LOG_MAX_FILE_BYTES)}-byte (4 GiB) ceiling`, diff --git a/src/domain/linux/kubernetesAuditLog.ts b/src/domain/linux/kubernetesAuditLog.ts index b0bf9cc1e6e..16c6c75c02e 100644 --- a/src/domain/linux/kubernetesAuditLog.ts +++ b/src/domain/linux/kubernetesAuditLog.ts @@ -1,3 +1,4 @@ +import { AuditLogLines } from "./auditLogLines.js"; import { ok, err, type Result } from "../result.js"; import { z } from "zod"; import { Budget } from "../budget.js"; @@ -273,13 +274,8 @@ const retainStage = ( * `auditID`. Each line remains an event in its own right, so a request whose * stages were written out of order is reported rather than reordered. */ -class KubernetesAuditScanner { - #pending: Buffer[] = []; - // not-an-allowance: bytes of the line being assembled, bounded by a fixed line ceiling rather than charged from a resource budget. - #pendingBytes = 0; - #lineNumber = 0; +class KubernetesAuditScanner extends AuditLogLines { #recordCount = 0; - #trailingBytes = 0; #malformedCount = 0; #oversizedLineCount = 0; #largestSkippedLineBytes = 0; @@ -295,32 +291,14 @@ class KubernetesAuditScanner { #unsupportedVersionLineCount = 0; #depthLimitedLines = 0; - constructor(private readonly maxLineBytes: number) {} - - write(chunk: Uint8Array): Result { - const bytes = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); - let start = 0; - for (let index = 0; index < chunk.length; index += 1) { - if (chunk[index] !== 0x0a) continue; - this.#acceptSegment(bytes.subarray(start, index)); - this.#finishLine(); - start = index + 1; - } - if (start < bytes.length) this.#acceptSegment(bytes.subarray(start)); - return ok(undefined); - } - finish(): Result { - if (this.#pendingBytes > 0) { - this.#trailingBytes = this.#pendingBytes; - this.#finishLine(); - } - if (this.#lineNumber === 0) + this.finishPendingLine(); + if (this.lineNumber === 0) return err(failure("file holds no Kubernetes audit records")); if (this.#recordCount === 0 && this.#oversizedLineCount === 0) return err( failure( - `${String(this.#lineNumber)} line(s) were read but none is a Kubernetes audit event`, + `${String(this.lineNumber)} line(s) were read but none is a Kubernetes audit event`, ), ); const sampleWithoutTerminalStage = [...this.#sample.values()].filter( @@ -331,7 +309,7 @@ class KubernetesAuditScanner { return ok({ metadata: { kind: "kubernetes-audit-log", - line_count: this.#lineNumber, + line_count: this.lineNumber, event_count: this.#recordCount, oversized_line_count: this.#oversizedLineCount, line_bytes_limit: this.maxLineBytes, @@ -353,7 +331,7 @@ class KubernetesAuditScanner { events, unsampled_event_line_count: this.#unsampledEventLines, depth_limited_line_count: this.#depthLimitedLines, - trailing_bytes: this.#trailingBytes, + trailing_bytes: this.trailingBytes, }, limitations: this.#limitations(events, sampleWithoutTerminalStage), }); @@ -412,33 +390,15 @@ class KubernetesAuditScanner { return limitations; } - #acceptSegment(segment: Buffer): void { - this.#pendingBytes += segment.length; - if (this.#pendingBytes > this.maxLineBytes) { - this.#pending.length = 0; - return; - } - if (segment.length > 0) this.#pending.push(Buffer.from(segment)); + protected override skipOversizedLine(length: number): void { + this.#oversizedLineCount += 1; + this.#largestSkippedLineBytes = Math.max( + this.#largestSkippedLineBytes, + length, + ); } - #finishLine(): void { - this.#lineNumber += 1; - const lineLength = this.#pendingBytes; - this.#pendingBytes = 0; - if (lineLength > this.maxLineBytes) { - this.#oversizedLineCount += 1; - this.#largestSkippedLineBytes = Math.max( - this.#largestSkippedLineBytes, - lineLength, - ); - return; - } - const lineBytes = Buffer.concat(this.#pending, lineLength); - this.#pending.length = 0; - this.#acceptLine(lineBytes); - } - - #acceptLine(lineBytes: Buffer): void { + protected override acceptLine(lineBytes: Buffer): void { const decoded = decodeUtf8PreservingBomOrNull(lineBytes); if (decoded === null) { this.#diagnose( @@ -530,7 +490,7 @@ class KubernetesAuditScanner { } const stageRecord: KubernetesAuditStageRecord = { stage, - line: this.#lineNumber, + line: this.lineNumber, request_received_timestamp: suppressFields ? null : parseTimestamp(event.requestReceivedTimestamp), @@ -610,7 +570,7 @@ class KubernetesAuditScanner { this.#malformedCount += 1; if (this.#malformed.length < KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT) this.#malformed.push({ - line: this.#lineNumber, + line: this.lineNumber, reason, excerpt: detachedText(excerptOf(text)), });