diff --git a/src/application/binaryDiagnostics/KernelModuleService.test.ts b/src/application/binaryDiagnostics/KernelModuleService.test.ts index 353f453fdba..837184ee7bd 100644 --- a/src/application/binaryDiagnostics/KernelModuleService.test.ts +++ b/src/application/binaryDiagnostics/KernelModuleService.test.ts @@ -102,19 +102,6 @@ it("rejects relative paths, extra arguments and invalid field budgets before rea expect(calls).toBe(0); }); -it("records an applicable module and its x86_64 architecture", async () => { - const result = await new KernelModuleService({ - identity, - inspect: () => Promise.resolve(ok(report)), - }).inspect({ path: report.artifact.path }); - if (!result.ok) throw result.error; - expect(result.value).toMatchObject({ - confidence: "observed", - subject: { identity: { format: "elf", architecture: "x86_64" } }, - normalized_result: report, - }); -}); - it("rejects a report whose entry count does not match the examined sections", async () => { const result = await new KernelModuleService({ identity, diff --git a/src/domain/native/kernelModule.test.ts b/src/domain/native/kernelModule.test.ts index a2e4b52087c..9d923eecca0 100644 --- a/src/domain/native/kernelModule.test.ts +++ b/src/domain/native/kernelModule.test.ts @@ -1,16 +1,10 @@ import { expect, it } from "vitest"; import { - KERNEL_MODULE_MODINFO_ENTRY_REASONS, inspectKernelModuleInputSchema, + kernelModuleSchema, } from "./kernelModule.js"; -it("rejects extra caller arguments and applies kernel-module budgets", () => { - expect( - inspectKernelModuleInputSchema.safeParse({ - path: "/artifacts/demo.ko", - extra: true, - }).success, - ).toBe(false); +it("applies the default kernel-module read and entry budgets", () => { expect( inspectKernelModuleInputSchema.parse({ path: "/artifacts/demo.ko" }), ).toMatchObject({ @@ -19,8 +13,11 @@ it("rejects extra caller arguments and applies kernel-module budgets", () => { }); }); -it("keeps modinfo field omission separate from entry validity", () => { - expect(KERNEL_MODULE_MODINFO_ENTRY_REASONS).not.toContain( - "modinfo_field_exceeds_limit", - ); +it("limits the external recovery probe to decompression", () => { + expect( + kernelModuleSchema.shape.next_probe.safeParse({ + operation: "extract_artifact", + rationale: "Test declared operation", + }).success, + ).toBe(false); }); diff --git a/src/native/elf/KernelModuleParser.test.ts b/src/native/elf/KernelModuleParser.test.ts index c444ba4d78f..231aefca278 100644 --- a/src/native/elf/KernelModuleParser.test.ts +++ b/src/native/elf/KernelModuleParser.test.ts @@ -6,21 +6,28 @@ import { kernelModuleSchema, MODULE_SIGNATURE_MAGIC, } from "../../domain/native/kernelModule.js"; -import { BinaryFormatFailure } from "../../domain/binaryContainer.js"; import { compressedKernelModuleContainer, kernelModuleFixture, modversionEntry, moduleSignatureTrailer, } from "./KernelModule.fixture.js"; -import { parseKernelModule } from "./KernelModuleParser.js"; +import { parseKernelModuleFromHandle } from "./KernelModuleParser.js"; const artifactPath = "/artifacts/demo.ko"; -const parse = (bytes: Buffer, extra: { readonly max_entries?: number } = {}) => +const parse = async ( + bytes: Buffer, + extra: { readonly max_entries?: number } = {}, +) => kernelModuleSchema.parse( - parseKernelModule( - bytes, + await parseKernelModuleFromHandle( + { + size: bytes.length, + prefix: bytes.subarray(0, 4096), + readRange: async (offset, length) => + bytes.subarray(offset, offset + length), + }, { path: artifactPath, sha256: "ab".repeat(32), @@ -36,13 +43,13 @@ const parse = (bytes: Buffer, extra: { readonly max_entries?: number } = {}) => const pkcs7 = Buffer.from("fake-pkcs7-bytes", "latin1"); const pkcs7Sha256 = createHash("sha256").update(pkcs7).digest("hex"); -it("preserves parameter duplicates, embedded equals, and original entry bytes", () => { +it("preserves parameter duplicates, embedded equals, and original entry bytes", async () => { const records = [ "parm=level:verbosity=a", "parmtype=level:int", "parm=level:again", ]; - const report = parse( + const report = await parse( kernelModuleFixture({ modinfo: Buffer.from(`${records.join("\0")}\0`) }), ); expect( @@ -60,13 +67,15 @@ it("preserves parameter duplicates, embedded equals, and original entry bytes", ); }); -it("distinguishes absent metadata from unavailable section names", () => { - const absent = parse(kernelModuleFixture({ modinfo: null, versions: null })); +it("distinguishes absent metadata from unavailable section names", async () => { + const absent = await parse( + kernelModuleFixture({ modinfo: null, versions: null }), + ); expect(absent.modinfo?.status).toBe("absent"); expect(absent.versions?.status).toBe("absent"); const bytes = kernelModuleFixture(); bytes.writeUInt16LE(0, 62); - const unknown = parse(bytes); + const unknown = await parse(bytes); expect(unknown.modinfo?.status).toBe("unknown"); expect(unknown.versions?.status).toBe("unknown"); expect(unknown.coverage.status).toBe("partial"); @@ -77,9 +86,21 @@ it.each([ [64, false], [32, true], [32, false], -] as const)("reports an ET_REL ELF%s %s module", (bits, little) => { - const report = parse(kernelModuleFixture({ bits, little })); - const width = bits === 64 ? 16 : 8; +] as const)("reports an ET_REL ELF%s %s module", async (bits, little) => { + const wideVersions = + bits === 64 + ? Buffer.concat([ + modversionEntry(0xfedcba9876543210n, "printk", 64, little), + modversionEntry(0x0100000000000002n, "module_layout", 64, little), + ]) + : undefined; + const report = await parse( + kernelModuleFixture({ + bits, + little, + ...(wideVersions === undefined ? {} : { versions: wideVersions }), + }), + ); expect(report).toMatchObject({ format: bits === 64 ? "elf64" : "elf32", byte_order: little ? "little" : "big", @@ -110,8 +131,8 @@ it.each([ expect( report.versions?.entries.map((entry) => [entry.crc_hex, entry.name]), ).toEqual([ - ["12345678".padStart(width, "0"), "printk"], - ["90abcdef".padStart(width, "0"), "module_layout"], + [bits === 64 ? "fedcba9876543210" : "12345678", "printk"], + [bits === 64 ? "0100000000000002" : "90abcdef", "module_layout"], ]); expect(report.this_module).toMatchObject({ status: "present", @@ -139,8 +160,8 @@ it.each([ [".exit.text", "exit_text", 1], ] as const)( "discloses duplicate %s sections while retaining the first size", - (name, key, size) => { - const report = parse( + async (name, key, size) => { + const report = await parse( kernelModuleFixture({ sharedNameSections: { name, count: 1, body: Buffer.from([1, 2, 3]) }, }), @@ -153,46 +174,36 @@ it.each([ }, ); -it("keeps earlier .modinfo entries when the last span is unterminated", () => { - const report = parse( +it("keeps readable fields and exact defects across a malformed .modinfo stream", async () => { + const report = await parse( kernelModuleFixture({ - modinfo: Buffer.from("license=GPL\0alias=pci:v3", "latin1"), + modinfo: Buffer.from( + "license=GPL\0license\0=GPL\0alias=pci:v3", + "latin1", + ), }), ); expect(report.modinfo?.status).toBe("present"); - expect(report.modinfo?.entries.map((entry) => entry.reason)).toEqual([ - null, - "unterminated_modinfo_entry", - ]); - expect(report.modinfo?.entries[1]).toMatchObject({ - status: "malformed", - key: "alias", - value: "pci:v3", - }); -}); - -it("reports a missing separator and an empty key as malformed entries", () => { - const report = parse( - kernelModuleFixture({ - modinfo: Buffer.from("license\0=GPL\0", "latin1"), - }), - ); - expect(report.modinfo?.entries.map((entry) => entry.reason)).toEqual([ - "modinfo_missing_separator", - "modinfo_empty_key", + expect( + report.modinfo?.entries.map(({ key, value, status, reason }) => [ + key, + value, + status, + reason, + ]), + ).toEqual([ + ["license", "GPL", "observed", null], + [null, null, "malformed", "modinfo_missing_separator"], + [null, "GPL", "malformed", "modinfo_empty_key"], + ["alias", "pci:v3", "malformed", "unterminated_modinfo_entry"], ]); expect(report.coverage.status).toBe("partial"); - expect(report.modinfo?.entries[1]).toMatchObject({ - key: null, - value: "GPL", - }); - expect( - report.modinfo?.entries.every((entry) => entry.status === "malformed"), - ).toBe(true); }); -it("closes __versions when the section size is not a multiple of 64", () => { - const report = parse(kernelModuleFixture({ versions: Buffer.alloc(63) })); +it("closes __versions when the section size is not a multiple of 64", async () => { + const report = await parse( + kernelModuleFixture({ versions: Buffer.alloc(63) }), + ); expect(report.coverage.status).toBe("partial"); expect(report.versions).toMatchObject({ status: "malformed", @@ -207,12 +218,12 @@ it("closes __versions when the section size is not a multiple of 64", () => { ); }); -it("observes a version name with nonzero padding and rejects a missing NUL", () => { +it("observes a version name with nonzero padding and rejects a missing NUL", async () => { const padded = modversionEntry(0x12345678, "printk", 64, true); padded[8 + "printk".length + 1] = 0x7f; const unterminated = Buffer.alloc(64, 0x41); unterminated.writeBigUInt64LE(0x11n, 0); - const report = parse( + const report = await parse( kernelModuleFixture({ versions: Buffer.concat([padded, unterminated]), }), @@ -231,8 +242,8 @@ it("observes a version name with nonzero padding and rejects a missing NUL", () }); }); -it("reports an inconsistent signature length without a PKCS#7 range", () => { - const report = parse( +it("reports an inconsistent signature length without a PKCS#7 range", async () => { + const report = await parse( kernelModuleFixture({ signature: moduleSignatureTrailer(Buffer.from("abcd"), 50_000), }), @@ -247,7 +258,7 @@ it("reports an inconsistent signature length without a PKCS#7 range", () => { expect(report.modinfo?.entries[0]?.key).toBe("license"); }); -it("withholds PKCS#7 bytes for nonzero signature parameters and a non-PKCS7 id", () => { +it("withholds PKCS#7 bytes for nonzero signature parameters and a non-PKCS7 id", async () => { const nonzero = Buffer.alloc(12); nonzero[0] = 1; nonzero[2] = 2; @@ -260,10 +271,12 @@ it("withholds PKCS#7 bytes for nonzero signature parameters and a non-PKCS7 id", const magic = Buffer.from(MODULE_SIGNATURE_MAGIC, "latin1"); const payload = Buffer.from("abcd"); expect( - parse( - kernelModuleFixture({ - signature: Buffer.concat([payload, nonzero, magic]), - }), + ( + await parse( + kernelModuleFixture({ + signature: Buffer.concat([payload, nonzero, magic]), + }), + ) ).signature, ).toMatchObject({ status: "malformed", @@ -271,10 +284,12 @@ it("withholds PKCS#7 bytes for nonzero signature parameters and a non-PKCS7 id", pkcs7: null, }); expect( - parse( - kernelModuleFixture({ - signature: Buffer.concat([payload, otherId, magic]), - }), + ( + await parse( + kernelModuleFixture({ + signature: Buffer.concat([payload, otherId, magic]), + }), + ) ).signature, ).toMatchObject({ status: "unsupported", @@ -284,8 +299,8 @@ it("withholds PKCS#7 bytes for nonzero signature parameters and a non-PKCS7 id", }); }); -it("does not examine kernel metadata on a non-relocatable ELF", () => { - const report = parse(kernelModuleFixture({ type: 2 })); +it("does not examine kernel metadata on a non-relocatable ELF", async () => { + const report = await parse(kernelModuleFixture({ type: 2 })); expect(report).toMatchObject({ applicability: "not_applicable", type: 2, @@ -299,8 +314,8 @@ it("does not examine kernel metadata on a non-relocatable ELF", () => { it.each(["gzip", "xz", "zstd"] as const)( "recommends external decompression for a %s container", - (codec) => { - const report = parse(compressedKernelModuleContainer(codec)); + async (codec) => { + const report = await parse(compressedKernelModuleContainer(codec)); expect(report).toMatchObject({ applicability: "unsupported", format: null, @@ -314,19 +329,13 @@ it.each(["gzip", "xz", "zstd"] as const)( expect(report.next_probe?.rationale).toContain( "call inspect_kernel_module on the decompressed file", ); - expect( - kernelModuleSchema.safeParse({ - ...report, - next_probe: { ...report.next_probe, operation: "extract_artifact" }, - }).success, - ).toBe(false); }, ); -it("fails closed when the combined entry budget is exhausted", () => { +it("fails closed when the combined entry budget is exhausted", async () => { let failure: unknown; try { - parse(kernelModuleFixture(), { max_entries: 7 }); + await parse(kernelModuleFixture(), { max_entries: 7 }); } catch (error) { failure = error; } @@ -334,8 +343,8 @@ it("fails closed when the combined entry budget is exhausted", () => { expect(failure).toMatchObject({ reason: "limit", boundary: "capacity" }); }); -it("examines the first of two .modinfo sections and records the duplicate", () => { - const report = parse( +it("examines the first of two .modinfo sections and records the duplicate", async () => { + const report = await parse( kernelModuleFixture({ modinfo: Buffer.from("name=first\0"), sharedNameSections: { @@ -348,71 +357,54 @@ it("examines the first of two .modinfo sections and records the duplicate", () = expect(report.modinfo?.entries.map(({ key, value }) => [key, value])).toEqual( [["name", "first"]], ); + expect(report.coverage.status).toBe("partial"); expect(report.limitations).toContainEqual( expect.stringMatching(/multiple.*\.modinfo.*first.*examined/iu), ); }); -it("does not decode compressed, nobits, or out-of-file metadata sections", () => { - const compressed = kernelModuleFixture(); - compressed.writeBigUInt64LE(0x800n, 64 + 64 + 8); - expect(parse(compressed).coverage.status).toBe("partial"); - expect(parse(compressed).modinfo).toMatchObject({ - status: "unsupported", - entries: [], - reason: "modinfo_section_compressed", - }); - const nobits = kernelModuleFixture(); - nobits.writeUInt32LE(8, 64 + 64 + 4); - expect(parse(nobits).modinfo).toMatchObject({ - status: "malformed", - location: null, - entries: [], - reason: "modinfo_section_not_file_backed", - }); - const outside = kernelModuleFixture(); - outside.writeBigUInt64LE(1_000_000n, 64 + 64 + 24); - expect(parse(outside).modinfo).toMatchObject({ - status: "malformed", - reason: "modinfo_section_not_file_backed", - }); - const versionsOutside = kernelModuleFixture(); - versionsOutside.writeBigUInt64LE(1_000_000n, 64 + 64 * 2 + 24); - expect(parse(versionsOutside).versions).toMatchObject({ - status: "malformed", - entries: [], - reason: "versions_section_not_file_backed", - }); - const versionsCompressed = kernelModuleFixture(); - versionsCompressed.writeBigUInt64LE(0x800n, 64 + 64 * 2 + 8); - expect(parse(versionsCompressed).versions).toMatchObject({ - status: "unsupported", - entries: [], - reason: "versions_section_compressed", - }); - const versionsNobits = kernelModuleFixture(); - versionsNobits.writeUInt32LE(8, 64 + 64 * 2 + 4); - expect(parse(versionsNobits).versions).toMatchObject({ - status: "malformed", - location: null, - entries: [], - reason: "versions_section_not_file_backed", - }); - const moduleSection = kernelModuleFixture(); - moduleSection.writeUInt32LE(8, 64 + 64 * 3 + 4); - expect(parse(moduleSection).this_module).toMatchObject({ +it.each([ + { index: 1, key: "modinfo" }, + { index: 2, key: "versions" }, +] as const)( + "keeps $key metadata unreadable when its storage is unavailable", + async ({ index, key }) => { + const header = 64 + index * 64; + const compressed = kernelModuleFixture(); + compressed.writeBigUInt64LE(0x800n, header + 8); + const packed = await parse(compressed); + expect(packed.coverage.status).toBe("partial"); + expect(packed[key]).toMatchObject({ + status: "unsupported", + entries: [], + reason: `${key}_section_compressed`, + }); + for (const nobits of [true, false]) { + const bytes = kernelModuleFixture(); + if (nobits) bytes.writeUInt32LE(8, header + 4); + else bytes.writeBigUInt64LE(1_000_000n, header + 24); + expect((await parse(bytes))[key]).toMatchObject({ + status: "malformed", + location: null, + entries: [], + reason: `${key}_section_not_file_backed`, + }); + } + }, +); + +it("keeps presence without a file range for a NOBITS module structure", async () => { + const bytes = kernelModuleFixture(); + bytes.writeUInt32LE(8, 64 + 64 * 3 + 4); + expect((await parse(bytes)).this_module).toMatchObject({ status: "present", location: null, layout: "unknown", }); }); -it("rejects a non-ELF file that is not a recognized container", () => { - expect(() => parse(Buffer.from("not an elf"))).toThrow(BinaryFormatFailure); -}); - -it("rejects ELF bytes preceding a bare signature magic as an inconsistent trailer", () => { - const report = parse( +it("rejects ELF bytes preceding a bare signature magic as an inconsistent trailer", async () => { + const report = await parse( kernelModuleFixture({ signature: Buffer.from(MODULE_SIGNATURE_MAGIC, "latin1"), }), @@ -426,8 +418,8 @@ it("rejects ELF bytes preceding a bare signature magic as an inconsistent traile expect(report.modinfo?.entries[0]?.key).toBe("license"); }); -it("records a missing trailer as observed absence", () => { - const report = parse(kernelModuleFixture({ signature: null })); +it("records a missing trailer as observed absence", async () => { + const report = await parse(kernelModuleFixture({ signature: null })); expect(report.signature).toMatchObject({ status: "absent", magic: null, @@ -440,10 +432,10 @@ it("records a missing trailer as observed absence", () => { ); }); -it("names a non-file-backed __ksymtab section without dropping the module", () => { +it("reports unbacked __ksymtab ranges while keeping module metadata", async () => { const bytes = kernelModuleFixture(); bytes.writeUInt32LE(8, 64 + 64 * 4 + 4); - const report = parse(bytes); + const report = await parse(bytes); expect(report.ksymtab?.sections).toEqual([]); expect(report.limitations).toContainEqual( expect.stringMatching( @@ -453,15 +445,20 @@ it("names a non-file-backed __ksymtab section without dropping the module", () = expect(report.modinfo?.entries[0]?.key).toBe("license"); }); -it("charges many sections sharing one huge __ksymtab name to the entry budget", () => { +it("charges many sections sharing one huge __ksymtab name to the entry budget", async () => { const name = `__ksymtab_${"x".repeat(65_490)}`; const bytes = kernelModuleFixture({ sharedNameSections: { name, count: 8192 }, }); - expect(() => parse(bytes)).toThrow(ArtifactReaderFailure); + const refused = parse(bytes); + await expect(refused).rejects.toBeInstanceOf(ArtifactReaderFailure); + await expect(refused).rejects.toMatchObject({ + reason: "limit", + boundary: "capacity", + }); // The shared name decodes once; per-section decoding exceeds the 16 MiB // section-name budget and refuses this module. - const report = parse(bytes, { max_entries: 65_536 }); + const report = await parse(bytes, { max_entries: 65_536 }); const huge = report.ksymtab?.sections.slice(1) ?? []; expect(huge).toHaveLength(8192); expect( @@ -475,23 +472,9 @@ it("charges many sections sharing one huge __ksymtab name to the entry budget", name: "__ksymtab", reason: null, }); - expect(report.coverage.examined_entries).toBe(6 + 2 + 1 + 8192); + expect(report.coverage).toEqual({ + status: "partial", + examined_entries: 8201, + }); expect(JSON.stringify(report).length).toBeLessThan(2 * 1024 * 1024); }); - -it.each([true, false])( - "keeps the upper CRC word of each ELF64 version record (little=%s)", - (little) => { - const versions = Buffer.concat([ - modversionEntry(0xfedcba9876543210n, "first", 64, little), - modversionEntry(0x0100000000000002n, "second", 64, little), - ]); - const report = parse(kernelModuleFixture({ bits: 64, little, versions })); - expect( - report.versions?.entries.map(({ crc_hex, name }) => [crc_hex, name]), - ).toEqual([ - ["fedcba9876543210", "first"], - ["0100000000000002", "second"], - ]); - }, -); diff --git a/src/native/elf/KernelModuleParser.ts b/src/native/elf/KernelModuleParser.ts index c41c0757875..9b92a8b1671 100644 --- a/src/native/elf/KernelModuleParser.ts +++ b/src/native/elf/KernelModuleParser.ts @@ -22,10 +22,7 @@ import { type ImageSection, type BinaryContainer, } from "../../domain/binaryContainer.js"; -import { - readElfImage, - readElfImageFromReader, -} from "../../domain/native/elfImage.js"; +import { readElfImageFromReader } from "../../domain/native/elfImage.js"; import type { NativeByteSource } from "../../domain/native/nativeSectionDirectory.js"; import { kernelCompressionCodecAt } from "./KernelCompressionCodec.js"; import { sha256Hex } from "../../kernel/sha256Hex.js"; @@ -485,32 +482,6 @@ const parseSignatureTrailer = ( }; }; -const parseSignatureFromBuffer = (bytes: Buffer): Report["signature"] => { - const tailLen = Math.min( - bytes.length, - MAGIC.length + MODULE_SIGNATURE_INFO_BYTES, - ); - const trailer = parseSignatureTrailer( - bytes.length, - bytes.subarray(bytes.length - tailLen), - ); - if (trailer.done) return trailer.signature; - const pkcs7 = bytes.subarray( - trailer.pkcs7Offset, - trailer.pkcs7Offset + trailer.pkcs7Bytes, - ); - return { - status: "present", - magic: trailer.magic, - info: trailer.info, - pkcs7: { - location: { offset: trailer.pkcs7Offset, bytes: trailer.pkcs7Bytes }, - sha256: sha256Hex(pkcs7), - }, - reason: null, - }; -}; - const parseSignatureFromSource = async ( source: NativeByteSource, ): Promise => { @@ -663,7 +634,7 @@ interface KernelModulePrepared { } const prepareKernelModule = ( - image: ReturnType, + image: Extract, ): KernelModulePrepared => { const facts = headerFacts(image); const sections = image.sections.filter( @@ -828,78 +799,6 @@ const finalizeKernelModule = ( }; }; -/** Decode kernel-module metadata from an admitted in-memory ELF image. */ -const parseKernelModuleImage = ( - bytes: Buffer, - artifact: Report["artifact"], - input: InspectKernelModuleInput, - image: ReturnType, -): Report => { - const facts = headerFacts(image); - if (facts.type !== 1) return notApplicable(artifact, facts); - const prepared = prepareKernelModule(image); - const modinfoLoc = modinfoSectionLocation( - prepared.modinfoSection, - bytes.length, - prepared.use, - ); - const modinfo = modinfoLoc.ready - ? parseModinfoStored( - bytes.subarray( - modinfoLoc.location.offset, - modinfoLoc.location.offset + modinfoLoc.location.bytes, - ), - modinfoLoc.location, - modinfoLoc.compressed, - prepared.use, - prepared.examined, - input, - ) - : modinfoLoc.result; - const versionsLoc = versionsSectionLocation( - prepared.versionsSection, - bytes.length, - image.bits, - prepared.use, - ); - const versions = versionsLoc.ready - ? parseVersionsStored( - bytes.subarray( - versionsLoc.location.offset, - versionsLoc.location.offset + versionsLoc.location.bytes, - ), - versionsLoc.location, - versionsLoc.compressed, - image.bits, - image.byte_order === "little", - prepared.examined, - input.max_entries, - ) - : versionsLoc.result; - return finalizeKernelModule( - bytes.length, - artifact, - input, - prepared, - modinfo, - versions, - parseSignatureFromBuffer(bytes), - ); -}; - -export const parseKernelModule = ( - bytes: Buffer, - artifact: Report["artifact"], - input: InspectKernelModuleInput, -): Report => - moduleCompressionReport(bytes, artifact) ?? - parseKernelModuleImage( - bytes, - artifact, - input, - readElfImage(bytes, "inspect_kernel_module"), - ); - /** Decode kernel-module metadata positionally over a bounded file handle. */ export const parseKernelModuleFromHandle = async ( source: NativeByteSource, diff --git a/tests/acceptance/kernelModuleCli.test.ts b/tests/acceptance/kernelModuleCli.test.ts index bec0c9ea724..3219c05a6d3 100644 --- a/tests/acceptance/kernelModuleCli.test.ts +++ b/tests/acceptance/kernelModuleCli.test.ts @@ -69,7 +69,16 @@ cliTest( async ({ cli }) => { const root = await createTestTempDirectory("rea-kernel-module-cli-"); const path = join(root, "demo.ko"); - await writeFile(path, kernelModuleFixture()); + await writeFile( + path, + kernelModuleFixture({ + sharedNameSections: { + name: ".init.text", + count: 1, + body: Buffer.from([1, 2, 3]), + }, + }), + ); const result = await cli.run({ arguments: ["inspect-kernel-module", path, "--json"], }); @@ -93,39 +102,13 @@ cliTest( expect(evidence.normalized_result.versions?.entries[0]?.crc_hex).toBe( "0000000012345678", ); - expect(evidence.normalized_result.signature?.status).toBe("present"); - }, -); - -cliTest( - "reports duplicate sections as partial through the public CLI", - async ({ cli }) => { - const root = await createTestTempDirectory("rea-kernel-module-duplicate-"); - const path = join(root, "duplicate.ko"); - await writeFile( - path, - kernelModuleFixture({ - sharedNameSections: { - name: ".init.text", - count: 1, - body: Buffer.from([1, 2, 3]), - }, - }), - ); - const result = await cli.run({ - arguments: ["inspect-kernel-module", path, "--json"], + expect(evidence.normalized_result).toMatchObject({ + signature: { status: "present" }, + coverage: { status: "partial" }, + init_text: { status: "present", bytes: 4 }, }); - expect(result.exitCode, result.stderr).toBe(0); - const evidence = toolContract("inspect_kernel_module").outputSchema.parse( - result.json, - ); - expect(evidence.normalized_result.coverage.status).toBe("partial"); - expect(evidence.normalized_result.init_text).toMatchObject({ - status: "present", - bytes: 4, - }); - expect(evidence.normalized_result.limitations).toContain( - "Multiple .init.text sections are declared; the first is examined.", + expect(evidence.normalized_result.limitations).toContainEqual( + expect.stringMatching(/Multiple \.init\.text .*first .*examined/u), ); }, ); @@ -149,20 +132,6 @@ cliTest( }, ); -cliTest("reports a non-ELF file as invalid input", async ({ cli }) => { - const root = await createTestTempDirectory("rea-kernel-module-cli-bad-"); - const path = join(root, "broken.ko"); - await writeFile(path, Buffer.from("not an elf")); - const result = await cli.run({ - arguments: ["inspect-kernel-module", path, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "invalid_request", - details: { operation: "inspect_kernel_module" }, - }); -}); - cliTest( "reports a compressed container without claiming the payload is a module", async ({ cli }) => { diff --git a/tests/acceptance/stableArtifactParserFailureCli.test.ts b/tests/acceptance/stableArtifactParserFailureCli.test.ts index edd9fa8b8bc..b762b3622bb 100644 --- a/tests/acceptance/stableArtifactParserFailureCli.test.ts +++ b/tests/acceptance/stableArtifactParserFailureCli.test.ts @@ -31,11 +31,11 @@ for (const command of [ await writeFile(path, bytes); const result = await cli.run({ arguments: [command, path, "--json"] }); expect(result.exitCode, result.stderr).toBe(1); - if (isBeam) { + if (isBeam || command === "inspect-kernel-module") { expect(result.json).toMatchObject({ code: "invalid_request", details: { - operation: "inspect_erlang_beam", + operation: command.replaceAll("-", "_"), issues: [{ path: ["path"], reason: "invalid_format" }], }, }); diff --git a/tests/boundary/filesystem/kernelModule.test.ts b/tests/boundary/filesystem/kernelModule.test.ts index af553ef25e1..1db8805e4fd 100644 --- a/tests/boundary/filesystem/kernelModule.test.ts +++ b/tests/boundary/filesystem/kernelModule.test.ts @@ -1,10 +1,11 @@ +import { createHash } from "node:crypto"; import { fileIdentity } from "../../fixtures/evidenceSubject.js"; import { symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createKernelModuleService } from "../../../src/composition/binaryDiagnostics/kernelModule.js"; +import { kernelModuleSchema } from "../../../src/domain/native/kernelModule.js"; import { - compressedKernelModuleContainer, kernelModuleFixture, moduleSignatureTrailer, } from "../../../src/native/elf/KernelModule.fixture.js"; @@ -48,28 +49,53 @@ describe("kernel module stable filesystem boundary", () => { const root = await createTestTempDirectory("rea-kernel-module-positional-"); const path = join(root, "demo.ko"); // Enough section headers to place .modinfo and the signature beyond 4 KiB. + const pkcs7 = Buffer.from("module signature outside prefix"); + const trailer = moduleSignatureTrailer(pkcs7); const bytes = kernelModuleFixture({ sharedNameSections: { name: ".padding", count: 70 }, + signature: trailer, }); const firstSection = Number(bytes.readBigUInt64LE(40)) + 64; const modinfoOffset = Number(bytes.readBigUInt64LE(firstSection + 24)); + const versionsOffset = Number( + bytes.readBigUInt64LE(firstSection + 64 + 24), + ); expect(modinfoOffset).toBeGreaterThan(4096); + expect(versionsOffset).toBeGreaterThan(4096); await writeFile(path, bytes); const service = createKernelModuleService(); try { const result = await service.inspect({ path }); if (!result.ok) throw result.error; - expect(result.value.normalized_result).toMatchObject({ - modinfo: { - entries: expect.arrayContaining([ - expect.objectContaining({ - key: "license", - value: "GPL", - location: { offset: modinfoOffset, bytes: expect.any(Number) }, - }), - ]), + expect(fileIdentity(result.value.subject)).toMatchObject({ + format: "elf", + architecture: "x86_64", + }); + expect(result.value.confidence).toBe("observed"); + const report = kernelModuleSchema.parse(result.value.normalized_result); + expect(report.modinfo?.entries[0]).toMatchObject({ + key: "license", + value: "GPL", + location: { offset: modinfoOffset, bytes: 12 }, + }); + expect(report.versions?.location).toEqual({ + offset: versionsOffset, + bytes: 128, + }); + expect(report.versions?.entries[0]).toMatchObject({ + crc_hex: "0000000012345678", + name: "printk", + location: { offset: versionsOffset, bytes: 64 }, + }); + expect(report.signature).toMatchObject({ + status: "present", + pkcs7: { + location: { + offset: bytes.length - trailer.length, + bytes: pkcs7.length, + }, + sha256: createHash("sha256").update(pkcs7).digest("hex"), }, - signature: { status: "present" }, }); } finally { await service.close(); @@ -134,27 +160,4 @@ describe("kernel module stable filesystem boundary", () => { await service.close(); } }); - - it.each(["gzip", "xz", "zstd"] as const)( - "reports a %s container as unsupported without treating it as a module", - async (codec) => { - const root = await createTestTempDirectory(`rea-kernel-module-${codec}-`); - const path = join(root, `demo.ko.${codec === "gzip" ? "gz" : codec}`); - await writeFile(path, compressedKernelModuleContainer(codec)); - const service = createKernelModuleService(); - try { - const result = await service.inspect({ path }); - if (!result.ok) throw result.error; - expect(fileIdentity(result.value.subject).format).toBe("file"); - expect(result.value.normalized_result).toMatchObject({ - applicability: "unsupported", - compression: { codec, status: "unsupported" }, - next_probe: { operation: "external_decompression" }, - modinfo: null, - }); - } finally { - await service.close(); - } - }, - ); }); diff --git a/tests/boundary/mcp/kernelModuleMcp.test.ts b/tests/boundary/mcp/kernelModuleMcp.test.ts index 19bc40e95ab..f05525a23a4 100644 --- a/tests/boundary/mcp/kernelModuleMcp.test.ts +++ b/tests/boundary/mcp/kernelModuleMcp.test.ts @@ -9,10 +9,7 @@ import { toolContract } from "../../../src/contracts/toolContracts.js"; import { createServer } from "../../../src/server/createServer.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; -import { - compressedKernelModuleContainer, - kernelModuleFixture, -} from "../../../src/native/elf/KernelModule.fixture.js"; +import { kernelModuleFixture } from "../../../src/native/elf/KernelModule.fixture.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js"; @@ -45,11 +42,15 @@ mcpTest( expect(response.isError, JSON.stringify(response.content)).not.toBe( true, ); - return toolContract("inspect_kernel_module").outputSchema.parse( - response.structuredContent, - ); + return response.structuredContent; }; - const initial = await inspect(); + const initialReply = await inspect(); + const outputSchema = canonicalOutputSchema("inspect_kernel_module"); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + expect(ajv.validateSchema(outputSchema as AnySchema)).toBe(true); + expect(ajv.compile(outputSchema as AnySchema)(initialReply)).toBe(true); + const parse = toolContract("inspect_kernel_module").outputSchema.parse; + const initial = parse(initialReply); const omitted = initial.normalized_result.modinfo?.entries[0]; expect(omitted).toMatchObject({ status: "observed", @@ -59,6 +60,24 @@ mcpTest( omitted_fields: ["key", "value"], raw_hex: null, }); + expect(() => + parse({ + ...initial, + normalized_result: { + ...initial.normalized_result, + modinfo: { + ...initial.normalized_result.modinfo, + entries: [ + { + ...omitted, + status: "malformed", + reason: "modinfo_field_exceeds_limit", + }, + ], + }, + }, + }), + ).toThrow(); expect(initial.normalized_result.coverage.status).toBe("partial"); expect(initial.normalized_result.limitations).toEqual( expect.arrayContaining([ @@ -88,10 +107,12 @@ mcpTest( expect(initial.normalized_result.limitations.join(" ")).not.toContain( "--max-modinfo", ); - const recovered = await inspect({ - max_modinfo_key_bytes: 257, - max_modinfo_value_bytes: 4097, - }); + const recovered = parse( + await inspect({ + max_modinfo_key_bytes: 257, + max_modinfo_value_bytes: 4097, + }), + ); expect(recovered.subject).toEqual(initial.subject); expect(recovered.normalized_result.modinfo?.entries[0]).toEqual({ ...omitted, @@ -152,53 +173,6 @@ mcpTest( }, ); -mcpTest( - "reports duplicate sections as partial in MCP Evidence", - async ({ mcp }) => { - const { client, session } = await connect(mcp); - try { - const root = await createTestTempDirectory( - "rea-kernel-module-duplicate-mcp-", - ); - const path = join(root, "duplicate.ko"); - await writeFile( - path, - kernelModuleFixture({ - sharedNameSections: { - name: ".exit.text", - count: 1, - body: Buffer.from([1, 2, 3]), - }, - }), - ); - const response = await client.callTool({ - name: "inspect_kernel_module", - arguments: { path }, - }); - expect(response.isError, JSON.stringify(response.content)).not.toBe(true); - const outputSchema = canonicalOutputSchema("inspect_kernel_module"); - const ajv = new Ajv2020({ strict: false, validateFormats: false }); - expect(ajv.validateSchema(outputSchema as AnySchema)).toBe(true); - expect( - ajv.compile(outputSchema as AnySchema)(response.structuredContent), - ).toBe(true); - const evidence = toolContract("inspect_kernel_module").outputSchema.parse( - response.structuredContent, - ); - expect(evidence.normalized_result.coverage.status).toBe("partial"); - expect(evidence.normalized_result.exit_text).toMatchObject({ - status: "present", - bytes: 1, - }); - expect(evidence.normalized_result.limitations).toContain( - "Multiple .exit.text sections are declared; the first is examined.", - ); - } finally { - await session.close(); - } - }, -); - mcpTest( "requires an absolute path for inspect_kernel_module", async ({ mcp }) => { @@ -218,30 +192,3 @@ mcpTest( } }, ); - -mcpTest( - "reports a zstd container as an unsupported kernel-module target", - async ({ mcp }) => { - const { client, session } = await connect(mcp); - try { - const root = await createTestTempDirectory("rea-kernel-module-zstd-mcp-"); - const path = join(root, "demo.ko.zst"); - await writeFile(path, compressedKernelModuleContainer("zstd")); - const response = await client.callTool({ - name: "inspect_kernel_module", - arguments: { path }, - }); - expect(response.isError, JSON.stringify(response.content)).not.toBe(true); - const evidence = toolContract("inspect_kernel_module").outputSchema.parse( - response.structuredContent, - ); - expect(evidence.normalized_result).toMatchObject({ - applicability: "unsupported", - compression: { codec: "zstd", status: "unsupported" }, - next_probe: { operation: "external_decompression" }, - }); - } finally { - await session.close(); - } - }, -);