diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index 98084944a4..f9975f91fc 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -784,8 +784,8 @@ editable setting or active worker telemetry. `inspect_artifact` and `extract_artifact` accept `bun`, `dotnet_bundle`, `node_sea`, `godot`, `iso9660`, `deno`, `wxapkg`, `tar` and -`android_sparse_image`, `android_vbmeta`, `media_asset` and `android_dtbo` -groups in `artifact_limits`. Their controls apply when +`android_sparse_image`, `android_vbmeta`, `media_asset`, `android_dtbo` and +`kubernetes_audit_log` groups in `artifact_limits`. Their controls apply when recognition or inventory encounters that format. Supplying a policy does not assert the format is present. Unsupported keys are rejected. Each group follows one domain-owned default policy. See [.NET bundles](../dotnet-bundles.md), @@ -797,6 +797,13 @@ one domain-owned default policy. See [.NET bundles](../dotnet-bundles.md), [media asset headers](../media-asset-headers.md) and [Android DTBO partition images](../android-dtbo.md) for format semantics. +`artifact_limits.kubernetes_audit_log.line_bytes` sets the largest audit JSON +record inspected from the log (default 4 MiB, range 1 byte to 16 MiB). The +inventory reports the effective value and counts larger complete lines as +capacity skips. Their contents are unexamined and their event, stage, and verb +facts are unknown. To inspect them, raise the allowance on the next call or +select a log with smaller records. + `artifact_limits.expanded_bytes` selects aggregate plaintext work for ZIP, Bun, SEA, PCK, ISO 9660, Deno, wxapkg, tar, macOS flat `.pkg` (including `Scripts`/`Payload` cpio archive decoding and scaled cpio member and path-byte diff --git a/scripts/verify/advertised-schemas/tools/extract_artifact.json b/scripts/verify/advertised-schemas/tools/extract_artifact.json index f903842842..035ecc2021 100644 --- a/scripts/verify/advertised-schemas/tools/extract_artifact.json +++ b/scripts/verify/advertised-schemas/tools/extract_artifact.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "f9715f4c636b469a", + "input compact": "7abd42cbc18fb8f0", "output compact": "fc6c5d5a78a47254" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_artifact.json b/scripts/verify/advertised-schemas/tools/inspect_artifact.json index 45db5e64da..9b183b185b 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_artifact.json +++ b/scripts/verify/advertised-schemas/tools/inspect_artifact.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "690407a018dd26a0", + "input compact": "9107d66c603bc42d", "output compact": "fc6c5d5a78a47254" }, "patterns": { diff --git a/scripts/verify/fixed-ceiling-registry.json b/scripts/verify/fixed-ceiling-registry.json index 50576c0694..9b81a47485 100644 --- a/scripts/verify/fixed-ceiling-registry.json +++ b/scripts/verify/fixed-ceiling-registry.json @@ -72,6 +72,13 @@ "reason": "The 4 GiB auditd log admission is a resource policy; issue #11345 tracks giving it a control as the reader grows past step 1." } }, + "src/artifacts/KubernetesAuditLogArtifactReader.ts": { + "\"The Kubernetes audit log file-size ceiling\"": { + "class": "pending", + "issue": 11352, + "reason": "The 4 GiB Kubernetes audit log admission is a resource policy; issue #11352 tracks giving it a control as the reader grows past step 1." + } + }, "src/artifacts/AndroidSparseImageArtifactReader.ts": { "ceiling.name": { "class": "forwarding", diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index 05592df190..442fa471f0 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -82,6 +82,7 @@ import { MAX_XML_PLIST_PROBE_BYTES, } from "../domain/apple/appleArchiveFormat.js"; import { hasDiskImageSignature } from "../domain/apple/diskImageFormat.js"; +import { KubernetesAuditEventProbe } from "../domain/linux/kubernetesAuditEventProbe.js"; import { recognizeArtifactFormat } from "../domain/artifactFormatRecognition.js"; import { gzipTarExtraFieldProbeBytes } from "../domain/tarFormat.js"; import { @@ -798,12 +799,14 @@ const detectArtifactFormat = async ( let suffix: Uint8Array | undefined; let espFlashLayout: boolean | undefined; let iso9660Descriptor: Uint8Array | undefined; + let kubernetesAuditEvent: boolean | undefined; const recognitionInput = () => ({ prefix: recognitionPrefix, fileSize: initial.size, suffix, espFlashLayout, iso9660Descriptor, + kubernetesAuditEvent, }); let recognition = recognizeArtifactFormat(recognitionInput()); while (recognition !== undefined) { @@ -833,7 +836,25 @@ const detectArtifactFormat = async ( ISO9660_SIGNATURE_BYTES, signal, ); - else + else if (recognition.format === "kubernetes-audit-log") { + const probe = new KubernetesAuditEventProbe(); + probe.write(recognitionPrefix); + let offset = recognitionPrefix.length; + while (offset < Math.min(initial.size, probe.limit)) { + const chunk = await readCachedRange( + offset, + Math.min(64 * 1024, initial.size - offset, probe.limit - offset), + ); + if (chunk.length === 0) break; + probe.write(chunk); + offset += chunk.length; + } + await assertStableRegularFileIdentity(handle, sourcePath, initial, { + symlinks: "reject", + ...(signal === undefined ? {} : { signal }), + }); + kubernetesAuditEvent = probe.finish(initial.size) ?? false; + } else espFlashLayout = ( await locateEspFlashLayout( initial.size, diff --git a/src/application/binary/TargetFormatVocabularies.test.ts b/src/application/binary/TargetFormatVocabularies.test.ts index 7a1e044a36..813517ac0d 100644 --- a/src/application/binary/TargetFormatVocabularies.test.ts +++ b/src/application/binary/TargetFormatVocabularies.test.ts @@ -167,6 +167,7 @@ const TARGETS: TargetFixtures = { "ntfs-mft": { ...archive, format: "ntfs-mft" }, "systemd-journal": { ...archive, format: "systemd-journal" }, "auditd-log": { ...archive, format: "auditd-log" }, + "kubernetes-audit-log": { ...archive, format: "kubernetes-audit-log" }, plist: { ...artifact, format: "plist" }, javascript: { ...artifact, format: "javascript" }, "source-map": { ...artifact, format: "source-map" }, diff --git a/src/artifacts/ArtifactClassificationProbe.ts b/src/artifacts/ArtifactClassificationProbe.ts index 921805a2a9..38e5a54ae0 100644 --- a/src/artifacts/ArtifactClassificationProbe.ts +++ b/src/artifacts/ArtifactClassificationProbe.ts @@ -26,6 +26,7 @@ import { ISO9660_DESCRIPTOR_OFFSET, ISO9660_SIGNATURE_BYTES, } from "../domain/iso9660/iso9660Structures.js"; +import { KubernetesAuditEventProbe } from "../domain/linux/kubernetesAuditEventProbe.js"; import { gzipTarExtraFieldProbeBytes } from "../domain/tarFormat.js"; import { createAsarHeaderSignatureProbe, @@ -44,6 +45,8 @@ export interface ArtifactClassificationEvidence { readonly suffix?: Buffer; /** The first ISO 9660 descriptor signature, when the stream reached it. */ readonly iso9660Descriptor?: Buffer; + /** Whether the candidate first JSON line is a Kubernetes audit event. */ + readonly kubernetesAuditEvent?: boolean; /** The probe matched an XML plist prolog in the retained prefix. */ readonly xmlPlistSignature: boolean; readonly asarHeader: FinalAsarHeaderProbeObservation; @@ -111,6 +114,7 @@ const finishClassificationEvidence = ( sliceHeadersByOffset: Map, mzWindowsHeaderSignature: MzWindowsHeaderSignatureEvidence | undefined, mzWindowsHeaderRecord: MzWindowsHeaderRecordEvidence | undefined, + kubernetesAuditEvent: boolean | undefined, ): ArtifactClassificationEvidence => { const finalHeader = readFatContainerHeader(prefix, archiveBytes); if (finalHeader.state === "parsed") { @@ -136,6 +140,7 @@ const finishClassificationEvidence = ( ...(suffix === undefined ? {} : { suffix }), ...(iso9660Descriptor === undefined ? {} : { iso9660Descriptor }), xmlPlistSignature, + ...(kubernetesAuditEvent === undefined ? {} : { kubernetesAuditEvent }), asarHeader: finishAsar(archiveBytes), fatHeader: finalHeader, fatSliceHeadersByOffset: @@ -155,6 +160,7 @@ export const createArtifactClassificationProbe = ( ) => { const xml = createXmlPlistSignatureProbe(); const asar = createAsarHeaderSignatureProbe(asarHeaderAdmission); + const kubernetesAudit = new KubernetesAuditEventProbe(); const blocks: Buffer[] = []; let retainedBytes = 0; let observedBytes = 0; @@ -310,11 +316,13 @@ export const createArtifactClassificationProbe = ( signaturePrefixLimit(), xml.state === "pending" ? MAX_XML_PLIST_PROBE_BYTES : 0, asar.observation.state === "pending" ? asar.limit : 0, + kubernetesAudit.limit, ); }, write(bytes: Uint8Array): void { const streamOffset = observedBytes; asar.write(bytes); + kubernetesAudit.write(bytes); let offset = 0; while (offset < bytes.length) { const limit = Math.max( @@ -396,6 +404,7 @@ export const createArtifactClassificationProbe = ( fatSliceHeadersByOffset, mzWindowsHeaderSignature, mzWindowsHeaderRecord, + kubernetesAudit.finish(archiveBytes), ); }, }; diff --git a/src/artifacts/KubernetesAuditLogArtifactReader.test.ts b/src/artifacts/KubernetesAuditLogArtifactReader.test.ts new file mode 100644 index 0000000000..2d27fc732e --- /dev/null +++ b/src/artifacts/KubernetesAuditLogArtifactReader.test.ts @@ -0,0 +1,969 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { expect, it } from "vitest"; + +import { KubernetesAuditLogArtifactReader } from "./KubernetesAuditLogArtifactReader.js"; +import { + KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT, + KUBERNETES_AUDIT_INLINE_EVENT_LIMIT, + KUBERNETES_AUDIT_INLINE_VERB_LIMIT, +} from "../domain/linux/kubernetesAuditLog.js"; +import { KUBERNETES_AUDIT_JSON_DEPTH } from "../domain/linux/kubernetesAuditRecord.js"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; + +interface EventOverrides { + readonly auditID?: string; + readonly stage?: string; + readonly verb?: string; + readonly requestURI?: string; + readonly username?: string; + readonly groups?: readonly string[]; + readonly sourceIPs?: readonly string[]; + readonly userAgent?: string; + readonly resource?: string; + readonly namespace?: string; + readonly name?: string; + readonly responseCode?: number; + readonly responseBody?: unknown; + readonly requestReceivedTimestamp?: string; +} + +const auditEvent = (overrides: EventOverrides = {}): string => + JSON.stringify({ + kind: "Event", + apiVersion: "audit.k8s.io/v1", + auditID: overrides.auditID ?? "00000000-0000-4000-8000-000000000001", + stage: overrides.stage ?? "RequestReceived", + requestURI: overrides.requestURI ?? "/api/v1/namespaces/default/pods", + verb: overrides.verb ?? "get", + user: { + username: overrides.username ?? "system:serviceaccount:default:reader", + groups: overrides.groups ?? [ + "system:serviceaccounts", + "system:authenticated", + ], + }, + sourceIPs: overrides.sourceIPs ?? ["10.0.0.7"], + userAgent: overrides.userAgent ?? "kubectl/v1.30.0", + objectRef: { + resource: overrides.resource ?? "pods", + namespace: overrides.namespace ?? "default", + name: overrides.name ?? "web-0", + }, + ...(overrides.responseCode === undefined + ? {} + : { responseStatus: { code: overrides.responseCode } }), + ...(overrides.responseBody === undefined + ? {} + : { responseObject: overrides.responseBody }), + requestReceivedTimestamp: + overrides.requestReceivedTimestamp ?? "2026-11-20T10:00:00.000000Z", + }); + +const writeLog = async (name: string, text: string): Promise => { + const directory = await createTestTempDirectory("rea-kubernetes-audit-"); + const path = join(directory, name); + await writeFile(path, text); + return path; +}; + +const metadataOf = async (text: string) => { + const reader = new KubernetesAuditLogArtifactReader( + await writeLog("audit.log", text), + ); + // The log declares no members, so the traversal only builds the inventory + // and reports what it could not establish through the coverage callback. + const limitations: string[] = []; + try { + for await (const _entry of reader.entries(undefined, { + onCoverage: (coverage) => limitations.push(...coverage.limitations), + })) { + // No members. + } + const metadata = reader.formatMetadata(); + if (metadata?.kind !== "kubernetes-audit-log") + throw new Error("Expected kubernetes-audit-log metadata"); + return { ...metadata, limitations }; + } finally { + await reader.close(); + } +}; + +const REQUEST = [ + auditEvent({ stage: "RequestReceived" }), + auditEvent({ stage: "ResponseStarted", responseCode: 200 }), + auditEvent({ stage: "ResponseComplete", responseCode: 200 }), +].join("\n"); + +it("joins the stages of one request on its auditID", async () => { + const metadata = await metadataOf(`${REQUEST}\n`); + expect(metadata.line_count).toBe(3); + expect(metadata.event_count).toBe(3); + expect(metadata.events).toHaveLength(1); + const [event] = metadata.events; + expect(event?.audit_id).toBe("00000000-0000-4000-8000-000000000001"); + expect(event?.stages.map((stage) => stage.stage)).toEqual([ + "RequestReceived", + "ResponseStarted", + "ResponseComplete", + ]); + expect(event?.stages.map((stage) => stage.line)).toEqual([1, 2, 3]); + expect(event?.request_uri).toBe("/api/v1/namespaces/default/pods"); + expect(event?.verb).toBe("get"); + expect(event?.username).toBe("system:serviceaccount:default:reader"); + expect(event?.user_groups).toEqual([ + "system:serviceaccounts", + "system:authenticated", + ]); + expect(event?.source_ips).toEqual(["10.0.0.7"]); + expect(event?.user_agent).toBe("kubectl/v1.30.0"); + expect(event?.resource).toBe("pods"); + expect(event?.namespace).toBe("default"); + expect(event?.object_name).toBe("web-0"); + expect(event?.response_code).toBe(200); + expect(event?.response_code_line).toBe(2); + expect(event?.stages.map((stage) => stage.response_code)).toEqual([ + null, + 200, + 200, + ]); + expect(event?.unsupported_version).toBe(false); + expect(metadata.sample_missing_terminal_stage_count).toBe(0); + expect(metadata.unsampled_event_line_count).toBe(0); + expect(metadata.sample_duplicate_stage_line_count).toBe(0); +}); + +it("counts stage and verb totals across every line", async () => { + const metadata = await metadataOf( + [ + auditEvent({ + auditID: "00000000-0000-4000-8000-00000000000a", + verb: "get", + }), + auditEvent({ + auditID: "00000000-0000-4000-8000-00000000000b", + stage: "ResponseComplete", + verb: "delete", + responseCode: 403, + }), + ].join("\n"), + ); + expect(metadata.stage_counts).toEqual([ + { label: "RequestReceived", count: 1 }, + { label: "ResponseComplete", count: 1 }, + ]); + expect(metadata.verb_counts).toEqual([ + { label: "delete", count: 1 }, + { label: "get", count: 1 }, + ]); + expect(metadata.events.map((event) => event.audit_id)).toEqual([ + "00000000-0000-4000-8000-00000000000a", + "00000000-0000-4000-8000-00000000000b", + ]); + expect(metadata.events[1]?.response_code).toBe(403); + expect(metadata.sample_missing_terminal_stage_count).toBe(1); +}); + +it("keeps a stage the API does not define out of the inventory as a diagnostic", async () => { + const metadata = await metadataOf( + [ + auditEvent(), + JSON.stringify({ + auditID: "00000000-0000-4000-8000-00000000000c", + stage: "Started", + }), + "not json at all", + "", + ].join("\n"), + ); + expect(metadata.event_count).toBe(1); + expect(metadata.malformed_line_count).toBe(2); + expect(metadata.malformed_lines.map((line) => line.line)).toEqual([2, 3]); + expect(metadata.malformed_lines.map((line) => line.excerpt)).toEqual([ + JSON.stringify({ + auditID: "00000000-0000-4000-8000-00000000000c", + stage: "Started", + }), + "not json at all", + ]); +}); + +it("keeps a malformed line between two valid events from stopping the scan", async () => { + const metadata = await metadataOf( + [ + auditEvent({ auditID: "00000000-0000-4000-8000-00000000000d" }), + "{truncated", + auditEvent({ + auditID: "00000000-0000-4000-8000-00000000000e", + stage: "ResponseComplete", + }), + ].join("\n"), + ); + expect(metadata.event_count).toBe(2); + expect(metadata.malformed_line_count).toBe(1); + expect(metadata.events.map((event) => event.audit_id)).toEqual([ + "00000000-0000-4000-8000-00000000000d", + "00000000-0000-4000-8000-00000000000e", + ]); +}); + +it("counts a repeated stage for one auditID without dropping the line", async () => { + const metadata = await metadataOf( + [ + auditEvent({ stage: "ResponseComplete", responseCode: 200 }), + auditEvent({ stage: "ResponseComplete", responseCode: 500 }), + ].join("\n"), + ); + expect(metadata.event_count).toBe(2); + expect(metadata.sample_duplicate_stage_line_count).toBe(1); + expect(metadata.events).toHaveLength(1); + expect(metadata.events[0]?.stages.map((stage) => stage.line)).toEqual([1, 2]); + expect( + metadata.events[0]?.stages.map((stage) => stage.response_code), + ).toEqual([200, 500]); +}); + +it("retains the first late terminal stage and accounts for every discarded repeat", async () => { + const metadata = await metadataOf( + [ + auditEvent(), + auditEvent(), + auditEvent(), + auditEvent(), + auditEvent({ stage: "ResponseComplete", responseCode: 403 }), + auditEvent({ stage: "ResponseComplete", responseCode: 500 }), + ].join("\n"), + ); + const [event] = metadata.events; + expect( + event?.stages.map(({ line, response_code }) => [line, response_code]), + ).toEqual([ + [1, null], + [2, null], + [3, null], + [5, 403], + ]); + expect(event?.omitted_stage_lines).toBe(2); + expect(metadata.sample_duplicate_stage_line_count).toBe(4); + expect(metadata.sample_missing_terminal_stage_count).toBe(0); +}); + +it("treats a recorded Panic as terminal even when earlier stages are absent", async () => { + const metadata = await metadataOf( + auditEvent({ stage: "Panic", responseCode: 500 }), + ); + expect(metadata.sample_missing_terminal_stage_count).toBe(0); + expect(metadata.events[0]?.stages).toMatchObject([ + { stage: "Panic", response_code: 500 }, + ]); +}); + +it("reads a safe response code written with a very long zero fraction", async () => { + const metadata = await metadataOf( + `${auditEvent({ + stage: "ResponseComplete", + responseCode: 200, + }).replace('"code":200', `"code":200.${"0".repeat(80)}`)}\n`, + ); + expect(metadata.events[0]?.response_code).toBe(200); +}); + +it("reads a safe response code written with a long zero fraction", async () => { + const metadata = await metadataOf( + `${auditEvent({ + stage: "ResponseComplete", + responseCode: 200, + }).replace('"code":200', '"code":200.00000000000000000')}\n`, + ); + expect(metadata.events[0]?.response_code).toBe(200); + expect(metadata.events[0]?.stages[0]?.response_code).toBe(200); +}); + +it("keeps the widest safe integral response code", async () => { + const metadata = await metadataOf( + [ + auditEvent({ + stage: "ResponseStarted", + responseCode: Number.MAX_SAFE_INTEGER, + }), + auditEvent({ + stage: "ResponseComplete", + responseCode: -Number.MAX_SAFE_INTEGER, + }), + ].join("\n"), + ); + expect( + metadata.events[0]?.stages.map((stage) => stage.response_code), + ).toEqual([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER]); + expect(metadata.events[0]?.response_code).toBe(Number.MAX_SAFE_INTEGER); +}); + +it.each([ + ["2e2", 200], + ["-2e2", -200], + ["2.01e2", 201], + ["0.2e3", 200], + ["2.5e2", 250], + ["2.010e2", 201], + [`200.${"0".repeat(80)}`, 200], + [`0.${"0".repeat(41)}2e44`, 200], +])( + "keeps the safe integer a long number lexeme evaluates to (%s)", + async (lexeme, expected) => { + const encoded = auditEvent({ stage: "ResponseStarted" }).replace( + '"stage":"ResponseStarted"', + `"stage":"ResponseStarted","responseStatus":{"code":${lexeme}}`, + ); + const metadata = await metadataOf( + [ + encoded, + auditEvent({ stage: "ResponseComplete", responseCode: 403 }), + ].join("\n"), + ); + expect( + metadata.events[0]?.stages.map((stage) => stage.response_code), + ).toEqual([expected, 403]); + expect(metadata.events[0]?.response_code).toBe(expected); + }, +); + +it("drops a fractional status code whose exponent does not make it integral", async () => { + const metadata = await metadataOf( + [ + auditEvent({ stage: "ResponseStarted" }).replace( + '"stage":"ResponseStarted"', + '"stage":"ResponseStarted","responseStatus":{"code":2.5e0}', + ), + auditEvent({ stage: "ResponseComplete", responseCode: 403 }), + ].join("\n"), + ); + expect( + metadata.events[0]?.stages.map((stage) => stage.response_code), + ).toEqual([null, 403]); + expect(metadata.events[0]?.response_code).toBe(403); +}); + +it("drops a status code whose value is not a safe integer", async () => { + const metadata = await metadataOf( + auditEvent({ + stage: "ResponseComplete", + responseCode: Number.MAX_SAFE_INTEGER + 2, + }), + ); + expect(metadata.events[0]?.response_code).toBeNull(); +}); + +it("retains valid response facts when another stage has a fractional response code", async () => { + const metadata = await metadataOf( + [ + auditEvent({ stage: "ResponseStarted", responseCode: 200.5 }), + auditEvent({ stage: "ResponseComplete", responseCode: 403 }), + ].join("\n"), + ); + expect( + metadata.events[0]?.stages.map((stage) => stage.response_code), + ).toEqual([null, 403]); + expect(metadata.events[0]?.response_code).toBe(403); +}); + +it.each(["audit.k8s.io/v0", null])( + "does not interpret an unmodelled audit API version (%s)", + async (apiVersion) => { + const metadata = await metadataOf( + `${JSON.stringify({ + kind: "Event", + apiVersion, + auditID: "00000000-0000-4000-8000-00000000000f", + stage: "RequestReceived", + requestURI: "/api/v1/pods", + verb: "list", + responseStatus: { code: 200 }, + requestReceivedTimestamp: "2026-11-20T10:00:00Z", + })}\n`, + ); + const [event] = metadata.events; + expect(event?.unsupported_version).toBe(true); + expect(event?.audit_id).toBe("00000000-0000-4000-8000-00000000000f"); + expect(event?.stages.map((stage) => stage.stage)).toEqual([ + "RequestReceived", + ]); + expect(event?.request_uri).toBeNull(); + expect(event?.verb).toBeNull(); + expect(event?.response_code).toBeNull(); + expect(event?.stages[0]).toMatchObject({ + request_received_timestamp: null, + response_code: null, + }); + expect(metadata.verb_counts).toEqual([]); + }, +); + +it("reads request fields from the first modelled stage of a mixed-version auditID", async () => { + const metadata = await metadataOf( + [ + JSON.stringify({ + apiVersion: "audit.k8s.io/v9", + auditID: "mixed-early", + stage: "RequestReceived", + verb: "delete", + requestURI: "/secret", + requestReceivedTimestamp: "2026-11-20T10:00:00Z", + }), + JSON.stringify({ + apiVersion: "audit.k8s.io/v1", + auditID: "mixed-early", + stage: "ResponseComplete", + verb: "get", + requestURI: "/api/v1/pods", + responseStatus: { code: 403 }, + requestReceivedTimestamp: "2026-11-20T10:00:01Z", + }), + JSON.stringify({ + apiVersion: "audit.k8s.io/v1", + auditID: "mixed-late", + stage: "RequestReceived", + verb: "list", + requestURI: "/api/v1/namespaces", + }), + JSON.stringify({ + apiVersion: "audit.k8s.io/v9", + auditID: "mixed-late", + stage: "ResponseComplete", + verb: "delete", + requestURI: "/secret", + responseStatus: { code: 500 }, + }), + ].join("\n"), + ); + expect(metadata.events.map((event) => event.audit_id)).toEqual([ + "mixed-early", + "mixed-late", + ]); + expect(metadata.events[0]).toMatchObject({ + unsupported_version: true, + verb: "get", + request_uri: "/api/v1/pods", + response_code: 403, + response_code_line: 2, + }); + expect(metadata.events[0]?.stages).toMatchObject([ + { + stage: "RequestReceived", + line: 1, + response_code: null, + request_received_timestamp: null, + }, + { + stage: "ResponseComplete", + line: 2, + response_code: 403, + request_received_timestamp: Date.parse("2026-11-20T10:00:01Z"), + }, + ]); + expect(metadata.events[1]).toMatchObject({ + unsupported_version: true, + verb: "list", + request_uri: "/api/v1/namespaces", + response_code: null, + }); + expect(metadata.verb_counts).toEqual([ + { label: "get", count: 1 }, + { label: "list", count: 1 }, + ]); +}); + +it("reads a log that begins with blank lines or a UTF-8 BOM", async () => { + const metadata = await metadataOf(`\n\n\uFEFF${auditEvent()}\n`); + expect(metadata.line_count).toBe(3); + expect(metadata.event_count).toBe(1); + expect(metadata.malformed_line_count).toBe(0); + expect(metadata.events[0]?.request_uri).toBe( + "/api/v1/namespaces/default/pods", + ); +}); + +it("reads an optional field it did not get as null, not as empty text", async () => { + const metadata = await metadataOf( + `${JSON.stringify({ + kind: "Event", + auditID: "00000000-0000-4000-8000-000000000010", + stage: "RequestReceived", + })}\n`, + ); + const [event] = metadata.events; + expect(event?.request_uri).toBeNull(); + expect(event?.verb).toBeNull(); + expect(event?.username).toBeNull(); + expect(event?.user_groups).toBeNull(); + expect(event?.source_ips).toBeNull(); + expect(event?.resource).toBeNull(); + expect(event?.response_code).toBeNull(); + expect(event?.stages[0]?.request_received_timestamp).toBeNull(); +}); + +it("preserves explicitly empty groups and source IP arrays", async () => { + const metadata = await metadataOf(auditEvent({ groups: [], sourceIPs: [] })); + expect(metadata.events[0]).toMatchObject({ user_groups: [], source_ips: [] }); +}); + +it("parses the event's own requestReceivedTimestamp", async () => { + const metadata = await metadataOf( + `${auditEvent({ requestReceivedTimestamp: "2026-11-20T10:00:00.000000Z" })}\n`, + ); + expect(metadata.events[0]?.stages[0]?.request_received_timestamp).toBe( + Date.parse("2026-11-20T10:00:00.000Z"), + ); +}); + +it("keeps unstructured timestamps unknown", async () => { + const metadata = await metadataOf( + auditEvent({ requestReceivedTimestamp: "1" }), + ); + expect(metadata.events[0]?.stages[0]?.request_received_timestamp).toBeNull(); +}); + +it("samples a bounded window of events while totals cover the whole file", async () => { + const lines = Array.from( + { length: KUBERNETES_AUDIT_INLINE_EVENT_LIMIT + 5 }, + (_value, index) => + auditEvent({ + auditID: `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`, + }), + ); + const metadata = await metadataOf(`${lines.join("\n")}\n`); + expect(metadata.event_count).toBe(KUBERNETES_AUDIT_INLINE_EVENT_LIMIT + 5); + expect(metadata.events).toHaveLength(KUBERNETES_AUDIT_INLINE_EVENT_LIMIT); + expect(metadata.unsampled_event_line_count).toBe(5); + expect(metadata.events[0]?.audit_id).toBe( + "00000000-0000-4000-8000-000000000000", + ); +}); + +it("bounds retained request text and verb labels while stage totals cover the log", async () => { + const first = auditEvent({ + auditID: "first", + userAgent: "x".repeat(128 * 1024), + verb: "get", + }); + const next = Array.from( + { length: KUBERNETES_AUDIT_INLINE_VERB_LIMIT }, + (_value, index) => + auditEvent({ + auditID: `id-${String(index)}`, + verb: `verb-${String(index)}`, + }), + ); + const complete = auditEvent({ + auditID: "first", + stage: "ResponseComplete", + verb: "get", + responseCode: 403, + }); + const metadata = await metadataOf([first, ...next, complete].join("\n")); + expect(metadata.events[0]).toMatchObject({ + audit_id: "first", + user_agent: null, + request_uri: "/api/v1/namespaces/default/pods", + request_fields_omitted: true, + response_code: 403, + }); + expect(metadata.verb_counts).toHaveLength(KUBERNETES_AUDIT_INLINE_VERB_LIMIT); + expect(metadata.verb_counts).toContainEqual({ label: "get", count: 2 }); + expect(metadata.unlisted_verb_line_count).toBe(1); + expect(metadata.unsampled_event_line_count).toBe(1); + expect(metadata.event_count).toBe(next.length + 2); +}); + +it("skips an ignored body and still reads fields written after it", async () => { + const nest = `${"[".repeat(8)}1${"]".repeat(8)}`; + const metadata = await metadataOf( + `{"auditID":"ordered","stage":"ResponseComplete","requestObject":${nest},"requestURI":"/after","verb":"list","responseStatus":{"code":201},"user":{"username":"ada","groups":["system:authenticated"]}}\n`, + ); + expect(metadata.malformed_line_count).toBe(0); + expect(metadata.events[0]).toMatchObject({ + audit_id: "ordered", + request_uri: "/after", + verb: "list", + username: "ada", + user_groups: ["system:authenticated"], + response_code: 201, + stages: [{ stage: "ResponseComplete" }], + }); +}); + +it("keeps owned fields when an ignored body exceeds the nesting bound", async () => { + const nest = `${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}`; + const deep = `{"apiVersion":"audit.k8s.io/v1","auditID":"deep","stage":"RequestReceived","requestURI":"/api/v1/pods","verb":"get","requestObject":${nest}}`; + const hidden = `{"requestObject":${nest},"auditID":"hidden","stage":"RequestReceived","requestURI":"/hidden"}`; + const metadata = await metadataOf( + `${deep}\n${hidden}\n${auditEvent({ + auditID: "after", + stage: "ResponseComplete", + responseCode: 200, + })}\n`, + ); + expect(metadata.events.map((event) => event.audit_id)).toEqual([ + "deep", + "after", + ]); + expect(metadata.events[0]).toMatchObject({ + request_uri: "/api/v1/pods", + verb: "get", + unsupported_version: false, + depth_limited: true, + }); + expect(metadata.events[1]?.depth_limited).toBe(false); + expect(metadata.malformed_line_count).toBe(0); + expect(metadata.depth_limited_line_count).toBe(2); + expect(metadata.event_count).toBe(2); +}); + +it("leaves a wrong-shaped version or address list unknown", async () => { + const metadata = await metadataOf( + [ + '{"apiVersion":{},"auditID":"shaped","stage":"RequestReceived","verb":"get","requestURI":"/secret"}', + '{"apiVersion":"audit.k8s.io/v1","auditID":"addrs","stage":"ResponseComplete","sourceIPs":["10.0.0.1",{}],"verb":"get"}', + ].join("\n"), + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "shaped", + unsupported_version: true, + verb: null, + request_uri: null, + }); + expect(metadata.events[1]).toMatchObject({ + audit_id: "addrs", + unsupported_version: false, + source_ips: null, + verb: "get", + }); + expect(metadata.malformed_line_count).toBe(0); +}); + +it("does not retain a source address list past the list text budget", async () => { + const addresses = Array.from({ length: 5000 }, () => "10.0.0.1"); + const metadata = await metadataOf( + `${JSON.stringify({ + apiVersion: "audit.k8s.io/v1", + auditID: "many-ips", + stage: "RequestReceived", + verb: "get", + requestURI: "/api", + sourceIPs: addresses, + })}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "many-ips", + request_uri: "/api", + verb: "get", + source_ips: null, + request_fields_omitted: true, + }); +}); + +it("does not interpret fields when the depth cap hides apiVersion", async () => { + const nest = `${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}`; + const metadata = await metadataOf( + `{"auditID":"cut","stage":"RequestReceived","verb":"delete","requestURI":"/secret","requestObject":${nest},"apiVersion":"audit.k8s.io/v100"}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "cut", + verb: null, + request_uri: null, + depth_limited: true, + unsupported_version: false, + }); + expect(metadata.verb_counts).toEqual([]); +}); + +it("clears a response object when a later array replaces it", async () => { + const metadata = await metadataOf( + '{"auditID":"replaced-array","stage":"ResponseComplete","responseStatus":{"code":403},"responseStatus":[],"verb":"get"}\n', + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "replaced-array", + verb: "get", + response_code: null, + }); +}); + +it("drops an address list when a later list is cut off by depth", async () => { + const nest = `${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}`; + const metadata = await metadataOf( + `{"apiVersion":"audit.k8s.io/v1","auditID":"ips","stage":"RequestReceived","verb":"get","sourceIPs":["10.0.0.1"],"sourceIPs":${nest}}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "ips", + source_ips: null, + verb: "get", + depth_limited: true, + }); +}); + +it("clears groups when a later scalar replaces the list", async () => { + const metadata = await metadataOf( + '{"auditID":"groups","stage":"RequestReceived","user":{"username":"ada","groups":["system:authenticated"]},"user":{"username":"ada","groups":null},"verb":"get"}\n', + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "groups", + username: "ada", + user_groups: null, + verb: "get", + }); +}); + +it("does not clear a nested omission from a same-named top-level key", async () => { + const metadata = await metadataOf( + `{"apiVersion":"audit.k8s.io/v1","auditID":"nested","stage":"RequestReceived","requestURI":"/api","verb":"get","user":{"username":"${"x".repeat(200_000)}"},"user.username":null}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "nested", + request_uri: "/api", + username: null, + request_fields_omitted: true, + }); +}); + +it("clears budget omission when a later null replaces an address list", async () => { + const addresses = Array.from({ length: 5000 }, () => "10.0.0.1"); + const first = JSON.stringify({ + apiVersion: "audit.k8s.io/v1", + auditID: "ips-null", + stage: "RequestReceived", + verb: "get", + requestURI: "/api", + sourceIPs: addresses, + }); + const metadata = await metadataOf( + `${first.slice(0, -1)},"sourceIPs":null}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "ips-null", + request_uri: "/api", + source_ips: null, + request_fields_omitted: false, + }); +}); + +it("clears budget omission when a later object replaces an address list", async () => { + const addresses = Array.from({ length: 5000 }, () => "10.0.0.1"); + const first = JSON.stringify({ + apiVersion: "audit.k8s.io/v1", + auditID: "ips-object", + stage: "RequestReceived", + verb: "get", + requestURI: "/api", + sourceIPs: addresses, + }); + const metadata = await metadataOf(`${first.slice(0, -1)},"sourceIPs":{}}\n`); + expect(metadata.events[0]).toMatchObject({ + audit_id: "ips-object", + request_uri: "/api", + source_ips: null, + request_fields_omitted: false, + }); +}); + +it("clears budget omission when a later null replaces the value", async () => { + const metadata = await metadataOf( + `{"apiVersion":"audit.k8s.io/v1","auditID":"agent-null","stage":"RequestReceived","requestURI":"/api","verb":"get","userAgent":"${"x".repeat(200_000)}","userAgent":null}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "agent-null", + request_uri: "/api", + verb: "get", + user_agent: null, + request_fields_omitted: false, + }); +}); + +it("keeps a small duplicate after an over-budget value", async () => { + const metadata = await metadataOf( + `{"apiVersion":"audit.k8s.io/v1","auditID":"agent","stage":"RequestReceived","requestURI":"/api","verb":"get","userAgent":"${"x".repeat(200_000)}","userAgent":"kubectl"}\n`, + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "agent", + request_uri: "/api", + verb: "get", + user_agent: "kubectl", + request_fields_omitted: false, + }); +}); + +it("drops a response object when a later value replaces it", async () => { + const metadata = await metadataOf( + '{"auditID":"replaced","stage":"ResponseComplete","responseStatus":{"code":403},"responseStatus":null,"verb":"get"}\n', + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "replaced", + verb: "get", + response_code: null, + response_code_line: null, + }); +}); + +it("does not read audit identity from inside an ignored body", async () => { + const metadata = await metadataOf( + '{"auditID":"top","stage":"RequestReceived","requestURI":"/top","requestObject":{"auditID":"nested","stage":"Panic","verb":"delete"}}\n', + ); + expect(metadata.events[0]).toMatchObject({ + audit_id: "top", + request_uri: "/top", + verb: null, + stages: [{ stage: "RequestReceived" }], + }); + expect(metadata.stage_counts).toEqual([ + { label: "RequestReceived", count: 1 }, + ]); +}); + +it("retains small request fields alongside an ignored response body", async () => { + const metadata = await metadataOf( + auditEvent({ + stage: "ResponseComplete", + responseCode: 403, + responseBody: { data: "x".repeat(200 * 1024) }, + }), + ); + expect(metadata.events[0]).toMatchObject({ + request_uri: "/api/v1/namespaces/default/pods", + username: "system:serviceaccount:default:reader", + user_groups: ["system:serviceaccounts", "system:authenticated"], + source_ips: ["10.0.0.7"], + response_code: 403, + request_fields_omitted: false, + }); +}); + +it("bounds the inline diagnostics while counting every malformed line", async () => { + const lines = Array.from( + { length: KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT + 3 }, + (_value, index) => `{"line":${String(index)}}`, + ); + const metadata = await metadataOf(`${[auditEvent(), ...lines].join("\n")}\n`); + expect(metadata.malformed_line_count).toBe( + KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT + 3, + ); + expect(metadata.malformed_lines).toHaveLength( + KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT, + ); + expect(metadata.omitted_malformed_lines).toBe(3); +}); + +it("reports a trailing line that the file ended without a newline", async () => { + const metadata = await metadataOf(`${auditEvent()}`); + expect(metadata.trailing_bytes).toBeGreaterThan(0); + expect(metadata.event_count).toBe(1); +}); + +it("counts the full size of an overlong unterminated line without retaining it", async () => { + const trailing = "x".repeat(4 * 1024 * 1024 + 128 * 1024); + const metadata = await metadataOf(`${auditEvent()}\n${trailing}`); + expect(metadata.trailing_bytes).toBe(trailing.length); + expect(metadata.oversized_line_count).toBe(1); + expect(metadata.malformed_line_count).toBe(0); + expect(metadata.event_count).toBe(1); + expect(metadata.line_bytes_limit).toBe(4 * 1024 * 1024); + expect(metadata.events).toHaveLength(1); +}); + +it("refuses a file whose lines are not audit events as malformed", async () => { + const reader = new KubernetesAuditLogArtifactReader( + await writeLog("audit.log", "hello\nworld\n"), + ); + try { + await expect(async () => { + for await (const _entry of reader.entries()) { + // No members. + } + }).rejects.toMatchObject({ reason: "malformed" }); + } finally { + await reader.close(); + } +}); + +it("reports cancellation requested from the coverage callback", async () => { + const reader = new KubernetesAuditLogArtifactReader( + await writeLog("audit.log", `${REQUEST}\n`), + ); + const controller = new AbortController(); + try { + const entries = reader + .entries(controller.signal, { + onCoverage: () => controller.abort(), + }) + [Symbol.asyncIterator](); + await expect(entries.next()).rejects.toMatchObject({ reason: "cancelled" }); + } finally { + await reader.close(); + } +}); + +it("reports no members to open", async () => { + const reader = new KubernetesAuditLogArtifactReader( + await writeLog("audit.log", `${REQUEST}\n`), + ); + await expect( + reader.open({ + path: "audit.log", + kind: "file", + declaredSize: null, + compressedSize: null, + executable: false, + encrypted: false, + byteOffset: null, + declaredIntegrity: null, + unpacked: false, + limitations: [], + adapterKey: "root", + }), + ).rejects.toMatchObject({ reason: "unavailable" }); + await reader.close(); +}); + +it("does not count a dropped verb when the audit version was not read", async () => { + const nest = `${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}`; + const cut = `{"auditID":"cut-verb","stage":"RequestReceived","verb":"${"v".repeat(200_000)}","requestObject":${nest}}`; + const metadata = await metadataOf(`${cut}\n${auditEvent({ verb: "get" })}\n`); + expect(metadata.depth_limited_line_count).toBe(1); + expect(metadata.unlisted_verb_line_count).toBe(0); + expect(metadata.verb_counts).toEqual([{ label: "get", count: 1 }]); + expect(metadata.events[0]).toMatchObject({ + audit_id: "cut-verb", + verb: null, + depth_limited: true, + }); +}); + +it("counts a dropped verb on an interpreted audit line as unlisted", async () => { + const metadata = await metadataOf( + `${auditEvent({ verb: "v".repeat(200_000) })}\n`, + ); + expect(metadata.unlisted_verb_line_count).toBe(1); + expect(metadata.verb_counts).toEqual([]); + expect(metadata.events[0]?.verb).toBeNull(); + expect(metadata.events[0]?.request_fields_omitted).toBe(true); +}); + +it("fills request fields from a readable stage after a depth-cut first one", async () => { + const nest = `${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH)}`; + const cut = `{"auditID":"late-fill","stage":"RequestReceived","requestObject":${nest},"apiVersion":"audit.k8s.io/v1"}`; + const readable = auditEvent({ + auditID: "late-fill", + stage: "ResponseComplete", + requestURI: "/api/v1/namespaces/default/pods", + verb: "delete", + username: "ada", + responseCode: 403, + }); + const metadata = await metadataOf(`${cut}\n${readable}\n`); + expect(metadata.events[0]).toMatchObject({ + audit_id: "late-fill", + request_uri: "/api/v1/namespaces/default/pods", + verb: "delete", + username: "ada", + response_code: 403, + depth_limited: true, + }); +}); diff --git a/src/artifacts/KubernetesAuditLogArtifactReader.ts b/src/artifacts/KubernetesAuditLogArtifactReader.ts new file mode 100644 index 0000000000..d093f2bb16 --- /dev/null +++ b/src/artifacts/KubernetesAuditLogArtifactReader.ts @@ -0,0 +1,207 @@ +import type { Readable } from "node:stream"; + +import { + DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS, + type KubernetesAuditLogReaderLimits, +} from "../domain/artifactReaderLimits.js"; +import type { ArtifactFormatMetadata } from "../domain/artifactFormatMetadata.js"; +import { kubernetesAuditLogMetadataSchema } from "../domain/formatMetadata/androidAndSystemMetadata.js"; +import type { RegionDecodeFailure } from "../domain/firmware/regionDecoder.js"; +import { + KUBERNETES_AUDIT_LOG_MAX_FILE_BYTES, + createKubernetesAuditLogDecoder, + type KubernetesAuditInventory, +} from "../domain/linux/kubernetesAuditLog.js"; +import { + artifactFixedLimitFailure, + ArtifactReaderFailure, + malformedArtifact, + type ArtifactEntry, + type ArtifactReader, + type ArtifactTraversalOptions, + ArtifactResourceScope, + assertArtifactReadActive, + ArtifactFileSource, + yieldArtifactRead, +} from "../resources/index.js"; +import { ArtifactPreparation } from "./ArtifactPreparation.js"; +import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js"; +import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; + +/** + * A Kubernetes audit log is its own content: its lines describe requests to the + * source cluster, not members inside the file, so the inventory is attached to + * the root occurrence and there is nothing to open. + */ +export class KubernetesAuditLogArtifactReader implements ArtifactReader { + readonly format = "kubernetes-audit-log" as const; + readonly #scope = new ArtifactResourceScope(); + readonly #source: ArtifactFileSource; + readonly #lineBytes: number; + readonly #preparation = new ArtifactPreparation(); + #metadata: ArtifactFormatMetadata | undefined; + #limitations: readonly string[] = []; + #closing = false; + + constructor( + path: string, + admitted?: StableRegularFileDescriptor, + limits: KubernetesAuditLogReaderLimits = DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS, + ) { + this.#lineBytes = limits.line_bytes; + this.#source = new ArtifactFileSource( + path, + "Kubernetes audit log", + admitted, + ); + } + + formatMetadata(): ArtifactFormatMetadata | undefined { + return this.#metadata === undefined + ? undefined + : structuredClone(this.#metadata); + } + + async prepareContainer( + expectedSha256: string, + signal?: AbortSignal, + ): Promise { + await this.#scope.run(async () => { + this.#assertOpen(signal); + await this.#source.bindSha256(expectedSha256, signal); + }); + } + + async *entries( + signal?: AbortSignal, + options?: ArtifactTraversalOptions, + ): AsyncIterable { + await this.#scope.run(async () => { + this.#assertOpen(signal); + await this.#preparation.run( + signal, + () => this.#prepare(signal), + () => this.#assertOpen(signal), + ); + this.#assertOpen(signal); + await this.#source.read(signal); + }); + // The log declares no members, so the root occurrence is the whole + // inventory; the coverage callback reports what the parse did not establish. + const coverage = + this.#limitations.length === 0 + ? { status: "complete" as const, limitations: [] } + : { status: "unknown" as const, limitations: [...this.#limitations] }; + options?.onCoverage?.(coverage); + // onCoverage may abort the supplied signal; cancellation queued during the + // await must resolve as cancelled rather than as a completed traversal. + await yieldArtifactRead(signal); + } + + async open(entry: ArtifactEntry, _signal?: AbortSignal): Promise { + return this.#scope.run(async () => { + throw new ArtifactReaderFailure( + "unavailable", + `Kubernetes audit log declares no member to open for ${entry.path}`, + ); + }); + } + + async close(): Promise { + this.#closing = true; + await this.#scope.close(); + await this.#source.close(); + this.#metadata = undefined; + } + + provenance(): readonly [] { + return []; + } + + #assertOpen(signal?: AbortSignal): void { + assertArtifactReadActive(signal); + if (this.#closing) + throw new ArtifactReaderFailure( + "unavailable", + "Kubernetes audit log reader is closed", + ); + } + + async #prepare(signal?: AbortSignal): Promise { + const image = await this.#decode(signal); + const metadata = kubernetesAuditLogMetadataSchema.parse(image.metadata); + // The final read re-verifies the source; publishing the inventory before it + // succeeds would leave `formatMetadata()` returning facts whose source + // identity was never confirmed. + await this.#source.read(signal); + this.#metadata = metadata; + this.#limitations = image.limitations; + } + + async #decode(signal?: AbortSignal): Promise { + const { handle, initial } = await this.#source.read(signal); + const decoder = createKubernetesAuditLogDecoder( + initial.size, + this.#lineBytes, + ); + if (!decoder.ok) throw this.#failure(decoder.error); + if (initial.size > 0) + for await (const chunk of readFileHandleChunks(handle, { + end: initial.size - 1, + signal, + cancellationFailure: (reason) => + new ArtifactReaderFailure( + "cancelled", + "Kubernetes audit log read cancelled", + { cause: reason }, + ), + }) as AsyncIterable) { + this.#assertOpen(signal); + // The scanner joins lines and keeps only aggregate facts, so each + // chunk's work is bounded and cancellation is never blocked on a + // whole-file buffer. + const written = decoder.value.write(chunk); + if (!written.ok) throw await this.#stableFailure(written.error, signal); + } + const image = decoder.value.finish(); + if (!image.ok) throw await this.#stableFailure(image.error, signal); + return image.value; + } + + /** + * A decoder failure blames the bytes only once the source is shown to be + * unchanged; a source that shrank or was replaced reports that instead, so an + * analyst does not read "malformed" for a file that changed mid-read. + */ + async #stableFailure( + failure: RegionDecodeFailure, + signal: AbortSignal | undefined, + ): Promise { + await this.#source.read(signal); + return this.#failure(failure); + } + + #failure(failure: RegionDecodeFailure): ArtifactReaderFailure { + if (failure.kind === "limit") + return artifactFixedLimitFailure( + { + name: "The Kubernetes audit log file-size ceiling", + kind: "input", + limit: KUBERNETES_AUDIT_LOG_MAX_FILE_BYTES, + unit: "bytes", + }, + `Kubernetes audit log exceeds a fixed limit: ${failure.message}`, + failure.boundary ?? "capacity", + ); + return failure.kind === "malformed" + ? malformedArtifact( + this.format, + `Kubernetes audit log is malformed: ${failure.message}`, + ) + : new ArtifactReaderFailure( + "limit", + `Kubernetes audit log exceeds a fixed limit: ${failure.message}`, + failure.boundary === undefined ? {} : { boundary: failure.boundary }, + ); + } +} diff --git a/src/artifacts/artifactFormats.ts b/src/artifacts/artifactFormats.ts index eb26e86cd2..31f09e5aec 100644 --- a/src/artifacts/artifactFormats.ts +++ b/src/artifacts/artifactFormats.ts @@ -61,6 +61,7 @@ import { UefiArtifactReader } from "../uefi/UefiArtifactReader.js"; import { Uf2ArtifactReader } from "./Uf2ArtifactReader.js"; import { NtfsMftArtifactReader } from "./NtfsMftArtifactReader.js"; import { AuditdLogArtifactReader } from "./AuditdLogArtifactReader.js"; +import { KubernetesAuditLogArtifactReader } from "./KubernetesAuditLogArtifactReader.js"; import { AndroidOtaPayloadArtifactReader } from "./AndroidOtaPayloadArtifactReader.js"; import { SystemdJournalArtifactReader } from "./SystemdJournalArtifactReader.js"; import { AndroidSparseImageArtifactReader } from "./AndroidSparseImageArtifactReader.js"; @@ -828,6 +829,19 @@ const NON_ZIP_FORMATS = { createReader: (path, options) => new AuditdLogArtifactReader(path, sourceOf(options)), }), + "kubernetes-audit-log": described("kubernetes-audit-log", { + ...plain, + role: "resource", + retainClassifiedSource: true, + readerLimitation: + "Kubernetes audit log inventory reports line, stage and verb totals and a bounded sample of requests joined by auditID. It counts malformed lines, oversized record skips, repeated stages, and requests without a recorded terminal stage. Set artifact_limits.kubernetes_audit_log.line_bytes to change the per-record allowance. Request and response object bodies, annotations, impersonation metadata and audit policy are not interpreted. Source completeness and authenticity are unknown.", + createReader: (path, options) => + new KubernetesAuditLogArtifactReader( + path, + sourceOf(options), + options.readerLimits?.kubernetes_audit_log, + ), + }), unknown: described("unknown", plain), } satisfies Record< Exclude, diff --git a/src/artifacts/inventory/ArtifactGraphConstruction.ts b/src/artifacts/inventory/ArtifactGraphConstruction.ts index fc4a8b3afd..51b24b7bff 100644 --- a/src/artifacts/inventory/ArtifactGraphConstruction.ts +++ b/src/artifacts/inventory/ArtifactGraphConstruction.ts @@ -659,6 +659,7 @@ export const classifyArtifactHeader = ( suffix, iso9660Descriptor, xmlPlistSignature: evidence.xmlPlistSignature, + kubernetesAuditEvent: evidence.kubernetesAuditEvent, }); if (recognized !== undefined) return only(recognized); const fatFormat = classifyFatArtifact(evidence); diff --git a/src/domain/artifactFormatMetadata.ts b/src/domain/artifactFormatMetadata.ts index 8f2bc11685..225d868355 100644 --- a/src/domain/artifactFormatMetadata.ts +++ b/src/domain/artifactFormatMetadata.ts @@ -64,6 +64,7 @@ import { androidVbmetaMetadataSchema, androidSparseImageMetadataSchema, auditdLogMetadataSchema, + kubernetesAuditLogMetadataSchema, iso9660EntryMetadataSchema, iso9660MetadataSchema, ntfsMftMetadataSchema, @@ -124,6 +125,7 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [ ntfsMftMetadataSchema, systemdJournalMetadataSchema, auditdLogMetadataSchema, + kubernetesAuditLogMetadataSchema, dfuSeMetadataSchema, dfuSeElementMetadataSchema, bfltMetadataSchema, @@ -416,6 +418,10 @@ const declarationsByKind: { notCompared: "Its fields come from the file's own record headers, which content comparison covers.", }, + "kubernetes-audit-log": { + notCompared: + "Its fields come from the file's own audit event lines, which content comparison covers.", + }, dfuse: { notCompared: "Its fields come from the file's own prefix, target headers and suffix, which content comparison covers.", diff --git a/src/domain/artifactFormatRecognition.test.ts b/src/domain/artifactFormatRecognition.test.ts index bdca7a4e8a..873bf59a21 100644 --- a/src/domain/artifactFormatRecognition.test.ts +++ b/src/domain/artifactFormatRecognition.test.ts @@ -13,6 +13,9 @@ import { recognizeArtifactFormat, recognizesArtifactPrefix, } from "./artifactFormatRecognition.js"; +import { MAX_KUBERNETES_AUDIT_LINE_BYTES } from "./artifactReaderLimits.js"; +import { KubernetesAuditEventProbe } from "./linux/kubernetesAuditEventProbe.js"; +import { KUBERNETES_AUDIT_JSON_DEPTH } from "./linux/kubernetesAuditRecord.js"; import { fullAndroidOtaPayload, v1AndroidOtaPayload, @@ -270,6 +273,133 @@ it("decides an auditd claim on a multi-megabyte prefix without overflowing the s }); }); +it("recognizes a Kubernetes audit log by its first event and leaves other JSON alone", () => { + const event = Buffer.from( + `${JSON.stringify({ + kind: "Event", + apiVersion: "audit.k8s.io/v1", + auditID: "0f5e3b1c-0000-4000-8000-000000000001", + stage: "RequestReceived", + requestURI: "/api/v1/namespaces/default/pods", + })}\n`, + ); + expect(recognize(event)).toMatchObject({ + state: "recognized", + format: "kubernetes-audit-log", + }); + // A JSON object without an auditID, or with a stage the API does not define, + // is not a claim this format makes. + expect( + recognize( + Buffer.from( + `${JSON.stringify({ kind: "Pod", stage: "RequestReceived" })}\n`, + ), + ), + ).toBeUndefined(); + expect( + recognize( + Buffer.from(`${JSON.stringify({ auditID: "a", stage: "Started" })}\n`), + ), + ).toBeUndefined(); +}); + +it("recognizes an audit record after a BOM or blank lines and ignores other padding", () => { + const record = JSON.stringify({ + auditID: "a", + stage: "RequestReceived", + }); + expect(recognize(Buffer.from(`\n\n${record}\n`))).toMatchObject({ + state: "recognized", + format: "kubernetes-audit-log", + }); + expect( + recognize( + Buffer.concat([ + Buffer.from([0xef, 0xbb, 0xbf]), + Buffer.from(`${record}\n`), + ]), + ), + ).toMatchObject({ + state: "recognized", + format: "kubernetes-audit-log", + }); + expect(recognize(Buffer.from(`\u00A0${record}\n`))).toBeUndefined(); + expect(recognize(Buffer.from(`\n{"payload":${record}}\n`))).toBeUndefined(); + expect( + recognizeArtifactFormat({ + prefix: Buffer.from("\n"), + fileSize: Buffer.byteLength(`\n${record}\n`), + espFlashLayout: false, + }), + ).toMatchObject({ + state: "needs-input", + format: "kubernetes-audit-log", + }); + const probe = new KubernetesAuditEventProbe(); + const head = Buffer.from([0xef, 0xbb]); + const tail = Buffer.concat([ + Buffer.from([0xbf]), + Buffer.from(`\n${record}\n`), + ]); + probe.write(head); + probe.write(tail); + expect(probe.finish(head.length + tail.length)).toBe(true); + const nest = `{"x":${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}}`; + expect(() => recognize(Buffer.from(nest))).not.toThrow(); + expect(recognize(Buffer.from(nest))).toBeUndefined(); + const claimed = `{"pad":"${"x".repeat(5000)}","auditID":"a","stage":"RequestReceived","requestObject":${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}}`; + const inline = `{"auditID":"a","stage":"RequestReceived","requestObject":${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}}`; + expect(recognize(Buffer.from(inline))).toMatchObject({ + state: "recognized", + format: "kubernetes-audit-log", + }); + const replaced = `{"auditID":"a","stage":"RequestReceived","pad":"${"y".repeat(5000)}","stage":"Unknown","requestObject":${"[".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}1${"]".repeat(KUBERNETES_AUDIT_JSON_DEPTH + 8)}}`; + expect(recognize(Buffer.from(replaced))).toBeUndefined(); + expect(recognize(Buffer.from(claimed))).toMatchObject({ + state: "recognized", + format: "kubernetes-audit-log", + }); + const padding = Buffer.alloc(MAX_KUBERNETES_AUDIT_LINE_BYTES, 0x0a); + const padded = Buffer.concat([padding, Buffer.from(`${record}\n`)]); + const probeAfterPadding = new KubernetesAuditEventProbe(); + probeAfterPadding.write(padding); + expect(probeAfterPadding.pending).toBe(true); + probeAfterPadding.write(Buffer.from(`${record}\n`)); + expect(probeAfterPadding.finish(padded.length)).toBe(true); + expect(recognize(padded)).toMatchObject({ + state: "recognized", + format: "kubernetes-audit-log", + }); +}); + +it("does not claim JSON with nested or malformed Kubernetes audit fields", () => { + for (const line of [ + '{"payload":{"auditID":"a","stage":"RequestReceived"}}', + '{"auditID":"a","payload":[{"stage":"RequestReceived"}]}', + '{"stage":"RequestReceived","payload":{"auditID":"a"}}', + '{"auditID":42,"stage":"RequestReceived"}', + '{"auditID":"a","stage":"RequestReceived","stage":"Unknown"}', + '{"auditID":"a","stage":"RequestReceived","invalid":', + ]) + expect(recognize(Buffer.from(line))).toBeUndefined(); +}); + +it("seeks the remainder after seeing audit fields in a clipped JSON prefix", () => { + const first = String.raw`{"auditID":"a","st\u0061ge":"RequestReceived","requestObject":{"message":"`; + const document = Buffer.from(`${first}€"}}\n`); + const clipped = document.subarray(0, Buffer.byteLength(first) + 1); + expect( + recognizeArtifactFormat({ + prefix: clipped, + fileSize: document.length, + espFlashLayout: false, + }), + ).toMatchObject({ + state: "needs-input", + format: "kubernetes-audit-log", + }); +}); + it("recognizes an Android sparse image by its 0xED26FF3A magic", () => { expect(recognize(mixedAndroidSparseImage())).toMatchObject({ state: "recognized", diff --git a/src/domain/artifactFormatRecognition.ts b/src/domain/artifactFormatRecognition.ts index 8df44e8f60..75bd462d3b 100644 --- a/src/domain/artifactFormatRecognition.ts +++ b/src/domain/artifactFormatRecognition.ts @@ -32,6 +32,10 @@ import { hasUnityFsHeader } from "./unityfsFormat.js"; import { hasMftFileRecordHeader } from "./windows/ntfsMft.js"; import { hasSystemdJournalHeader } from "./linux/systemdJournal.js"; import { hasAuditdLogRecord } from "./linux/auditdLog.js"; +import { + hasKubernetesAuditEvent, + kubernetesAuditNeedsMore, +} from "./linux/kubernetesAuditEventProbe.js"; import { hasWindowsShortcutHeader } from "./windows/windowsShortcutHeader.js"; import { BinaryFormatFailure } from "./binaryContainer.js"; import { @@ -101,6 +105,7 @@ export type RecognizedArtifactFormat = Extract< | "ntfs-mft" | "systemd-journal" | "auditd-log" + | "kubernetes-audit-log" | "plist" | StandaloneArtifactFormat >; @@ -141,6 +146,8 @@ export interface ArtifactRecognitionInput { * route has read them and the prefix does not reach them. */ readonly iso9660Descriptor?: Uint8Array | undefined; + /** Result of the bounded continuation when the fixed prefix was insufficient. */ + readonly kubernetesAuditEvent?: boolean | undefined; } /** @@ -337,6 +344,16 @@ export const ARTIFACT_FORMAT_RECOGNIZERS: readonly ArtifactFormatRecognizer[] = when("ntfs-mft", hasMftFileRecordHeader), when("systemd-journal", hasSystemdJournalHeader), when("auditd-log", hasAuditdLogRecord), + ({ prefix, fileSize, kubernetesAuditEvent }) => { + if ( + kubernetesAuditEvent === undefined && + kubernetesAuditNeedsMore(prefix, fileSize) + ) + return { state: "needs-input", format: "kubernetes-audit-log" }; + return (kubernetesAuditEvent ?? hasKubernetesAuditEvent(prefix, fileSize)) + ? { state: "recognized", format: "kubernetes-audit-log" } + : undefined; + }, when("sqlite", hasSqliteHeader), when("windows-shortcut", hasWindowsShortcutHeader), when("deb", hasDebPackageHeader), diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts index deb60f5bf4..9bf5baf36c 100644 --- a/src/domain/artifactGraph.ts +++ b/src/domain/artifactGraph.ts @@ -130,6 +130,7 @@ export const ARTIFACT_FORMAT_IDS = [ "ntfs-mft", "systemd-journal", "auditd-log", + "kubernetes-audit-log", "sqlite", "windows-shortcut", "python-pyc", @@ -186,6 +187,7 @@ const artifactContentFormatSchema = artifactFormatSchema.extract([ "ntfs-mft", "systemd-journal", "auditd-log", + "kubernetes-audit-log", "mach-o-universal", "mach-o", "elf", diff --git a/src/domain/artifactReaderLimits.ts b/src/domain/artifactReaderLimits.ts index cc01327fe7..135c4473db 100644 --- a/src/domain/artifactReaderLimits.ts +++ b/src/domain/artifactReaderLimits.ts @@ -217,6 +217,19 @@ export const tarReaderLimitsSchema = z.strictObject({ }); export type TarReaderLimits = z.output; +/** Kubernetes audit JSON is decoded one line at a time. */ +export const DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS = { + line_bytes: 4 * 1024 * 1024, +}; +/** Bound the one-line UTF-8 and JSON decoder working set. */ +export const MAX_KUBERNETES_AUDIT_LINE_BYTES = 16 * 1024 * 1024; +const kubernetesAuditLogReaderLimitsSchema = z.strictObject({ + line_bytes: bytes.max(MAX_KUBERNETES_AUDIT_LINE_BYTES), +}); +export type KubernetesAuditLogReaderLimits = z.output< + typeof kubernetesAuditLogReaderLimitsSchema +>; + /** Input selections preserve omission; only the producing operation resolves defaults. */ export const artifactReaderLimitsInputSchema = z.strictObject({ bun: z @@ -391,6 +404,15 @@ export const artifactReaderLimitsInputSchema = z.strictObject({ .describe( `tar admission; omitted fields use ${JSON.stringify(DEFAULT_TAR_READER_LIMITS)}. Extended-header bytes bound one pax or GNU long-name record; metadata bytes bound retained member metadata.`, ), + kubernetes_audit_log: z + .strictObject({ + line_bytes: + kubernetesAuditLogReaderLimitsSchema.shape.line_bytes.exactOptional(), + }) + .exactOptional() + .describe( + `Kubernetes audit log admission; omitted fields use ${JSON.stringify(DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS)}. Line bytes bound one JSON record before decoding.`, + ), expanded_bytes: bytes .exactOptional() .describe( @@ -413,6 +435,7 @@ const readerLimitGroups = { deno: denoReaderLimitsSchema, wxapkg: wxapkgReaderLimitsSchema, tar: tarReaderLimitsSchema, + kubernetes_audit_log: kubernetesAuditLogReaderLimitsSchema, } as const; const resolvedArtifactReaderLimitsSchema = z.strictObject({ @@ -423,13 +446,14 @@ export type ArtifactReaderLimits = z.output< typeof resolvedArtifactReaderLimitsSchema >; -// Earlier Evidence may omit the later vbmeta, sparse-image, media and DTBO policies. +// Earlier Evidence may omit reader policies added in later versions. export const artifactReaderLimitsSchema = resolvedArtifactReaderLimitsSchema.extend({ android_vbmeta: androidVbmetaReaderLimitsSchema.exactOptional(), android_sparse_image: androidSparseImageReaderLimitsSchema.exactOptional(), media_asset: mediaAssetReaderLimitsSchema.exactOptional(), android_dtbo: androidDtboReaderLimitsSchema.exactOptional(), + kubernetes_audit_log: kubernetesAuditLogReaderLimitsSchema.exactOptional(), }); /** @@ -487,6 +511,10 @@ export const resolveArtifactReaderLimits = ( }, wxapkg: { ...DEFAULT_WXAPKG_READER_LIMITS, ...selected?.wxapkg }, tar: { ...DEFAULT_TAR_READER_LIMITS, ...selected?.tar }, + kubernetes_audit_log: { + ...DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS, + ...selected?.kubernetes_audit_log, + }, ...(selected?.expanded_bytes === undefined ? {} : { expanded_bytes: selected.expanded_bytes }), diff --git a/src/domain/formatMetadata/androidAndSystemMetadata.ts b/src/domain/formatMetadata/androidAndSystemMetadata.ts index d4f66909a6..354cce781e 100644 --- a/src/domain/formatMetadata/androidAndSystemMetadata.ts +++ b/src/domain/formatMetadata/androidAndSystemMetadata.ts @@ -13,6 +13,13 @@ import { AUDITD_INLINE_EVENT_LIMIT, AUDITD_INLINE_EVENT_TYPE_LIMIT, } from "../linux/auditdLog.js"; +import { KUBERNETES_AUDIT_STAGES } from "../linux/kubernetesAuditEventProbe.js"; +import { + KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT, + KUBERNETES_AUDIT_INLINE_EVENT_LIMIT, + KUBERNETES_AUDIT_INLINE_STAGE_LIMIT, + KUBERNETES_AUDIT_INLINE_VERB_LIMIT, +} from "../linux/kubernetesAuditLog.js"; import { offset, uint32 } from "./primitives.js"; const ntfsRecordHeaderSchema = z.strictObject({ @@ -506,6 +513,74 @@ export const auditdLogMetadataSchema = z.strictObject({ trailing_bytes: offset, }); +const kubernetesAuditStageSchema = z.enum(KUBERNETES_AUDIT_STAGES); +const kubernetesAuditCount = z.strictObject({ + label: z.string(), + count: offset, +}); +/** One stage line: the stage, its source line and the request's own instant. */ +const kubernetesAuditStageRecordSchema = z.strictObject({ + stage: kubernetesAuditStageSchema, + line: offset, + request_received_timestamp: z.number().int().nullable(), + response_code: z.number().int().nullable(), +}); +/** Kubernetes audit log facts: line and stage totals plus a sampled event window. */ +export const kubernetesAuditLogMetadataSchema = z.strictObject({ + kind: z.literal("kubernetes-audit-log"), + line_count: offset, + event_count: offset, + oversized_line_count: offset, + line_bytes_limit: offset, + malformed_line_count: offset, + malformed_lines: z + .array( + z.strictObject({ + line: offset, + reason: z.string(), + excerpt: z.string(), + }), + ) + .max(KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT), + omitted_malformed_lines: offset, + sample_missing_terminal_stage_count: offset, + sample_duplicate_stage_line_count: offset, + stage_counts: z.array(kubernetesAuditCount), + verb_counts: z + .array(kubernetesAuditCount) + .max(KUBERNETES_AUDIT_INLINE_VERB_LIMIT), + unlisted_verb_line_count: offset, + events: z + .array( + z.strictObject({ + audit_id: z.string(), + request_uri: z.string().nullable(), + verb: z.string().nullable(), + username: z.string().nullable(), + user_groups: z.array(z.string()).nullable(), + source_ips: z.array(z.string()).nullable(), + user_agent: z.string().nullable(), + resource: z.string().nullable(), + namespace: z.string().nullable(), + object_name: z.string().nullable(), + // As the event recorded it; a status code is an integer, not a byte offset. + response_code: z.number().int().nullable(), + response_code_line: offset.nullable(), + stages: z + .array(kubernetesAuditStageRecordSchema) + .max(KUBERNETES_AUDIT_INLINE_STAGE_LIMIT), + omitted_stage_lines: offset, + request_fields_omitted: z.boolean(), + depth_limited: z.boolean(), + unsupported_version: z.boolean(), + }), + ) + .max(KUBERNETES_AUDIT_INLINE_EVENT_LIMIT), + unsampled_event_line_count: offset, + depth_limited_line_count: offset, + trailing_bytes: offset, +}); + const vbmetaHex = z.string().regex(/^[0-9a-f]*$/u); /** An unsigned 64-bit value that is metadata only, as a decimal string. */ const vbmetaU64Decimal = z.string().regex(/^(?:0|[1-9][0-9]*)$/u); diff --git a/src/domain/linux/kubernetesAuditEventProbe.ts b/src/domain/linux/kubernetesAuditEventProbe.ts new file mode 100644 index 0000000000..b77f18f14b --- /dev/null +++ b/src/domain/linux/kubernetesAuditEventProbe.ts @@ -0,0 +1,384 @@ +import { getManyValues, isMany, none, type Many } from "stream-chain/defs.js"; +import { jsonParser, type Token } from "stream-json/core/parser.js"; +import { MAX_KUBERNETES_AUDIT_LINE_BYTES } from "../artifactReaderLimits.js"; +import { isHostLimitFailure } from "../parseFailure.js"; +import { strictUtf8Decoder } from "../strictUtf8.js"; +import { + isTokenizerDepth, + KUBERNETES_AUDIT_JSON_DEPTH, +} from "./kubernetesAuditRecord.js"; + +/** The stages one request's `auditID` can pass through, in Kubernetes' order. */ +export const KUBERNETES_AUDIT_STAGES = [ + "RequestReceived", + "ResponseStarted", + "ResponseComplete", + "Panic", +] as const; +export type KubernetesAuditStage = (typeof KUBERNETES_AUDIT_STAGES)[number]; + +export const kubernetesAuditStageOf = ( + value: unknown, +): KubernetesAuditStage | null => + KUBERNETES_AUDIT_STAGES.find((stage) => stage === value) ?? null; + +/** Leading blank lines and JSON whitespace do not shrink the first record. */ +const PREAMBLE_BYTES = MAX_KUBERNETES_AUDIT_LINE_BYTES; +/** Byte allowance includes the optional newline after the first record. */ +const RECORD_BYTES = MAX_KUBERNETES_AUDIT_LINE_BYTES + 1; +/** Each tokenizer call may emit several token fragments per input byte. */ +const TOKEN_CHUNK_BYTES = 64 * 1024; +const IDENTITY_TOKEN_LIMIT = Math.max( + "auditID".length, + "stage".length, + ...KUBERNETES_AUDIT_STAGES.map((stage) => stage.length), +); + +const UTF8_BOM = [0xef, 0xbb, 0xbf] as const; + +export const kubernetesAuditNeedsMore = ( + prefix: Uint8Array, + fileSize: number, +): boolean => { + if (prefix.length === 0 || prefix.length >= fileSize) return false; + const probe = new KubernetesAuditEventProbe(); + probe.write(prefix); + return probe.pending; +}; + +/** Query the same top-level identity from a prefix or an extended source. */ +export const hasKubernetesAuditEvent = ( + prefix: Uint8Array, + fileSize: number, +): boolean => { + const probe = new KubernetesAuditEventProbe(); + probe.write(prefix); + return probe.finish(fileSize) === true; +}; + +type AuditIdentityField = "auditID" | "stage"; +/** The tokenizer is flushable with `none`, which its string-only type omits. */ +type AuditJsonTokenizer = ( + value: string | typeof none, +) => Many | typeof none; + +/** + * Inspect the first non-empty JSON line without assembling its body or its + * values. Empty lines, JSON whitespace, and one U+FEFF at the start of a + * line are padding, the same bytes the reader ignores. A finished line must + * be valid JSON; a clipped + * prefix retains only complete top-level audit fields. Padding and the first + * record each have their own allowance, so blank lines do not shrink the + * record window. The reader admits and decodes the record under the caller's + * line allowance. + */ +export class KubernetesAuditEventProbe { + #decoder: TextDecoder | undefined; + #tokens: AuditJsonTokenizer | undefined; + #observed = 0; + /** File offset of the first record's `{`, once padding has ended. */ + #recordStart: number | undefined; + #lineEnded = false; + #done = false; + #failed = false; + #depthStopped = false; + /** Decoded slices of the first record, kept only to reread a depth overflow. */ + #recordSlices: string[] = []; + #preamble = true; + #atLineStart = true; + #bomMatched = 0; + #depth = 0; + #field: AuditIdentityField | undefined; + #capture: "key" | "stage" | undefined; + // not-an-allowance: text longer than every recognized key or stage cannot match. + #text = ""; + #hasAuditId = false; + #hasStage = false; + + get limit(): number { + if (this.#done) return this.#observed; + if (this.#recordStart === undefined) return PREAMBLE_BYTES + RECORD_BYTES; + return this.#recordStart + RECORD_BYTES; + } + + /** Another byte of this file could still change the format decision. */ + get pending(): boolean { + return !this.#done; + } + + write(chunk: Uint8Array): void { + if (this.#done || chunk.length === 0) return; + let input = chunk; + if (this.#preamble) { + const room = Math.max(0, PREAMBLE_BYTES - this.#observed); + const take = Math.min(input.length, room); + if (take > 0) { + const window = input.subarray(0, take); + const before = this.#observed; + this.#observed += window.length; + input = input.subarray(take); + const offset = this.#consumePreamble(window); + if (this.#done) return; + if (!this.#preamble) { + this.#recordStart = before + offset; + this.#consumeRecord(window.subarray(offset)); + } + } + if (this.#preamble) { + if (this.#observed < PREAMBLE_BYTES || input.length === 0) return; + if (input[0] !== 0x7b) { + this.#done = true; + return; + } + this.#preamble = false; + this.#atLineStart = false; + this.#recordStart = this.#observed; + } else if (this.#done || input.length === 0) return; + } + const room = this.limit - this.#observed; + if (room <= 0) { + this.#done = true; + return; + } + const rest = input.subarray(0, Math.min(input.length, room)); + this.#observed += rest.length; + this.#consumeRecord(rest); + } + + /** Tokenize the first record. `bytes` are already included in `#observed`. */ + #consumeRecord(bytes: Uint8Array): void { + if (this.#done || bytes.length === 0) return; + const newline = bytes.indexOf(0x0a); + if (newline !== -1) this.#lineEnded = true; + const line = newline === -1 ? bytes : bytes.subarray(0, newline); + if ( + this.#lineEnded || + (this.#recordStart !== undefined && + this.#observed >= this.#recordStart + RECORD_BYTES) + ) + this.#done = true; + if (line.length === 0) return; + if (this.#decoder === undefined) { + this.#decoder = strictUtf8Decoder("preserve"); + this.#tokens = jsonParser({ + packValues: false, + packKeys: false, + packStrings: false, + packNumbers: false, + streamValues: true, + maxDepth: KUBERNETES_AUDIT_JSON_DEPTH, + }) as AuditJsonTokenizer; + } + try { + for (let start = 0; start < line.length; start += TOKEN_CHUNK_BYTES) { + const decoded = this.#decoder.decode( + line.subarray(start, start + TOKEN_CHUNK_BYTES), + { stream: true }, + ); + // Chunks keep ordinary lines cheap. A depth overflow drops only the + // tokens inside the chunk that overflowed; that chunk is reread one + // code unit at a time when identity is not already known. + for (let index = 0; index < decoded.length;) { + const end = Math.min(decoded.length, index + 4096); + const slice = decoded.slice(index, end); + this.#recordSlices.push(slice); + try { + this.#feed(slice); + } catch (cause: unknown) { + if (isHostLimitFailure(cause)) throw cause; + if (!isTokenizerDepth(cause)) { + this.#failed = true; + this.#done = true; + this.#recordSlices.length = 0; + return; + } + this.#rereadRecord(); + this.#failed = !this.#depthStopped; + this.#done = true; + this.#recordSlices.length = 0; + return; + } + index = end; + } + } + if (this.#done) this.#recordSlices.length = 0; + } catch (cause: unknown) { + if (isHostLimitFailure(cause)) throw cause; + this.#failed = true; + this.#done = true; + this.#recordSlices.length = 0; + } + } + + /** + * The overflowed chunk's tokens were discarded. Reread the first record from + * its start so identity that shared that chunk is still observed. + */ + #rereadRecord(): void { + const failed = this.#recordSlices.pop() ?? ""; + const prior = this.#recordSlices.splice(0); + this.#depth = 0; + this.#hasAuditId = false; + this.#hasStage = false; + this.#field = undefined; + this.#capture = undefined; + this.#text = ""; + this.#tokens = jsonParser({ + packValues: false, + packKeys: false, + packStrings: false, + packNumbers: false, + streamValues: true, + maxDepth: KUBERNETES_AUDIT_JSON_DEPTH, + }) as AuditJsonTokenizer; + for (const slice of prior) this.#feed(slice); + for (let index = 0; index < failed.length; index += 1) { + try { + this.#feed(failed.charAt(index)); + } catch (cause: unknown) { + if (isHostLimitFailure(cause)) throw cause; + this.#depthStopped = this.#hasAuditId && this.#hasStage; + return; + } + } + this.#depthStopped = this.#hasAuditId && this.#hasStage; + } + + /** + * Skip blank lines and one leading U+FEFF. Return the index of the record's + * `{`, or the end of `bytes` while the preamble continues. + */ + #consumePreamble(bytes: Uint8Array): number { + for (let index = 0; index < bytes.length; index += 1) { + const byte = bytes[index]!; + if (this.#bomMatched > 0) { + const expected = UTF8_BOM[this.#bomMatched]; + if (expected === undefined || byte !== expected) { + this.#done = true; + return index; + } + this.#bomMatched += 1; + if (this.#bomMatched === UTF8_BOM.length) { + this.#bomMatched = 0; + this.#atLineStart = false; + } + continue; + } + if (byte === 0x0a) { + this.#atLineStart = true; + continue; + } + if (byte === 0x20 || byte === 0x09 || byte === 0x0d) { + this.#atLineStart = false; + continue; + } + if (byte === UTF8_BOM[0] && this.#atLineStart) { + this.#bomMatched = 1; + continue; + } + if (byte === 0x7b) { + this.#preamble = false; + this.#atLineStart = false; + return index; + } + this.#done = true; + return index; + } + return bytes.length; + } + + finish(fileSize: number): boolean | undefined { + const decided = + this.#failed || + this.#depthStopped || + this.#lineEnded || + this.#done || + this.#observed >= fileSize; + if (decided) this.#recordSlices.length = 0; + if (this.#decoder === undefined) return undefined; + if (this.#failed) return false; + if (this.#depthStopped) return this.#hasAuditId && this.#hasStage; + if (this.#lineEnded || this.#observed >= fileSize) + try { + this.#feed(this.#decoder.decode()); + this.#feed(none); + } catch { + return false; + } + else if (!this.#done) return undefined; + return this.#hasAuditId && this.#hasStage; + } + + #feed(value: string | typeof none): void { + const tokens = this.#tokens?.(value); + if (isMany(tokens)) + for (const token of getManyValues(tokens)) this.#consume(token); + } + + #consume(token: Token): void { + if (token.name === "startObject" || token.name === "startArray") { + if (this.#depth === 1) this.#field = undefined; + this.#depth += 1; + return; + } + if (token.name === "endObject" || token.name === "endArray") { + this.#depth -= 1; + return; + } + if (this.#depth !== 1) return; + switch (token.name) { + case "startKey": + this.#capture = "key"; + this.#text = ""; + break; + case "endKey": + this.#field = + this.#text === "auditID" || this.#text === "stage" + ? this.#text + : undefined; + // A duplicate top-level key replaces the previous observation, just + // as it does when the complete line is parsed by the reader. + if (this.#field === "auditID") this.#hasAuditId = false; + if (this.#field === "stage") this.#hasStage = false; + this.#capture = undefined; + break; + case "startString": + if (this.#field === "stage") { + this.#capture = "stage"; + this.#text = ""; + } + break; + case "stringChunk": + if ( + this.#capture !== undefined && + this.#text.length <= IDENTITY_TOKEN_LIMIT + ) + this.#text += token.value.slice( + 0, + IDENTITY_TOKEN_LIMIT + 1 - this.#text.length, + ); + break; + case "endString": + if (this.#field === "auditID") this.#hasAuditId = true; + if (this.#field === "stage") + this.#hasStage = kubernetesAuditStageOf(this.#text) !== null; + this.#capture = undefined; + this.#field = undefined; + break; + case "startNumber": + case "nullValue": + case "trueValue": + case "falseValue": + this.#field = undefined; + break; + case "endNumber": + case "numberChunk": + case "whitespace": + // Packed value tokens are disabled in the tokenizer configuration. + case "keyValue": + case "numberValue": + case "stringValue": + break; + } + } +} diff --git a/src/domain/linux/kubernetesAuditLog.ts b/src/domain/linux/kubernetesAuditLog.ts new file mode 100644 index 0000000000..b0bf9cc1e6 --- /dev/null +++ b/src/domain/linux/kubernetesAuditLog.ts @@ -0,0 +1,632 @@ +import { ok, err, type Result } from "../result.js"; +import { z } from "zod"; +import { Budget } from "../budget.js"; +import { + DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS, + MAX_KUBERNETES_AUDIT_LINE_BYTES, +} from "../artifactReaderLimits.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { isRecord } from "../../kernel/isRecord.js"; +import { ellipsisExcerpt } from "../excerpt.js"; +import { decodeUtf8PreservingBomOrNull } from "../strictUtf8.js"; +import { + KUBERNETES_AUDIT_STAGES, + kubernetesAuditStageOf, + type KubernetesAuditStage, +} from "./kubernetesAuditEventProbe.js"; +import { parseKubernetesAuditLine } from "./kubernetesAuditRecord.js"; +import type { + RegionDecodeFailure, + RegionDecoder, +} from "../firmware/regionDecoder.js"; + +/** Whole-log work admission; retained memory is bounded independently. */ +export const KUBERNETES_AUDIT_LOG_MAX_FILE_BYTES = 1024 * 1024 * 1024 * 4; +/** Inline events are a sample; totals below cover the whole file. */ +export const KUBERNETES_AUDIT_INLINE_EVENT_LIMIT = 32; +/** Inline diagnostics are a sample too. */ +export const KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT = 16; +/** The first-seen sample bounds keys and optional field text retained. */ +export const KUBERNETES_AUDIT_INLINE_VERB_LIMIT = 32; +const MAX_SAMPLE_KEY_UNITS = 128; +const MAX_SAMPLE_FIELD_BYTES = 128 * 1024; + +/** Retain one record per distinct stage before retaining repeats. */ +export const KUBERNETES_AUDIT_INLINE_STAGE_LIMIT = + KUBERNETES_AUDIT_STAGES.length; + +/** Audit event versions whose fields this reader interprets. */ +const AUDIT_VERSIONS: readonly string[] = [ + "audit.k8s.io/v1", + "audit.k8s.io/v1beta1", +]; + +export interface KubernetesAuditDiagnostic { + /** 1-based source line, as counted by the reader. */ + readonly line: number; + readonly reason: string; + /** Bounded excerpt of the offending text, never the whole line. */ + readonly excerpt: string; +} + +export interface KubernetesAuditStageRecord { + readonly stage: KubernetesAuditStage; + readonly line: number; + /** + * `requestReceivedTimestamp` as epoch milliseconds, or null when the event + * omitted it or it did not parse. A stage line carries the same instant. + */ + readonly request_received_timestamp: number | null; + readonly response_code: number | null; +} + +export interface KubernetesAuditEventSummary { + /** `auditID`, the identifier the stages of one request share. */ + readonly audit_id: string; + readonly request_uri: string | null; + readonly verb: string | null; + readonly username: string | null; + readonly user_groups: readonly string[] | null; + readonly source_ips: readonly string[] | null; + readonly user_agent: string | null; + /** `objectRef.resource`, `namespace` and `name`; each null when unstated. */ + readonly resource: string | null; + readonly namespace: string | null; + readonly object_name: string | null; + /** First understood `responseStatus.code`; individual values are on stages. */ + readonly response_code: number | null; + /** Source line of `response_code`, even if that stage record was omitted. */ + readonly response_code_line: number | null; + readonly stages: readonly KubernetesAuditStageRecord[]; + readonly omitted_stage_lines: number; + /** One or more optional request fields did not fit the sample budget. */ + readonly request_fields_omitted: boolean; + /** The tokenizer stopped inside this request, so later fields were not read. */ + readonly depth_limited: boolean; + /** + * True when the event names an API version this reader does not model. Its + * `auditID` and stage are still joined, but no field of it is interpreted. + */ + readonly unsupported_version: boolean; +} + +export interface KubernetesAuditEventCount { + readonly label: string; + readonly count: number; +} + +interface KubernetesAuditLines { + readonly kind: "kubernetes-audit-log"; + readonly line_count: number; + readonly event_count: number; + readonly oversized_line_count: number; + readonly line_bytes_limit: number; + readonly malformed_line_count: number; + readonly malformed_lines: readonly KubernetesAuditDiagnostic[]; + readonly omitted_malformed_lines: number; + /** Sampled requests with no recorded ResponseComplete or Panic. */ + readonly sample_missing_terminal_stage_count: number; + /** Extra lines that repeat a stage for a sampled auditID. */ + readonly sample_duplicate_stage_line_count: number; + readonly stage_counts: readonly KubernetesAuditEventCount[]; + readonly verb_counts: readonly KubernetesAuditEventCount[]; + /** Lines whose understood verbs were outside the retained labels. */ + readonly unlisted_verb_line_count: number; + readonly events: readonly KubernetesAuditEventSummary[]; + /** Valid event lines whose auditID was outside the request sample. */ + readonly unsampled_event_line_count: number; + /** Lines whose ignored body exceeded the tokenizer's container depth. */ + readonly depth_limited_line_count: number; + /** Bytes after the last newline, which no line boundary ended. */ + readonly trailing_bytes: number; +} + +export interface KubernetesAuditInventory { + readonly metadata: KubernetesAuditLines; + readonly limitations: readonly string[]; +} + +const failure = (message: string): RegionDecodeFailure => ({ + kind: "malformed", + message, +}); + +const stringOrNull = (value: unknown): string | null => + typeof value === "string" ? value : null; + +const stringArrayOrNull = (value: unknown): readonly string[] | null => + Array.isArray(value) && + value.every((entry): entry is string => typeof entry === "string") + ? value + : null; + +/** Detach text from the potentially much larger JSON source string. */ +const detachedText = (value: string): string => + Buffer.from(value, "utf16le").toString("utf16le"); + +/** Charge UTF-16 storage plus an allowance for a string and its reference. */ +const retainedTextBytes = (value: string): number => 2 * value.length + 32; + +const responseCode = (event: Record): number | null => { + const status = isRecord(event.responseStatus) + ? event.responseStatus.code + : null; + return typeof status === "number" && Number.isSafeInteger(status) + ? status + : null; +}; + +const isJsonWhitespace = (code: number): boolean => + code === 0x20 || code === 0x09 || code === 0x0d; + +/** + * One leading U+FEFF and the JSON whitespace around a record are padding. + * Anything else stays in the text so `JSON.parse` rejects it, which is the + * same rule the recognizer uses before `{`. + */ +const auditRecordText = (line: string): string | undefined => { + let start = line.charCodeAt(0) === 0xfeff ? 1 : 0; + let end = line.length; + while (start < end && isJsonWhitespace(line.charCodeAt(start))) start += 1; + while (end > start && isJsonWhitespace(line.charCodeAt(end - 1))) end -= 1; + if (start === end) return undefined; + return line.slice(start, end); +}; + +/** How much of an offending line a diagnostic shows. */ +const DIAGNOSTIC_EXCERPT_UNITS = 160; +/** An excerpt a diagnostic can show without dumping a whole line. */ +const excerptOf = (line: string): string => + ellipsisExcerpt(line, DIAGNOSTIC_EXCERPT_UNITS); + +const auditTimestamp = z.iso.datetime({ offset: true }); +const parseTimestamp = (value: unknown): number | null => { + const result = auditTimestamp.safeParse(value); + if (!result.success) return null; + const parsed = Date.parse(result.data); + return Number.isFinite(parsed) ? parsed : null; +}; + +/** `audit.k8s.io/v1`-style versions; a missing one is read as supported. */ +const isUnsupportedVersion = (value: unknown): boolean => + value !== undefined && + (typeof value !== "string" || !AUDIT_VERSIONS.includes(value)); + +/** Interpreted request fields from the first line of a sampled auditID. */ +const summarizeEvent = ( + event: Record | undefined, + auditId: string, + stageRecord: KubernetesAuditStageRecord, + unsupported: boolean, + fieldBudget: Budget, +): KubernetesAuditEventSummary => { + const user = isRecord(event?.user) ? event.user : undefined; + const object = isRecord(event?.objectRef) ? event.objectRef : undefined; + let requestFieldsOmitted = false; + const reserve = (bytes: number): boolean => { + if (fieldBudget.tryCharge(bytes)) return true; + requestFieldsOmitted = true; + return false; + }; + const text = (value: unknown): string | null => { + const valid = stringOrNull(value); + return valid !== null && reserve(retainedTextBytes(valid)) + ? detachedText(valid) + : null; + }; + const list = (value: unknown): readonly string[] | null => { + const valid = stringArrayOrNull(value); + if (valid === null) return null; + const bytes = valid.reduce( + (total, item) => total + retainedTextBytes(item), + 0, + ); + return reserve(bytes) ? valid.map(detachedText) : null; + }; + return { + audit_id: auditId, + request_uri: text(event?.requestURI), + verb: text(event?.verb), + username: text(user?.username), + user_groups: list(user?.groups), + source_ips: list(event?.sourceIPs), + user_agent: text(event?.userAgent), + resource: text(object?.resource), + namespace: text(object?.namespace), + object_name: text(object?.name), + response_code: stageRecord.response_code, + response_code_line: + stageRecord.response_code === null ? null : stageRecord.line, + stages: [stageRecord], + omitted_stage_lines: 0, + request_fields_omitted: requestFieldsOmitted, + depth_limited: false, + unsupported_version: unsupported, + }; +}; + +type SampledRequest = { + summary: KubernetesAuditEventSummary; + readonly seenStages: Set; + /** Request strings come from the first stage with a modelled API version. */ + fieldsRecorded: boolean; +}; + +/** Keep the first observation of each stage. Repeats use the remaining slots. */ +const retainStage = ( + stages: readonly KubernetesAuditStageRecord[], + record: KubernetesAuditStageRecord, + alreadySeen: boolean, +): readonly KubernetesAuditStageRecord[] => { + if (stages.length < KUBERNETES_AUDIT_INLINE_STAGE_LIMIT) + return [...stages, record]; + if (alreadySeen) return stages; + const lastRepeat = stages.findLastIndex( + (stage, index) => + stages.findIndex((earlier) => earlier.stage === stage.stage) < index, + ); + return [...stages.filter((_stage, index) => index !== lastRepeat), record]; +}; + +/** + * Feed the admitted file one line at a time and join audit events on their + * `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; + #recordCount = 0; + #trailingBytes = 0; + #malformedCount = 0; + #oversizedLineCount = 0; + #largestSkippedLineBytes = 0; + readonly #malformed: KubernetesAuditDiagnostic[] = []; + /** Insertion order is the first-seen display order. */ + readonly #sample = new Map(); + readonly #sampleFields = new Budget(MAX_SAMPLE_FIELD_BYTES); + #unsampledEventLines = 0; + #unlistedVerbLines = 0; + readonly #stageCounts = new Map(); + readonly #verbCounts = new Map(); + #sampleDuplicateStageLines = 0; + #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) + 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`, + ), + ); + const sampleWithoutTerminalStage = [...this.#sample.values()].filter( + ({ seenStages }) => + !seenStages.has("ResponseComplete") && !seenStages.has("Panic"), + ).length; + const events = [...this.#sample.values()].map(({ summary }) => summary); + return ok({ + metadata: { + kind: "kubernetes-audit-log", + line_count: this.#lineNumber, + event_count: this.#recordCount, + oversized_line_count: this.#oversizedLineCount, + line_bytes_limit: this.maxLineBytes, + malformed_line_count: this.#malformedCount, + malformed_lines: this.#malformed, + omitted_malformed_lines: Math.max( + 0, + this.#malformedCount - this.#malformed.length, + ), + sample_missing_terminal_stage_count: sampleWithoutTerminalStage, + sample_duplicate_stage_line_count: this.#sampleDuplicateStageLines, + stage_counts: [...this.#stageCounts] + .sort(([left], [right]) => compareUnicodeCodePoints(left, right)) + .map(([label, count]) => ({ label, count })), + verb_counts: [...this.#verbCounts] + .sort(([left], [right]) => compareUnicodeCodePoints(left, right)) + .map(([label, count]) => ({ label, count })), + unlisted_verb_line_count: this.#unlistedVerbLines, + events, + unsampled_event_line_count: this.#unsampledEventLines, + depth_limited_line_count: this.#depthLimitedLines, + trailing_bytes: this.#trailingBytes, + }, + limitations: this.#limitations(events, sampleWithoutTerminalStage), + }); + } + + #limitations( + events: readonly KubernetesAuditEventSummary[], + sampleWithoutTerminalStage: number, + ): string[] { + const limitations: string[] = []; + if (this.#oversizedLineCount > 0) { + const required = this.#largestSkippedLineBytes; + const recovery = + required <= MAX_KUBERNETES_AUDIT_LINE_BYTES + ? `Set artifact_limits.kubernetes_audit_log.line_bytes to at least ${String(required)} to include those lines, or inspect a capture whose records fit.` + : `At least one record exceeds the ${String(MAX_KUBERNETES_AUDIT_LINE_BYTES)}-byte maximum. Inspect a capture whose records fit.`; + limitations.push( + `${String(this.#oversizedLineCount)} line(s) exceeded the ${String(this.maxLineBytes)}-byte line limit and were not parsed or included in event, stage or verb totals. ${recovery}`, + ); + } + if (this.#malformedCount > 0) + limitations.push( + `${String(this.#malformedCount)} line(s) are not JSON objects, not audit events, or name an unknown stage; their text is not represented`, + ); + if (this.#unsupportedVersionLineCount > 0) + limitations.push( + `${String(this.#unsupportedVersionLineCount)} line(s) declare an audit API version this reader does not model; their auditID and stage are retained, but their request, user, object and response fields are not interpreted`, + ); + if (sampleWithoutTerminalStage > 0) + limitations.push( + `${String(sampleWithoutTerminalStage)} sampled auditID(s) have no recorded ResponseComplete or Panic stage; capture and policy coverage remain unknown`, + ); + if (this.#sampleDuplicateStageLines > 0) + limitations.push( + `${String(this.#sampleDuplicateStageLines)} line(s) repeat a stage for a sampled auditID; a bounded stage window retains the first occurrence of each observed stage`, + ); + if (this.#unsampledEventLines > 0) + limitations.push( + `events are listed for ${String(events.length)} auditID(s); ${String(this.#unsampledEventLines)} further event line(s) contribute to aggregate counts`, + ); + if (this.#unlistedVerbLines > 0) + limitations.push( + `${String(this.#unlistedVerbLines)} line(s) carry verbs outside the bounded verb histogram`, + ); + if (this.#depthLimitedLines > 0) + limitations.push( + `${String(this.#depthLimitedLines)} line(s) contain an ignored value nested deeper than the tokenizer scans; fields after that value on the line were not read`, + ); + if (events.some((event) => event.request_fields_omitted)) + limitations.push( + "some sampled request fields exceed the retained field-text budget and are left unknown; their stage and numeric response facts remain available", + ); + limitations.push( + "events are inventoried by the declared request, user, object reference and response code: request and response object bodies, annotations, impersonation metadata and audit policy are not interpreted, and the log is not treated as complete or authentic", + ); + 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)); + } + + #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 { + const decoded = decodeUtf8PreservingBomOrNull(lineBytes); + if (decoded === null) { + this.#diagnose( + "line is not valid UTF-8, which JSON-lines requires", + lineBytes.subarray(0, 160).toString("utf8"), + ); + return; + } + const line = auditRecordText(decoded); + if (line === undefined) return; + const parsed = parseKubernetesAuditLine(line); + if (parsed.kind === "nesting") { + this.#depthLimitedLines += 1; + return; + } + if (parsed.kind !== "event") { + this.#diagnose("line is not JSON", line); + return; + } + if (parsed.depthLimited) this.#depthLimitedLines += 1; + const { value } = parsed; + if (typeof value.auditID !== "string") { + this.#diagnose( + "JSON value is not a Kubernetes audit event (no auditID)", + line, + ); + return; + } + const stage = kubernetesAuditStageOf(value.stage); + if (stage === null) { + this.#diagnose("audit event names an unknown stage", line); + return; + } + this.#record( + value, + value.auditID, + stage, + parsed.depthLimited, + parsed.budgetOmitted, + parsed.verbOmitted, + ); + } + + #countVerb(verb: string): void { + const previous = this.#verbCounts.get(verb); + if (previous !== undefined) { + this.#verbCounts.set(verb, previous + 1); + return; + } + if ( + this.#verbCounts.size >= KUBERNETES_AUDIT_INLINE_VERB_LIMIT || + verb.length > MAX_SAMPLE_KEY_UNITS + ) { + this.#unlistedVerbLines += 1; + return; + } + this.#verbCounts.set(detachedText(verb), 1); + } + + #record( + event: Record, + auditId: string, + stage: KubernetesAuditStage, + depthLimited: boolean, + budgetOmitted: boolean, + verbOmitted: boolean, + ): void { + this.#recordCount += 1; + const versionUnexamined = + depthLimited && !Object.hasOwn(event, "apiVersion"); + // A cutoff before apiVersion is not a declared unmodelled version. + const unsupported = isUnsupportedVersion(event.apiVersion); + const suppressFields = unsupported || versionUnexamined; + // An unread version leaves every field, including a dropped verb, out of + // the histogram. A dropped verb on an interpreted line is unlisted. + if (unsupported) this.#unsupportedVersionLineCount += 1; + else if (!suppressFields && verbOmitted) this.#unlistedVerbLines += 1; + else if (!suppressFields && typeof event.verb === "string") + this.#countVerb(event.verb); + this.#stageCounts.set(stage, (this.#stageCounts.get(stage) ?? 0) + 1); + const sampled = this.#sample.get(auditId); + if ( + sampled === undefined && + (this.#sample.size >= KUBERNETES_AUDIT_INLINE_EVENT_LIMIT || + auditId.length > MAX_SAMPLE_KEY_UNITS) + ) { + this.#unsampledEventLines += 1; + return; + } + const stageRecord: KubernetesAuditStageRecord = { + stage, + line: this.#lineNumber, + request_received_timestamp: suppressFields + ? null + : parseTimestamp(event.requestReceivedTimestamp), + response_code: suppressFields ? null : responseCode(event), + }; + if (sampled === undefined) { + const key = detachedText(auditId); + this.#sample.set(key, { + summary: summarizeEvent( + suppressFields ? undefined : event, + key, + stageRecord, + unsupported, + this.#sampleFields, + ), + seenStages: new Set([stage]), + fieldsRecorded: !suppressFields, + }); + const created = this.#sample.get(key); + if (created !== undefined && (depthLimited || budgetOmitted)) + created.summary = { + ...created.summary, + depth_limited: created.summary.depth_limited || depthLimited, + request_fields_omitted: + created.summary.request_fields_omitted || budgetOmitted, + }; + return; + } + + const alreadySeen = sampled.seenStages.has(stage); + if (alreadySeen) this.#sampleDuplicateStageLines += 1; + else sampled.seenStages.add(stage); + if (!suppressFields && !sampled.fieldsRecorded) { + const filled = summarizeEvent( + suppressFields ? undefined : event, + sampled.summary.audit_id, + stageRecord, + false, + this.#sampleFields, + ); + sampled.fieldsRecorded = true; + sampled.summary = { + ...sampled.summary, + request_uri: filled.request_uri, + verb: filled.verb, + username: filled.username, + user_groups: filled.user_groups, + source_ips: filled.source_ips, + user_agent: filled.user_agent, + resource: filled.resource, + namespace: filled.namespace, + object_name: filled.object_name, + request_fields_omitted: filled.request_fields_omitted, + }; + } + const previous = sampled.summary; + const stages = retainStage(previous.stages, stageRecord, alreadySeen); + sampled.summary = { + ...previous, + response_code: previous.response_code ?? stageRecord.response_code, + response_code_line: + previous.response_code_line ?? + (stageRecord.response_code === null ? null : stageRecord.line), + stages, + omitted_stage_lines: + previous.omitted_stage_lines + + previous.stages.length + + 1 - + stages.length, + unsupported_version: previous.unsupported_version || unsupported, + depth_limited: previous.depth_limited || depthLimited, + request_fields_omitted: previous.request_fields_omitted || budgetOmitted, + }; + } + + #diagnose(reason: string, text: string): void { + this.#malformedCount += 1; + if (this.#malformed.length < KUBERNETES_AUDIT_INLINE_DIAGNOSTIC_LIMIT) + this.#malformed.push({ + line: this.#lineNumber, + reason, + excerpt: detachedText(excerptOf(text)), + }); + } +} + +export const createKubernetesAuditLogDecoder = ( + fileBytes: number, + maxLineBytes = DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS.line_bytes, +): Result, RegionDecodeFailure> => + Number.isSafeInteger(fileBytes) && + fileBytes >= 0 && + fileBytes <= KUBERNETES_AUDIT_LOG_MAX_FILE_BYTES + ? ok(new KubernetesAuditScanner(maxLineBytes)) + : err({ + kind: "limit", + message: `file is ${String(fileBytes)} bytes, exceeding the fixed ${String(KUBERNETES_AUDIT_LOG_MAX_FILE_BYTES)}-byte (4 GiB) ceiling`, + boundary: "file-size", + }); diff --git a/src/domain/linux/kubernetesAuditRecord.ts b/src/domain/linux/kubernetesAuditRecord.ts new file mode 100644 index 0000000000..3a75c10130 --- /dev/null +++ b/src/domain/linux/kubernetesAuditRecord.ts @@ -0,0 +1,664 @@ +import { getManyValues, isMany, none, type Many } from "stream-chain/defs.js"; +import { jsonParser, type Token } from "stream-json/core/parser.js"; +import { MAX_KUBERNETES_AUDIT_LINE_BYTES } from "../artifactReaderLimits.js"; +import { isHostLimitFailure } from "../parseFailure.js"; + +/** + * Containers kept for the summary are at most three deep (the record, `user`, + * and `groups`). Anything deeper belongs to an ignored body. The tokenizer + * stops there so a nested body cannot grow a value tree or the parser stack. + */ +export const KUBERNETES_AUDIT_JSON_DEPTH = 64; +/** Longer than every owned key. A longer key cannot match and is not stored. */ +const MAX_OWNED_KEY_CHARS = 64; +/** + * Digits retained from a status-code significand. A longer exact integer is + * outside the safe integer range, so the extra digits are not stored. + */ +const MAX_NUMBER_CHARS = 24; + +const ROOT_STRINGS = new Set([ + "apiVersion", + "auditID", + "stage", + "requestURI", + "verb", + "userAgent", + "requestReceivedTimestamp", +]); +const OBJECT_REF_STRINGS = new Set(["resource", "namespace", "name"]); + +type AuditJsonTokenizer = ( + value: string | typeof none, +) => Many | typeof none; + +/** Retained list text. A longer list is not stored; the field stays null. */ +const LIST_TEXT_BUDGET = 128 * 1024; + +type StringList = { + readonly kind: "strings"; + readonly target: "sourceIPs" | "groups"; + readonly values: string[]; + bytes: number; + invalid: boolean; + overBudget: boolean; +}; +type Frame = + | { readonly kind: "root" } + | { readonly kind: "skip" } + | { readonly kind: "user" } + | { readonly kind: "objectRef" } + | { readonly kind: "responseStatus" } + | StringList; + +export type KubernetesAuditLineParse = + | { + readonly kind: "event"; + readonly value: Record; + /** True when the tokenizer stopped before the record's closing brace. */ + readonly depthLimited: boolean; + /** A kept string or list was dropped because it exceeded the text budget. */ + readonly budgetOmitted: boolean; + /** The verb text was dropped by that budget. */ + readonly verbOmitted: boolean; + } + | { readonly kind: "syntax" } + | { readonly kind: "nesting" }; + +const detachedText = (value: string): string => + Buffer.from(value, "utf16le").toString("utf16le"); + +export const isTokenizerDepth = (cause: unknown): boolean => + cause instanceof Error && + cause.name === "RangeError" && + cause.message.includes("maxDepth"); + +/** + * Read one audit line without building object bodies the inventory does not + * keep. `requestObject`, `responseObject`, annotations and any other container + * are skipped. A body deeper than {@link KUBERNETES_AUDIT_JSON_DEPTH} stops + * the scan; identity already read is kept and fields after that body are absent. + */ +export const parseKubernetesAuditLine = ( + line: string, + step = 4096, + replayFrom?: number, +): KubernetesAuditLineParse => { + const value: Record = {}; + const user: Record = {}; + const objectRef: Record = {}; + const responseStatus: Record = {}; + let sawUser = false; + let sawObject = false; + let sawStatus = false; + const stack: Frame[] = []; + let pendingKey: string | undefined; + let capture: "key" | "string" | "number" | undefined; + let text = ""; + let keyTooLong = false; + let numberNegative = false; + let numberSawSign = false; + let numberSawDigit = false; + let numberSawDot = false; + let numberSawExp = false; + let numberExpSign = 1; + let numberExp = 0; + let numberExpDigits = 0; + let numberScale = 0; + let numberDroppedZeros = 0; + let numberInexact = false; + let numberDigits = ""; + let stringOverflow = false; + /** Final fields whose last value was dropped for the text budget. */ + const budgetOmittedFields = new Set(); + const REQUEST_OMISSION_KEYS = new Set([ + "root:requestURI", + "root:verb", + "root:userAgent", + "user:username", + "list:groups", + "list:sourceIPs", + "object:resource", + "object:namespace", + "object:name", + ]); + const budgetOmitted = (): boolean => + [...budgetOmittedFields].some((key) => REQUEST_OMISSION_KEYS.has(key)); + const fieldKey = (): string | undefined => { + const frame = top(); + if (frame?.kind === "strings") + return frame.target === "sourceIPs" ? "list:sourceIPs" : "list:groups"; + if (frame?.kind === "root" && pendingKey === "sourceIPs") + return "list:sourceIPs"; + if (frame?.kind === "root") return `root:${pendingKey}`; + if (frame?.kind === "user" && pendingKey === "groups") return "list:groups"; + if (frame?.kind === "user" && pendingKey === "username") + return "user:username"; + if (frame?.kind === "objectRef" && pendingKey !== undefined) + return `object:${pendingKey}`; + return undefined; + }; + const forgetOmission = (): void => { + const key = fieldKey(); + if (key !== undefined) budgetOmittedFields.delete(key); + }; + + const top = (): Frame | undefined => stack.at(-1); + const skipping = (): boolean => top()?.kind === "skip"; + + const ownedString = (): boolean => { + const frame = top(); + if (frame === undefined || frame.kind === "skip") return false; + if (frame.kind === "strings") return !frame.invalid; + if (frame.kind === "root") + return pendingKey !== undefined && ROOT_STRINGS.has(pendingKey); + if (frame.kind === "user") return pendingKey === "username"; + if (frame.kind === "objectRef") + return pendingKey !== undefined && OBJECT_REF_STRINGS.has(pendingKey); + return false; + }; + + const takeString = (entry: string): void => { + const frame = top(); + if (frame?.kind === "strings") { + if (frame.invalid) return; + const cost = 2 * entry.length + 32; + if (frame.bytes + cost > LIST_TEXT_BUDGET) { + frame.invalid = true; + frame.overBudget = true; + frame.values.length = 0; + frame.bytes = 0; + return; + } + frame.bytes += cost; + frame.values.push(detachedText(entry)); + return; + } + const kept = detachedText(entry); + if (frame?.kind === "root" && pendingKey !== undefined) + value[pendingKey] = kept; + else if (frame?.kind === "user" && pendingKey === "username") { + sawUser = true; + user.username = kept; + } else if ( + frame?.kind === "objectRef" && + pendingKey !== undefined && + OBJECT_REF_STRINGS.has(pendingKey) + ) { + sawObject = true; + objectRef[pendingKey] = kept; + } + }; + + const rejectScalar = (): void => { + const frame = top(); + if (frame?.kind === "strings") { + frame.invalid = true; + return; + } + if (frame?.kind === "root" && pendingKey === "user") { + sawUser = false; + for (const key of Object.keys(user)) delete user[key]; + budgetOmittedFields.delete("user:username"); + budgetOmittedFields.delete("list:groups"); + return; + } + if (frame?.kind === "root" && pendingKey === "objectRef") { + sawObject = false; + for (const key of Object.keys(objectRef)) delete objectRef[key]; + budgetOmittedFields.delete("object:resource"); + budgetOmittedFields.delete("object:namespace"); + budgetOmittedFields.delete("object:name"); + return; + } + if (frame?.kind === "root" && pendingKey === "responseStatus") { + sawStatus = false; + delete responseStatus.code; + return; + } + if (frame?.kind === "root" && pendingKey === "sourceIPs") { + value.sourceIPs = null; + budgetOmittedFields.delete("list:sourceIPs"); + return; + } + if (frame?.kind === "root" && pendingKey !== undefined) { + if (pendingKey === "auditID" || pendingKey === "stage") + value[pendingKey] = null; + else if (ROOT_STRINGS.has(pendingKey)) value[pendingKey] = null; + else delete value[pendingKey]; + } else if (frame?.kind === "user" && pendingKey === "groups") { + sawUser = true; + user.groups = null; + } else if (frame?.kind === "user" && pendingKey === "username") { + sawUser = true; + user.username = null; + } else if ( + frame?.kind === "objectRef" && + pendingKey !== undefined && + OBJECT_REF_STRINGS.has(pendingKey) + ) { + sawObject = true; + objectRef[pendingKey] = null; + } else if (frame?.kind === "responseStatus" && pendingKey === "code") { + sawStatus = true; + responseStatus.code = null; + } + forgetOmission(); + }; + + /** A container where a scalar or string list was required leaves that field null. */ + const invalidatePending = (): void => { + const frame = top(); + if (frame?.kind === "strings") { + frame.invalid = true; + frame.values.length = 0; + frame.bytes = 0; + return; + } + if (frame?.kind === "root" && pendingKey === "user") { + sawUser = false; + for (const key of Object.keys(user)) delete user[key]; + budgetOmittedFields.delete("user:username"); + budgetOmittedFields.delete("list:groups"); + return; + } + if (frame?.kind === "root" && pendingKey === "objectRef") { + sawObject = false; + for (const key of Object.keys(objectRef)) delete objectRef[key]; + budgetOmittedFields.delete("object:resource"); + budgetOmittedFields.delete("object:namespace"); + budgetOmittedFields.delete("object:name"); + return; + } + if (frame?.kind === "root" && pendingKey === "responseStatus") { + sawStatus = false; + delete responseStatus.code; + return; + } + if (frame?.kind === "root" && pendingKey === "sourceIPs") { + value.sourceIPs = null; + budgetOmittedFields.delete("list:sourceIPs"); + return; + } + if ( + frame?.kind === "root" && + pendingKey !== undefined && + ROOT_STRINGS.has(pendingKey) + ) { + value[pendingKey] = null; + forgetOmission(); + return; + } + if (frame?.kind === "user" && pendingKey === "groups") { + sawUser = true; + user.groups = null; + forgetOmission(); + return; + } + if (frame?.kind === "user" && pendingKey === "username") { + sawUser = true; + user.username = null; + forgetOmission(); + return; + } + if ( + frame?.kind === "objectRef" && + pendingKey !== undefined && + OBJECT_REF_STRINGS.has(pendingKey) + ) { + sawObject = true; + objectRef[pendingKey] = null; + forgetOmission(); + return; + } + if (frame?.kind === "responseStatus" && pendingKey === "code") { + sawStatus = true; + responseStatus.code = null; + } + forgetOmission(); + }; + + const pushValue = (token: "object" | "array"): void => { + const frame = top(); + if (frame === undefined) { + stack.push(token === "object" ? { kind: "root" } : { kind: "skip" }); + pendingKey = undefined; + return; + } + if (token === "object" && frame.kind === "root") { + if (pendingKey === "user") { + sawUser = true; + for (const key of Object.keys(user)) delete user[key]; + budgetOmittedFields.delete("user:username"); + budgetOmittedFields.delete("list:groups"); + stack.push({ kind: "user" }); + } else if (pendingKey === "objectRef") { + sawObject = true; + for (const key of Object.keys(objectRef)) delete objectRef[key]; + budgetOmittedFields.delete("object:resource"); + budgetOmittedFields.delete("object:namespace"); + budgetOmittedFields.delete("object:name"); + stack.push({ kind: "objectRef" }); + } else if (pendingKey === "responseStatus") { + sawStatus = true; + delete responseStatus.code; + stack.push({ kind: "responseStatus" }); + } else { + invalidatePending(); + stack.push({ kind: "skip" }); + } + } else if ( + token === "array" && + frame.kind === "root" && + pendingKey === "sourceIPs" + ) { + value.sourceIPs = null; + budgetOmittedFields.delete("list:sourceIPs"); + stack.push({ + kind: "strings", + target: "sourceIPs", + values: [], + bytes: 0, + invalid: false, + overBudget: false, + }); + } else if ( + token === "array" && + frame.kind === "user" && + pendingKey === "groups" + ) { + sawUser = true; + user.groups = null; + budgetOmittedFields.delete("list:groups"); + stack.push({ + kind: "strings", + target: "groups", + values: [], + bytes: 0, + invalid: false, + overBudget: false, + }); + } else { + invalidatePending(); + stack.push({ kind: "skip" }); + } + pendingKey = undefined; + capture = undefined; + }; + + const finishList = (frame: StringList): void => { + const listKey = + frame.target === "sourceIPs" ? "list:sourceIPs" : "list:groups"; + if (frame.overBudget) budgetOmittedFields.add(listKey); + else budgetOmittedFields.delete(listKey); + const list = frame.invalid ? null : frame.values; + if (frame.target === "sourceIPs") value.sourceIPs = list; + else { + sawUser = true; + user.groups = list; + } + }; + + const statusCode = (): number | null => { + if ( + numberInexact || + !numberSawDigit || + (numberSawExp && numberExpDigits === 0) + ) + return null; + if (numberDigits.length === 0) return 0; + const shift = numberExpSign * numberExp - numberScale + numberDroppedZeros; + // A larger positive shift cannot be a safe integer. A larger negative + // shift leaves a fraction. + if (shift > 20 || shift < -numberDigits.length) return null; + const magnitude = BigInt(numberDigits); + const divisor = 10n ** BigInt(Math.abs(shift)); + const resolved = + shift >= 0 + ? magnitude * divisor + : magnitude % divisor === 0n + ? magnitude / divisor + : null; + if (resolved === null || resolved > BigInt(Number.MAX_SAFE_INTEGER)) + return null; + const code = Number(resolved); + return numberNegative ? -code : code; + }; + + const consume = (token: Token): void => { + if (token.name === "startObject") { + pushValue("object"); + return; + } + if (token.name === "startArray") { + pushValue("array"); + return; + } + if (token.name === "endObject" || token.name === "endArray") { + const frame = stack.pop(); + if (frame?.kind === "strings") finishList(frame); + pendingKey = undefined; + capture = undefined; + return; + } + if (skipping()) return; + switch (token.name) { + case "startKey": + capture = "key"; + text = ""; + keyTooLong = false; + break; + case "endKey": + pendingKey = keyTooLong ? undefined : text; + capture = undefined; + break; + case "startString": + if (ownedString()) { + capture = "string"; + text = ""; + } else rejectScalar(); + break; + case "stringChunk": + if (capture === "key" && text.length <= MAX_OWNED_KEY_CHARS) { + const room = MAX_OWNED_KEY_CHARS + 1 - text.length; + text += token.value.slice(0, room); + if (text.length > MAX_OWNED_KEY_CHARS) keyTooLong = true; + } else if (capture === "string" && text.length <= LIST_TEXT_BUDGET) { + const room = LIST_TEXT_BUDGET + 1 - text.length; + text += token.value.slice(0, room); + if (text.length > LIST_TEXT_BUDGET) stringOverflow = true; + } + break; + case "endString": + if (capture === "string" && stringOverflow) { + rejectScalar(); + const key = fieldKey(); + if (key !== undefined) budgetOmittedFields.add(key); + const list = top(); + if (list?.kind === "strings") { + list.invalid = true; + list.overBudget = true; + list.values.length = 0; + } + } else if (capture === "string") { + const key = fieldKey(); + takeString(text); + if (key !== undefined) budgetOmittedFields.delete(key); + } + stringOverflow = false; + capture = undefined; + pendingKey = undefined; + break; + case "startNumber": + if (top()?.kind === "responseStatus" && pendingKey === "code") { + capture = "number"; + numberNegative = false; + numberSawSign = false; + numberSawDigit = false; + numberSawDot = false; + numberSawExp = false; + numberExpSign = 1; + numberExp = 0; + numberExpDigits = 0; + numberScale = 0; + numberDroppedZeros = 0; + numberInexact = false; + numberDigits = ""; + } else rejectScalar(); + break; + case "numberChunk": + if (capture !== "number" || numberInexact) break; + for (const char of token.value) { + if (numberSawExp) { + if ( + (char === "+" || char === "-") && + numberExpDigits === 0 && + numberExp === 0 + ) { + numberExpSign = char === "-" ? -1 : 1; + continue; + } + if (char < "0" || char > "9") { + numberInexact = true; + break; + } + numberExpDigits += 1; + numberExp = numberExp * 10 + (char.charCodeAt(0) - 48); + // The fractional scale cannot exceed the line, so a larger + // exponent cannot cancel down to a safe integer. + if (numberExp > MAX_KUBERNETES_AUDIT_LINE_BYTES) { + numberInexact = true; + break; + } + continue; + } + if ( + char === "-" && + !numberSawDigit && + !numberSawDot && + !numberSawSign + ) { + numberNegative = true; + numberSawSign = true; + continue; + } + if (char === "." && !numberSawDot) { + numberSawDot = true; + continue; + } + if ((char === "e" || char === "E") && numberSawDigit) { + numberSawExp = true; + continue; + } + if (char < "0" || char > "9") { + numberInexact = true; + break; + } + numberSawDigit = true; + if (numberSawDot) numberScale += 1; + if (char === "0" && numberDigits.length === 0) continue; + if (numberDigits.length >= MAX_NUMBER_CHARS) { + if (char === "0") numberDroppedZeros += 1; + else { + numberInexact = true; + break; + } + continue; + } + numberDigits += char; + } + break; + case "endNumber": + if (capture === "number") { + sawStatus = true; + responseStatus.code = statusCode(); + } + capture = undefined; + pendingKey = undefined; + break; + case "nullValue": + case "trueValue": + case "falseValue": + rejectScalar(); + pendingKey = undefined; + break; + case "keyValue": + case "numberValue": + case "stringValue": + case "whitespace": + break; + } + }; + + const publish = (): Record => { + if (sawUser) value.user = { ...user }; + if (sawObject) value.objectRef = { ...objectRef }; + if (sawStatus) value.responseStatus = { ...responseStatus }; + return value; + }; + + const tokens = jsonParser({ + packValues: false, + packKeys: false, + packStrings: false, + packNumbers: false, + streamValues: false, + jsonStreaming: false, + maxDepth: KUBERNETES_AUDIT_JSON_DEPTH, + }) as AuditJsonTokenizer; + const feed = (chunk: string | typeof none): void => { + const produced = tokens(chunk); + if (isMany(produced)) + for (const token of getManyValues(produced)) consume(token); + }; + const partial = (): KubernetesAuditLineParse => + typeof value.auditID === "string" && typeof value.stage === "string" + ? { + kind: "event", + value: publish(), + depthLimited: true, + budgetOmitted: budgetOmitted(), + verbOmitted: budgetOmittedFields.has("root:verb"), + } + : { kind: "nesting" }; + try { + if (replayFrom === undefined) { + let offset = 0; + while (offset < line.length) { + const end = Math.min(line.length, offset + step); + try { + feed(line.slice(offset, end)); + } catch (cause: unknown) { + if (isHostLimitFailure(cause)) throw cause; + if (!isTokenizerDepth(cause) || step === 1) throw cause; + // Replay the successful prefix in slices and only the overflowed + // slice one code unit at a time. + return parseKubernetesAuditLine(line, 1, offset); + } + offset = end; + } + } else { + let offset = 0; + while (offset < replayFrom) { + const end = Math.min(replayFrom, offset + 4096); + feed(line.slice(offset, end)); + offset = end; + } + const badEnd = Math.min(line.length, replayFrom + 4096); + for (let index = replayFrom; index < badEnd; index += 1) + feed(line.charAt(index)); + } + feed(none); + } catch (cause: unknown) { + if (isHostLimitFailure(cause)) throw cause; + if (!isTokenizerDepth(cause)) return { kind: "syntax" }; + return partial(); + } + return { + kind: "event", + value: publish(), + depthLimited: false, + budgetOmitted: budgetOmitted(), + verbOmitted: budgetOmittedFields.has("root:verb"), + }; +}; diff --git a/src/domain/native/peOverlay.ts b/src/domain/native/peOverlay.ts index c4e1c33425..1ef5557ea3 100644 --- a/src/domain/native/peOverlay.ts +++ b/src/domain/native/peOverlay.ts @@ -117,6 +117,7 @@ export const PE_OVERLAY_LEADING_FORMATS = [ "labview-rsrc", "systemd-journal", "auditd-log", + "kubernetes-audit-log", ] as const; export type PeOverlayLeadingFormat = (typeof PE_OVERLAY_LEADING_FORMATS)[number]; diff --git a/src/domain/targetFormats.ts b/src/domain/targetFormats.ts index 0564ff2ac5..89c0ccf6e7 100644 --- a/src/domain/targetFormats.ts +++ b/src/domain/targetFormats.ts @@ -59,6 +59,7 @@ export const BINARY_TARGET_FORMAT_KINDS = { "ntfs-mft": "archive", "systemd-journal": "archive", "auditd-log": "archive", + "kubernetes-audit-log": "archive", plist: "artifact", javascript: "artifact", uefi: "artifact", diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index 21ea449136..e50685534c 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -297,6 +297,7 @@ export interface ArtifactReader { | "ntfs-mft" | "systemd-journal" | "auditd-log" + | "kubernetes-audit-log" | "pkg" | "file"; entries( diff --git a/tests/acceptance/kubernetesAuditLogCli.test.ts b/tests/acceptance/kubernetesAuditLogCli.test.ts new file mode 100644 index 0000000000..87090a3535 --- /dev/null +++ b/tests/acceptance/kubernetesAuditLogCli.test.ts @@ -0,0 +1,164 @@ +import { writeFile } from "node:fs/promises"; +import { expect } from "vitest"; +import { parseBinaryTarget } from "../../src/application/BinaryTargetResolver.js"; +import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js"; +import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js"; +import { parseEvidence } from "../../src/domain/evidence.js"; +import { workspaceCliTest as test } from "../support/cli/workspaceCliFixture.js"; + +const readInventory = (reply: unknown) => { + const inspection = artifactInspectionResultSchema.parse( + parseEvidence(reply).normalized_result, + ); + return artifactInventoryResultSchema.parse( + inspection.substeps.find((step) => step.operation === "inventory_artifact") + ?.evidence.normalized_result, + ); +}; + +test("reports skipped Kubernetes audit lines and reads them with a raised allowance", async ({ + cli, + workspace, +}) => { + const path = workspace.path("kubernetes-audit.jsonl"); + const event = { + apiVersion: "audit.k8s.io/v1", + auditID: "example", + stage: "RequestReceived", + }; + const first = JSON.stringify(event); + const second = JSON.stringify({ + ...event, + stage: "ResponseComplete", + responseObject: { text: "x".repeat(300) }, + }); + await writeFile(path, `${first}\n${second}\n`); + + const inspect = async (lineBytes: number) => { + const result = await cli.run({ + arguments: [ + "inspect-artifact", + path, + "--json", + "--artifact-limits", + JSON.stringify({ kubernetes_audit_log: { line_bytes: lineBytes } }), + ], + }); + expect(result.exitCode, result.stderr).toBe(0); + const inventory = readInventory(result.json); + expect(inventory.effective_limits).toMatchObject({ + kubernetes_audit_log: { line_bytes: lineBytes }, + }); + return inventory.occurrences.find((row) => row.logical_path === ".") + ?.format_metadata; + }; + + const smallAllowance = Buffer.byteLength(first); + expect(await inspect(smallAllowance)).toMatchObject({ + kind: "kubernetes-audit-log", + event_count: 1, + line_bytes_limit: smallAllowance, + malformed_line_count: 0, + oversized_line_count: 1, + }); + const measured = Buffer.byteLength(second); + expect(await inspect(measured)).toMatchObject({ + kind: "kubernetes-audit-log", + event_count: 2, + line_bytes_limit: measured, + malformed_line_count: 0, + oversized_line_count: 0, + }); +}); + +test("recognizes audit fields after a long first property in file and directory routes", async ({ + cli, + workspace, +}) => { + const path = workspace.path("capture.data"); + const unrelated = workspace.path("ordinary.data"); + const shadowed = workspace.path("shadowed.data"); + const requestObject = { body: "x".repeat(10 * 1024) }; + const identity = { auditID: "recorded", stage: "ResponseComplete" }; + await writeFile(path, `${JSON.stringify({ requestObject, ...identity })}\n`); + await writeFile( + unrelated, + `${JSON.stringify({ requestObject, payload: identity })}\n`, + ); + const earlyIdentity = JSON.stringify({ ...identity, requestObject }); + await writeFile( + shadowed, + `${earlyIdentity.slice(0, -1)},"stage":"Unknown"}\n`, + ); + + const target = await parseBinaryTarget(path); + expect(target).toMatchObject({ + ok: true, + value: { kind: "archive", format: "kubernetes-audit-log" }, + }); + expect(await parseBinaryTarget(shadowed)).not.toMatchObject({ + ok: true, + value: { format: "kubernetes-audit-log" }, + }); + + const inspect = async (selected: string) => { + const result = await cli.run({ + arguments: ["inspect-artifact", selected, "--json"], + }); + expect(result.exitCode, result.stderr).toBe(0); + return readInventory(result.json); + }; + expect((await inspect(path)).occurrences[0]?.format_metadata).toMatchObject({ + kind: "kubernetes-audit-log", + event_count: 1, + }); + expect((await inspect(workspace.root)).occurrences).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + logical_path: "capture.data", + artifact_format: "kubernetes-audit-log", + }), + expect.objectContaining({ + logical_path: "ordinary.data", + artifact_format: "file", + }), + expect.objectContaining({ + logical_path: "shadowed.data", + artifact_format: "file", + }), + ]), + ); +}); + +test("recognizes an oversized first event and inventories only admitted lines", async ({ + cli, + workspace, +}) => { + const path = workspace.path("capture.data"); + const defaultLineBytes = 4 * 1024 * 1024; + const oversized = JSON.stringify({ + requestObject: { body: "x".repeat(defaultLineBytes) }, + auditID: "oversized", + stage: "RequestReceived", + }); + const admitted = JSON.stringify({ + auditID: "admitted", + stage: "ResponseComplete", + }); + await writeFile(path, `${oversized}\n${admitted}\n`); + + const result = await cli.run({ + arguments: ["inspect-artifact", path, "--json"], + }); + expect(result.exitCode, result.stderr).toBe(0); + expect( + readInventory(result.json).occurrences[0]?.format_metadata, + ).toMatchObject({ + kind: "kubernetes-audit-log", + line_bytes_limit: defaultLineBytes, + event_count: 1, + oversized_line_count: 1, + malformed_line_count: 0, + events: [{ audit_id: "admitted" }], + }); +});