diff --git a/src/application/binaryDiagnostics/ElfDebugLinkService.test.ts b/src/application/binaryDiagnostics/ElfDebugLinkService.test.ts index 44b427dcf9..8f86a5fb59 100644 --- a/src/application/binaryDiagnostics/ElfDebugLinkService.test.ts +++ b/src/application/binaryDiagnostics/ElfDebugLinkService.test.ts @@ -5,9 +5,12 @@ import { expect, it } from "vitest"; import { ElfDebugLinkService } from "./ElfDebugLinkService.js"; import { ELF_DEBUG_LINK_PROVIDER } from "../../domain/investigationProviders.js"; import { + DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES, deriveDebugFileLookupPaths, - ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, + MAX_ELF_DEBUG_CANDIDATE_BYTES, ELF_DEBUG_LINK_CANNOT_VERIFY_LIMITATION, ELF_DEBUG_LINK_LIMITATIONS, type ElfDebugLink, @@ -132,89 +135,118 @@ it("rejects a report whose type name, lookup paths, or verification disagree", a }), coverage: { status: "complete", examined_sections: 1 }, }; - const cases: ElfDebugLink[] = [ - { ...report, type_name: "executable" }, - { - ...linked, - lookup_paths: linked.lookup_paths.map((entry) => - entry.kind === "build_id" ? { ...entry, path: "/tmp/other" } : entry, - ), + const candidate = { + path: "/artifacts/prog.debug", + sha256: digest, + bytes: 32, + format: "elf64", + byte_order: "little", + debug_info: "present", + symtab: "present", + } as const; + const verification = { + status: "matches", + reason: null, + crc32: { + status: "match", + expected_hex: "12345678", + observed_hex: "12345678", + reason: null, }, - { - ...linked, - candidate: { - path: "/artifacts/prog.debug", - sha256: digest, - bytes: 32, - format: "elf64", - byte_order: "little", - debug_info: "present", - symtab: "present", - }, - verification: { - status: "matches", - reason: null, - crc32: { - status: "match", - expected_hex: "00000000", - observed_hex: "00000000", - reason: null, - }, - build_id: { - status: "match", - binary_hex: "abcd", - candidate_hex: "abcd", - reason: null, - }, - }, - }, - ]; - for (const value of cases) { - const result = await serviceFor(value).inspect({ - path: report.artifact.path, - ...(value.candidate === null - ? {} - : { candidate_path: value.candidate.path }), - }); - expect(result.ok).toBe(false); - if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError); - } - const unexpectedCandidate = await serviceFor({ - ...report, - candidate: { - path: "/artifacts/prog.debug", - sha256: digest, - bytes: 32, - format: null, - byte_order: null, - debug_info: "not_elf", - symtab: "not_elf", - }, - verification: { - status: "cannot_verify", - reason: "no_comparable_identity", - crc32: { - status: "unavailable", - expected_hex: null, - observed_hex: "00000000", - reason: "debuglink_crc_absent", - }, - build_id: { - status: "unavailable", - binary_hex: null, - candidate_hex: null, - reason: "binary_build_id_absent", - }, + build_id: { + status: "match", + binary_hex: "abcd", + candidate_hex: "abcd", + reason: null, }, + } as const; + const interruptedCandidate = { + ...candidate, + format: null, + byte_order: null, + debug_info: "unknown", + symtab: "unknown", + } as const; + const interrupted: ElfDebugLink = { + ...linked, + candidate: interruptedCandidate, limitations: [ - ...ELF_DEBUG_LINK_LIMITATIONS, - "Neither the debuglink CRC32 nor the GNU build-id could be compared with the candidate.", + ...linked.limitations, + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, ], - }).inspect({ path: report.artifact.path }); - expect(unexpectedCandidate.ok).toBe(false); + }; + const imageInput = { path: report.artifact.path }; + const selectedInput = { ...imageInput, candidate_path: candidate.path }; + const cases = [ + { value: { ...report, type_name: "executable" }, input: imageInput }, + { + value: { + ...linked, + lookup_paths: linked.lookup_paths.map((entry) => + entry.kind === "build_id" ? { ...entry, path: "/tmp/other" } : entry, + ), + }, + input: imageInput, + }, + { + value: { ...linked, candidate, verification }, + input: imageInput, + }, + { + value: { + ...linked, + candidate, + verification: { + ...verification, + crc32: { + ...verification.crc32, + expected_hex: "00000000", + observed_hex: "00000000", + }, + }, + }, + input: selectedInput, + }, + { value: interrupted, input: selectedInput }, + ] satisfies { value: ElfDebugLink; input: object }[]; + for (const { value, input } of cases) { + const result = await serviceFor(value).inspect(input); + if (result.ok) throw new Error("Unexpected debug-link report admission"); + expect(result.error).toBeInstanceOf(AnalysisOutputError); + } + for (const invalid of [ + { + ...interrupted, + candidate: { ...interruptedCandidate, path: "/artifacts/foreign.debug" }, + }, + { + ...interrupted, + candidate: { + ...interruptedCandidate, + bytes: MAX_ELF_DEBUG_CANDIDATE_BYTES + 1, + }, + }, + { + ...interrupted, + limitations: [ + ...interrupted.limitations, + ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, + ], + }, + ]) { + const error = new AnalysisCancelledError("inspect_elf_debug_link", { + partialObservation: invalid, + }); + const result = await new ElfDebugLinkService({ + identity, + inspect: () => Promise.resolve(err(error)), + }).inspect(selectedInput); + if (result.ok) throw new Error("Expected candidate cancellation"); + expect(result.error.partialObservation).toBe(invalid); + } }); -it("accepts an unreadable-candidate verdict only with its limitations", async () => { +it("rejects an unreadable-candidate verdict without its limitation", async () => { const unreadable: ElfDebugLink = { ...report, candidate: null, @@ -236,7 +268,6 @@ it("accepts an unreadable-candidate verdict only with its limitations", async () }, limitations: [ ...ELF_DEBUG_LINK_LIMITATIONS, - ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, ELF_DEBUG_LINK_CANNOT_VERIFY_LIMITATION, ], }; @@ -244,17 +275,10 @@ it("accepts an unreadable-candidate verdict only with its limitations", async () path: report.artifact.path, candidate_path: "/artifacts/missing.debug", }; - const accepted = await serviceFor(unreadable).inspect(input); - if (!accepted.ok) throw accepted.error; - expect(accepted.value.normalized_result).toEqual(unreadable); - const unlabelled = await serviceFor({ - ...unreadable, - limitations: [ - ...ELF_DEBUG_LINK_LIMITATIONS, - ELF_DEBUG_LINK_CANNOT_VERIFY_LIMITATION, - ], - }).inspect(input); - expect(unlabelled.ok).toBe(false); + const result = await serviceFor(unreadable).inspect(input); + if (result.ok) + throw new Error("Expected missing unreadable-candidate limitation to fail"); + expect(result.error).toBeInstanceOf(AnalysisOutputError); }); it("retains a completed observation if the caller cancels while the provider completes", async () => { @@ -304,7 +328,10 @@ it("keeps omitted and explicitly selected defaults distinct in complete and part const observations = []; for (const parameters of [ { path: report.artifact.path }, - { path: report.artifact.path, max_entries: 32 }, + { + path: report.artifact.path, + max_entries: DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES, + }, ]) { const result = await service.inspect(parameters); const evidence = parseEvidence( @@ -318,35 +345,6 @@ it("keeps omitted and explicitly selected defaults distinct in complete and part } }); -it("retains the selected candidate when cancellation leaves only the completed image report", async () => { - const partial = { - ...report, - limitations: [ - ...report.limitations, - ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, - ], - }; - const error = new AnalysisCancelledError("inspect_elf_debug_link", { - partialObservation: partial, - }); - const service = new ElfDebugLinkService({ - identity, - inspect: () => Promise.resolve(err(error)), - }); - const parameters = { - path: report.artifact.path, - candidate_path: "/artifacts/prog.debug", - }; - const result = await service.inspect(parameters); - expect(result.ok).toBe(false); - if (result.ok) throw new Error("Expected candidate cancellation"); - expect(result.error).toBe(error); - expect(parseEvidence(result.error.partialObservation)).toMatchObject({ - parameters, - normalized_result: partial, - }); -}); - it("keeps caller Evidence after retained cleanup releases and reveals the primary failure", async () => { const parameters = { path: report.artifact.path, @@ -376,6 +374,7 @@ it("keeps caller Evidence after retained cleanup releases and reveals the primar }); const result = await service.inspect(parameters); if (result.ok) throw new Error("Expected retained cleanup failure"); + expect(result.error).toBe(failure); const before = parseEvidence(result.error.partialObservation); expect(result.error.cleanupIncomplete).toBe(true); completion.cleanupReleased = true; @@ -384,4 +383,5 @@ it("keeps caller Evidence after retained cleanup releases and reveals the primar const after = parseEvidence(resolved.partialObservation); expect(after).toEqual(before); expect(after.parameters).toEqual(parameters); + expect(after.normalized_result).toEqual(partial); }); diff --git a/src/application/binaryDiagnostics/ElfDebugLinkService.ts b/src/application/binaryDiagnostics/ElfDebugLinkService.ts index 210b010d27..34517c573f 100644 --- a/src/application/binaryDiagnostics/ElfDebugLinkService.ts +++ b/src/application/binaryDiagnostics/ElfDebugLinkService.ts @@ -9,7 +9,9 @@ import { deriveDebugFileLookupPaths, elfDebugLinkSchema, ELF_DEBUG_LINK_CANDIDATE_PREFIX_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_BUDGET_LIMITATION, ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, ELF_DEBUG_LINK_CANNOT_VERIFY_LIMITATION, ELF_DEBUG_LINK_LIMITATIONS, @@ -58,32 +60,24 @@ export class ElfDebugLinkService { if (!result.ok) { const source = result.error.partialObservation; const partial = elfDebugLinkSchema.safeParse(source); - if (partial.success) { - const partialInput = - partial.data.verification === null && - partial.data.limitations.includes( - ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, - ) - ? { ...input.value, candidate_path: undefined } - : input.value; - if ( - partial.data.artifact.path === input.value.path && - validReport(partial.data, partialInput) - ) { - const evidence = createElfDebugLinkEvidence( - partial.data, - this.provider.identity, - parameters, - ); - // Cleanup completion can reveal any primary that shares this exact report. - for ( - let owner: AnalysisError | undefined = result.error; - owner !== undefined; - owner = owner.cleanupPrimary - ) - if (owner.partialObservation === source) - owner.partialObservation = evidence; - } + if ( + partial.success && + partial.data.artifact.path === input.value.path && + validReport(partial.data, input.value, "partial") + ) { + const evidence = createElfDebugLinkEvidence( + partial.data, + this.provider.identity, + parameters, + ); + // Cleanup completion can reveal any primary that shares this exact report. + for ( + let owner: AnalysisError | undefined = result.error; + owner !== undefined; + owner = owner.cleanupPrimary + ) + if (owner.partialObservation === source) + owner.partialObservation = evidence; } return result; } @@ -91,7 +85,7 @@ export class ElfDebugLinkService { if ( !report.success || report.data.artifact.path !== input.value.path || - !validReport(report.data, input.value) + !validReport(report.data, input.value, "complete") ) return err( new AnalysisOutputError( @@ -310,9 +304,10 @@ const unreadableAgrees = ( (report.build_id.status === "observed" ? report.build_id.hex : null) && verification.build_id.candidate_hex === null; -const verificationAgrees = (report: ElfDebugLink): boolean => { - const verification = report.verification; - if (verification === null) return report.candidate === null; +const verificationAgrees = ( + report: ElfDebugLink, + verification: NonNullable, +): boolean => { const crc = verification.crc32; const build = verification.build_id; if (report.candidate === null) return unreadableAgrees(report, verification); @@ -481,7 +476,14 @@ const limitationAgrees = (report: ElfDebugLink): boolean => { ) return false; const verification = report.verification; - if (verification === null) return true; + if (verification === null) + return ![ + ELF_DEBUG_LINK_CANDIDATE_PREFIX_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_BUDGET_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, + ELF_DEBUG_LINK_UNAVAILABLE_CHECK_LIMITATION, + ELF_DEBUG_LINK_CANNOT_VERIFY_LIMITATION, + ].some((line) => report.limitations.includes(line)); if ( (verification.reason === "candidate_unreadable") !== report.limitations.includes(ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION) @@ -520,6 +522,7 @@ const lookupAgrees = (report: ElfDebugLink): boolean => { const validReport = ( report: ElfDebugLink, input: InspectElfDebugLinkInput, + outcome: "complete" | "partial", ): boolean => { if ( report.artifact.bytes > input.max_file_bytes || @@ -536,14 +539,43 @@ const validReport = ( !examinedAgrees(report) || !coverageAgrees(report) || !lookupAgrees(report) || - !limitationAgrees(report) || - !verificationAgrees(report) + !limitationAgrees(report) ) return false; + const { candidate, verification } = report; + const readIncomplete = report.limitations.includes( + ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, + ); + const comparisonIncomplete = report.limitations.includes( + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, + ); if (input.candidate_path === undefined) - return report.candidate === null && report.verification === null; - if (report.verification === null) return false; - const candidate = report.candidate; + return ( + candidate === null && + verification === null && + !readIncomplete && + !comparisonIncomplete + ); + if (candidate !== null && candidate.path !== input.candidate_path) + return false; + if (verification === null) { + if (outcome === "complete") return false; + if (candidate === null) return readIncomplete && !comparisonIncomplete; + return ( + comparisonIncomplete && + !readIncomplete && + candidate.format === null && + candidate.byte_order === null && + candidate.debug_info === "unknown" && + candidate.symtab === "unknown" + ); + } + if ( + readIncomplete || + comparisonIncomplete || + !verificationAgrees(report, verification) + ) + return false; if (candidate === null) return !report.limitations.includes( ELF_DEBUG_LINK_CANDIDATE_PREFIX_LIMITATION, @@ -552,7 +584,6 @@ const validReport = ( // but only its ELF header was decoded. const streamed = candidate.bytes > input.max_file_bytes; if ( - candidate.path !== input.candidate_path || streamed !== report.limitations.includes(ELF_DEBUG_LINK_CANDIDATE_PREFIX_LIMITATION) || (streamed && @@ -560,5 +591,5 @@ const validReport = ( (candidate.debug_info !== "unknown" || candidate.symtab !== "unknown")) ) return false; - return candidateAgrees(candidate, report.verification?.build_id.reason); + return candidateAgrees(candidate, verification.build_id.reason); }; diff --git a/src/domain/native/elfDebugLink.test.ts b/src/domain/native/elfDebugLink.test.ts index 4f5ed80e30..e2b931eed1 100644 --- a/src/domain/native/elfDebugLink.test.ts +++ b/src/domain/native/elfDebugLink.test.ts @@ -65,6 +65,10 @@ it("uses the directory of a POSIX image path", () => { }); it("uses the directory of a Windows image path with a drive letter", () => { + expect(directoryStrings("C:/dir/sub/prog")).toEqual([ + "C:/dir/sub/.debug/prog.debug", + "/usr/lib/debug/C/dir/sub/prog.debug", + ]); expect(directoryStrings("C:\\dir\\sub\\prog")).toEqual([ "C:\\dir\\sub\\.debug\\prog.debug", "/usr/lib/debug/C/dir/sub/prog.debug", diff --git a/src/domain/native/elfDebugLink.ts b/src/domain/native/elfDebugLink.ts index 46d3a0857f..a35ce6e3dd 100644 --- a/src/domain/native/elfDebugLink.ts +++ b/src/domain/native/elfDebugLink.ts @@ -63,6 +63,10 @@ export const ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION = export const ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION = "The candidate read did not complete, so the candidate was not compared. Only the image linkage is retained."; +/** Candidate bytes were acquired without settling the ELF comparison. */ +export const ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION = + "The candidate read completed. Its ELF comparison did not complete."; + /** * Whole-file ceiling for a streamed candidate. Only `max_file_bytes` of it is * retained for ELF decoding; the rest is hashed in bounded chunks. @@ -338,7 +342,7 @@ const imageDirectory = ( const segments = rest.split(/[\\/]+/u).filter((part) => part.length > 0); return { directory, - separator: "\\", + separator: binaryPath.includes("\\") ? "\\" : "/", globalRelative: [ ...(letter === undefined ? [] : [letter]), ...segments, diff --git a/src/native/elf/ElfDebugLink.test.ts b/src/native/elf/ElfDebugLink.test.ts index 883d7dd326..b13439365a 100644 --- a/src/native/elf/ElfDebugLink.test.ts +++ b/src/native/elf/ElfDebugLink.test.ts @@ -29,16 +29,12 @@ const digest = "ab".repeat(32); const inputFor = (extra: { readonly max_entries?: number } = {}) => inspectElfDebugLinkInputSchema.parse({ path: artifactPath, ...extra }); -const parse = ( - bytes: Buffer, - extra: { readonly max_entries?: number } = {}, - path = artifactPath, -) => +const parse = (bytes: Buffer, extra: { readonly max_entries?: number } = {}) => elfDebugLinkSchema.parse( parseElfDebugLink( bytes, - { path, sha256: digest, bytes: bytes.length }, - inspectElfDebugLinkInputSchema.parse({ path, ...extra }), + { path: artifactPath, sha256: digest, bytes: bytes.length }, + inspectElfDebugLinkInputSchema.parse({ path: artifactPath, ...extra }), ), ); @@ -270,13 +266,7 @@ it("reads the build-id beside glibc's SystemTap probe notes by default", () => { }); }); -it("preserves parent-directory segments and omits a slash name", () => { - const preserved = parse(elfDebugLinkFixture(), {}, "/var/tmp/../lib/prog"); - expect( - preserved.lookup_paths.find( - (entry) => entry.kind === "global_debug_directory", - )?.path, - ).toBe("/usr/lib/debug/var/tmp/../lib/prog.debug"); +it("observes a slash name without producing directory lookup strings", () => { const slashed = parse( elfDebugLinkFixture({ debuglink: debuglinkSection("dir/prog.debug", 0x12345678, true), diff --git a/src/native/elf/ElfDebugLinkNameBudget.test.ts b/src/native/elf/ElfDebugLinkNameBudget.test.ts index 749cbcb0f4..4eebf6a97f 100644 --- a/src/native/elf/ElfDebugLinkNameBudget.test.ts +++ b/src/native/elf/ElfDebugLinkNameBudget.test.ts @@ -87,17 +87,35 @@ const inputFor = (maxFileBytes: number) => max_file_bytes: maxFileBytes, }); -it("refuses compressed image names above the selected budget before inflating them", () => { - const image = withCompressedNames(elfDebugLinkFixture()); - expect(() => - parseElfDebugLink( - image, - { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, - inputFor(image.length + 1), - ), - ).toThrow(ParseFailureError); - expect(zlib.inflated).toBe(0); -}); +it.each(["direct", "extended"] as const)( + "checks the decoded image-name budget with a %s section count", + (encoding) => { + const compressed = withCompressedNames(elfDebugLinkFixture()); + const image = + encoding === "extended" + ? withExtendedSectionCount(compressed) + : compressed; + const artifact = { + path: "/artifacts/prog", + sha256: "ab".repeat(32), + bytes: image.length, + }; + const requiredBytes = image.length + DECODED_NAME_BYTES; + expect(() => + parseElfDebugLink(image, artifact, inputFor(requiredBytes - 1)), + ).toThrow(ParseFailureError); + expect(zlib.inflated).toBe(0); + if (encoding === "direct") { + const report = parseElfDebugLink( + image, + artifact, + inputFor(requiredBytes), + ); + expect(report.debuglink.status).toBe("present"); + expect(zlib.inflated).toBeGreaterThan(0); + } + }, +); it.each(["unbacked", "wrong type"] as const)( "validates a %s section-name table before charging its declared decoded size", @@ -127,43 +145,51 @@ it.each(["unbacked", "wrong type"] as const)( }, ); -it("leaves compressed candidate names above the selected budget undecoded", () => { - const candidate = withCompressedNames(elfDebugCandidateFixture()); - const image = elfDebugLinkFixture(); - const input = inputFor(image.length + 1); - const report = parseElfDebugLink( - image, - { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, - input, - ); - const verified = verifyElfDebugCandidate( - report, - { - path: "/artifacts/prog.debug", - sha256: "cd".repeat(32), - bytes: candidate.length, - crc32: crc32(candidate), - prefix: candidate, - }, - input, - ); - expect(zlib.inflated).toBe(0); - expect(verified.candidate).toMatchObject({ - debug_info: "unknown", - symtab: "unknown", - }); -}); - -it("still decodes compressed names that fit the selected budget", () => { - const image = withCompressedNames(elfDebugLinkFixture()); - const report = parseElfDebugLink( - image, - { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, - inputFor(image.length + DECODED_NAME_BYTES), - ); - expect(zlib.inflated).toBeGreaterThan(0); - expect(report.debuglink.status).toBe("present"); -}); +it.each(["direct", "extended"] as const)( + "leaves over-budget candidate names undecoded with a %s section count", + (encoding) => { + const compressed = withCompressedNames(elfDebugCandidateFixture()); + const candidate = + encoding === "extended" + ? withExtendedSectionCount(compressed) + : compressed; + const image = elfDebugLinkFixture(); + const input = inputFor(Math.max(image.length, candidate.length)); + const report = parseElfDebugLink( + image, + { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, + input, + ); + const verified = verifyElfDebugCandidate( + report, + { + path: "/artifacts/prog.debug", + sha256: "cd".repeat(32), + bytes: candidate.length, + crc32: crc32(candidate), + prefix: candidate, + }, + input, + ); + expect(zlib.inflated).toBe(0); + expect(verified).toMatchObject({ + candidate: { + bytes: candidate.length, + debug_info: "unknown", + symtab: "unknown", + }, + verification: { + build_id: { + status: "unavailable", + reason: "candidate_build_id_unknown", + }, + }, + }); + expect(verified.limitations).toContain( + ELF_DEBUG_LINK_CANDIDATE_BUDGET_LIMITATION, + ); + }, +); it("keeps the build-id of an image whose names use an unsupported compression above the budget", () => { const image = withCompressedNames(elfDebugLinkFixture(), 0x7fff); @@ -182,7 +208,7 @@ it("keeps the build-id of an image whose names use an unsupported compression ab it("keeps the build-id of a candidate whose names use an unsupported compression above the budget", () => { const candidate = withCompressedNames(elfDebugCandidateFixture(), 0x7fff); const image = elfDebugLinkFixture(); - const input = inputFor(image.length + 1); + const input = inputFor(Math.max(image.length, candidate.length)); const report = parseElfDebugLink( image, { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, @@ -208,45 +234,3 @@ it("keeps the build-id of a candidate whose names use an unsupported compression ELF_DEBUG_LINK_CANDIDATE_BUDGET_LIMITATION, ); }); - -it("refuses compressed image names above the budget when only section zero declares the count", () => { - const image = withExtendedSectionCount( - withCompressedNames(elfDebugLinkFixture()), - ); - expect(() => - parseElfDebugLink( - image, - { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, - inputFor(image.length + 1), - ), - ).toThrow(ParseFailureError); - expect(zlib.inflated).toBe(0); -}); - -it("leaves compressed candidate names undecoded when only section zero declares the count", () => { - const candidate = withExtendedSectionCount( - withCompressedNames(elfDebugCandidateFixture()), - ); - const image = elfDebugLinkFixture(); - const input = inputFor(candidate.length + 1); - const report = parseElfDebugLink( - image, - { path: "/artifacts/prog", sha256: "ab".repeat(32), bytes: image.length }, - input, - ); - const verified = verifyElfDebugCandidate( - report, - { - path: "/artifacts/prog.debug", - sha256: "cd".repeat(32), - bytes: candidate.length, - crc32: crc32(candidate), - prefix: candidate, - }, - input, - ); - expect(zlib.inflated).toBe(0); - expect(verified.limitations).toContain( - ELF_DEBUG_LINK_CANDIDATE_BUDGET_LIMITATION, - ); -}); diff --git a/src/native/elf/ElfDebugLinkProvider.test.ts b/src/native/elf/ElfDebugLinkProvider.test.ts index c4ebeda7c5..5ea93b6937 100644 --- a/src/native/elf/ElfDebugLinkProvider.test.ts +++ b/src/native/elf/ElfDebugLinkProvider.test.ts @@ -2,8 +2,6 @@ import { primaryAnalysisError } from "../../domain/analysisErrorBase.js"; import { expect, it, vi } from "vitest"; import { ArtifactReaderFailure } from "../../resources/ArtifactReader.js"; -import { ArtifactFileCancelled } from "../../resources/ArtifactFileOperation.js"; -import { completedStableArtifactObservation } from "../../resources/StableArtifactObservation.js"; import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js"; import { ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, @@ -139,50 +137,6 @@ it("retains the decoded image report when the candidate read is cancelled", asyn ); }); -const completedCandidate = { - sha256: "cd".repeat(32), - size: 8192, - prefix: image.subarray(0, 64), -}; - -it("keeps a completed candidate stream's identity when cancellation arrives during close", async () => { - const result = await inspect( - new ArtifactFileCancelled({ - reason: new Error("stop"), - outcome: { kind: "completed", value: completedCandidate }, - }), - ); - expect(result.ok).toBe(false); - if (result.ok) return; - const report = retainedReport(result.error); - expect(report?.artifact.sha256).toBe("ab".repeat(32)); - expect(report?.candidate).toMatchObject({ - path: "/artifacts/prog.debug", - sha256: "cd".repeat(32), - bytes: 8192, - }); - expect(report?.limitations).not.toContain( - ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, - ); -}); - -it("recovers a completed stream's whole-file size, not its prefix length", () => { - expect( - completedStableArtifactObservation( - new ArtifactFileCancelled({ - reason: new Error("stop"), - outcome: { kind: "completed", value: completedCandidate }, - }), - "/artifacts/prog.debug", - ), - ).toEqual({ - kind: "file-snapshot-hash", - path: "/artifacts/prog.debug", - sha256: "cd".repeat(32), - bytes: 8192, - }); -}); - it("retains the completed image snapshot when ELF decoding fails", async () => { const garbage = Buffer.alloc(128, 0x41); imageBytes.current = garbage; diff --git a/src/native/elf/ElfDebugLinkProvider.ts b/src/native/elf/ElfDebugLinkProvider.ts index b600fc9fde..03b4b4ffbf 100644 --- a/src/native/elf/ElfDebugLinkProvider.ts +++ b/src/native/elf/ElfDebugLinkProvider.ts @@ -18,6 +18,7 @@ import { type StableArtifactSnapshot, type StableArtifactStream, artifactFilePrimaryFacts, + artifactFileCompletion, type ArtifactFilePrimaryFacts, ArtifactResourceScope, } from "../../resources/index.js"; @@ -27,6 +28,7 @@ import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { ELF_DEBUG_LINK_CANDIDATE_INCOMPLETE_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, MAX_ELF_DEBUG_CANDIDATE_BYTES, MAX_INSPECT_ELF_DEBUG_LINK_ENTRIES, MAX_INSPECT_ELF_DEBUG_LINK_FILE_BYTES, @@ -199,7 +201,7 @@ const unverifiedCandidateObservation = ( }, limitations: [ ...report.limitations, - "The candidate read completed. Its ELF comparison did not complete.", + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, ], }); @@ -226,7 +228,9 @@ const candidatePhaseObservation = ( ], }; const file = candidateFile(phase, completed, crc32); - // A stream whose close failed can still supply a complete comparison. + if (artifactFileCompletion(cause)?.cancellation !== undefined) + return unverifiedCandidateObservation(phase.report, file); + // A close failure alone can retain a complete comparison. try { return verifyElfDebugCandidate(phase.report, file, input); } catch { diff --git a/tests/acceptance/elfDebugLinkCli.test.ts b/tests/acceptance/elfDebugLinkCli.test.ts index 57ba6179bd..fcc29c522d 100644 --- a/tests/acceptance/elfDebugLinkCli.test.ts +++ b/tests/acceptance/elfDebugLinkCli.test.ts @@ -24,7 +24,7 @@ const debugLinkContract = contractNamed( ); cliTest( - "verifies a matching debug file from absolute and relative paths", + "verifies a debug file while preserving both relative caller paths", async ({ cli }) => { const root = await createTestTempDirectory("rea-elf-debug-link-cli-"); const candidate = elfDebugCandidateFixture(); @@ -35,17 +35,23 @@ cliTest( const candidatePath = join(root, "prog.debug"); await writeFile(imagePath, image); await writeFile(candidatePath, candidate); - const absolute = await cli.run({ + const selected = await cli.run({ arguments: [ "inspect-elf-debug-link", - imagePath, + "prog", "--candidate-path", - candidatePath, + "prog.debug", "--json", ], + cwd: root, + }); + expect(selected.exitCode, selected.stderr).toBe(0); + const evidence = debugLinkContract.outputSchema.parse(selected.json); + expect(evidence.subject.local_path).toBe(imagePath); + expect(evidence.caller_input_path).toBe("prog"); + expect(evidence.caller_input_paths).toEqual({ + candidate_path: "prog.debug", }); - expect(absolute.exitCode, absolute.stderr).toBe(0); - const evidence = debugLinkContract.outputSchema.parse(absolute.json); expect(evidence.parameters).toEqual({ path: imagePath, candidate_path: candidatePath, @@ -94,31 +100,6 @@ cliTest( ], ].map(([kind, path]) => ({ kind, path, trust: "observed-untrusted" })), ); - const relative = await cli.run({ - arguments: [ - "inspect-elf-debug-link", - "prog", - "--candidate-path", - "prog.debug", - "--json", - ], - cwd: root, - }); - expect(relative.exitCode, relative.stderr).toBe(0); - const relativeEvidence = debugLinkContract.outputSchema.parse( - relative.json, - ); - expect(relativeEvidence.normalized_result.verification?.status).toBe( - "matches", - ); - expect(relativeEvidence.subject?.local_path).toBe(imagePath); - expect(relativeEvidence.caller_input_path).toBe("prog"); - expect(relativeEvidence.caller_input_paths).toEqual({ - candidate_path: "prog.debug", - }); - expect(relativeEvidence.normalized_result.candidate?.path).toBe( - candidatePath, - ); }, ); @@ -149,9 +130,16 @@ cliTest( }); expect(result.exitCode, result.stderr).toBe(0); const evidence = debugLinkContract.outputSchema.parse(result.json); - expect(evidence.normalized_result.verification?.status).toBe( - "does_not_match", - ); + expect(evidence.normalized_result.verification).toMatchObject({ + status: "does_not_match", + reason: "crc32_and_build_id_mismatch", + crc32: { status: "mismatch", expected_hex: "11111111" }, + build_id: { + status: "mismatch", + binary_hex: FIXTURE_BUILD_ID_HEX, + candidate_hex: "dd".repeat(20), + }, + }); }, ); diff --git a/tests/boundary/filesystem/elfDebugLink.test.ts b/tests/boundary/filesystem/elfDebugLink.test.ts index 4a74b16080..6041704297 100644 --- a/tests/boundary/filesystem/elfDebugLink.test.ts +++ b/tests/boundary/filesystem/elfDebugLink.test.ts @@ -5,9 +5,15 @@ import { join } from "node:path"; import { scheduler } from "node:timers/promises"; import { describe, expect, it, vi } from "vitest"; import { AnalysisResourceConstraintError } from "../../../src/domain/analysisErrorCore.js"; +import { + primaryAnalysisError, + resolvedAnalysisError, +} from "../../../src/domain/analysisErrorBase.js"; import { createElfDebugLinkService } from "../../../src/composition/binaryDiagnostics.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; import { ELF_DEBUG_LINK_CANDIDATE_BUDGET_LIMITATION, + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, ELF_DEBUG_LINK_CANDIDATE_PREFIX_LIMITATION, ELF_DEBUG_LINK_CANDIDATE_UNREADABLE_LIMITATION, ELF_DEBUG_LINK_CANNOT_VERIFY_LIMITATION, @@ -150,23 +156,15 @@ describe("ELF debug-link stable filesystem boundary", () => { reason: "candidate_unreadable", }, }); - const linked = await service.inspect({ path, candidate_path: alias }); - const relative = await service.inspect({ - path, - candidate_path: "prog.debug", - }); - if (linked.ok) - throw new Error("Expected a symlinked candidate rejection"); - expect(linked.error).toMatchObject({ - _tag: "AnalysisInputError", - issues: [{ path: ["candidate_path"], reason: "invalid_format" }], - }); - if (relative.ok) - throw new Error("Expected a relative candidate rejection"); - expect(relative.error).toMatchObject({ - _tag: "AnalysisInputError", - issues: [{ path: ["candidate_path"], reason: "invalid_format" }], - }); + for (const candidate_path of [alias, "prog.debug"]) { + const refusal = await service.inspect({ path, candidate_path }); + if (refusal.ok) + throw new Error(`Expected refusal for ${candidate_path}`); + expect(refusal.error).toMatchObject({ + _tag: "AnalysisInputError", + issues: [{ path: ["candidate_path"], reason: "invalid_format" }], + }); + } } finally { await service.close(); } @@ -234,53 +232,118 @@ it("does not open a conventional lookup path when no candidate is selected", asy } }); -describe("ELF debug-link streamed candidate boundary", () => { - it("retains streamed candidate identity when cancellation stops ELF comparison", async () => { +it.each(["comparison", "descriptor close", "failed descriptor close"] as const)( + "retains streamed candidate Evidence when cancelled during %s", + async (stage) => { const root = await createTestTempDirectory( "rea-elf-debug-link-cancel-candidate-", ); const path = join(root, "prog"); const candidatePath = join(root, "prog.debug"); - const candidate = elfFrameAllowanceFixture(); - await writeFile(path, elfDebugLinkFixture()); + const candidateFixture = elfFrameAllowanceFixture(); + const image = elfDebugLinkFixture(); + const closing = stage !== "comparison"; + const closeFailed = stage === "failed descriptor close"; + const candidate = closing + ? Buffer.concat([candidateFixture, Buffer.alloc(160_000)]) + : candidateFixture; + const parameters = { + path, + candidate_path: candidatePath, + ...(closing ? { max_file_bytes: image.length } : {}), + }; + await writeFile(path, image); await writeFile(candidatePath, candidate); const service = createElfDebugLinkService(); const controller = new AbortController(); - const reason = new Error("stop while decoding candidate names"); + const reason = new Error(`stop during the candidate ${stage}`); const yieldToEventLoop = scheduler.yield.bind(scheduler); - const pause = vi - .spyOn(scheduler, "yield") - .mockImplementationOnce(async () => { + const pause = vi.spyOn(scheduler, "yield"); + const openFile = vi.mocked(open); + if (stage === "comparison") { + pause.mockImplementationOnce(async () => { await yieldToEventLoop(); controller.abort(reason); }); + } else { + const real = + await vi.importActual( + "node:fs/promises", + ); + openFile.mockImplementation(async (...args) => { + const handle = await real.open(...args); + if (args[0] === candidatePath) { + const close = handle.close.bind(handle); + vi.spyOn(handle, "close").mockImplementationOnce(async () => { + if (!closeFailed) await close(); + controller.abort(reason); + if (closeFailed) + throw new Error("candidate descriptor not released"); + }); + } + return handle; + }); + } try { - const result = await service.inspect( - { path, candidate_path: candidatePath }, - { signal: controller.signal }, - ); + const result = await service.inspect(parameters, { + signal: controller.signal, + }); if (result.ok) throw new Error("Expected candidate comparison cancellation"); - expect(result.error).toMatchObject({ - _tag: "AnalysisCancelledError", - cause: reason, - partialObservation: { - build_id: { status: "observed", hex: FIXTURE_BUILD_ID_HEX }, - candidate: { - path: candidatePath, - sha256: createHash("sha256").update(candidate).digest("hex"), - bytes: candidate.length, - debug_info: "unknown", - symtab: "unknown", - }, - verification: null, + const primary = primaryAnalysisError(result.error); + expect(primary._tag).toBe("AnalysisCancelledError"); + expect(primary.cause).toBe(reason); + expect(result.error.cleanupIncomplete).toBe(closeFailed); + expect(result.error.cleanupResources).toEqual( + closeFailed ? [candidatePath] : [], + ); + const evidence = parseEvidence(result.error.partialObservation); + expect(evidence.parameters).toEqual(parameters); + expect(evidence.subject).toMatchObject({ + identity: { + kind: "file", + format: "elf", + sha256: createHash("sha256").update(image).digest("hex"), }, + local_path: path, }); + expect(evidence.locations.slice(0, 2)).toEqual([ + { kind: "artifact-path", path }, + { kind: "artifact-path", path: candidatePath }, + ]); + const report = elfDebugLinkSchema.parse(evidence.normalized_result); + expect(report.build_id).toMatchObject({ + status: "observed", + hex: FIXTURE_BUILD_ID_HEX, + }); + expect(report.candidate).toEqual({ + path: candidatePath, + sha256: createHash("sha256").update(candidate).digest("hex"), + bytes: candidate.length, + format: null, + byte_order: null, + debug_info: "unknown", + symtab: "unknown", + }); + expect(report.verification).toBeNull(); + expect(report.limitations).toContain( + ELF_DEBUG_LINK_CANDIDATE_COMPARISON_INCOMPLETE_LIMITATION, + ); + if (closeFailed) { + await service.close(); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.cleanupResources).toEqual([]); + expect(resolvedAnalysisError(result.error)).toBe(primary); + expect(parseEvidence(primary.partialObservation)).toEqual(evidence); + } } finally { pause.mockRestore(); + openFile.mockReset(); await service.close(); } - }); + }, +); +describe("ELF debug-link streamed candidate boundary", () => { it("matches the known CRC32 of a non-ELF candidate", async () => { const root = await createTestTempDirectory("rea-elf-debug-link-crc32-"); const path = join(root, "prog"); diff --git a/tests/boundary/mcp/elfDebugLinkMcp.test.ts b/tests/boundary/mcp/elfDebugLinkMcp.test.ts index 7a7a9845a3..99f736b284 100644 --- a/tests/boundary/mcp/elfDebugLinkMcp.test.ts +++ b/tests/boundary/mcp/elfDebugLinkMcp.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { expect } from "vitest"; import { contractNamed } from "../../../src/cli/contractCliDescription.js"; import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../../../src/contracts/native/binaryDiagnosticsToolContracts.js"; +import { DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES } from "../../../src/domain/native/elfDebugLink.js"; import { createServer } from "../../../src/server/createServer.js"; import { debuglinkSection, @@ -77,13 +78,19 @@ mcpTest( expect(evidence.parameters).toEqual({ path }); const explicit = await client.callTool({ name: "inspect_elf_debug_link", - arguments: { path, max_entries: 32 }, + arguments: { + path, + max_entries: DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES, + }, }); expect(explicit.isError).not.toBe(true); const selected = debugLinkContract.outputSchema.parse( explicit.structuredContent, ); - expect(selected.parameters).toEqual({ path, max_entries: 32 }); + expect(selected.parameters).toEqual({ + path, + max_entries: DEFAULT_INSPECT_ELF_DEBUG_LINK_ENTRIES, + }); expect(selected.normalized_result).toEqual(evidence.normalized_result); expect(selected.evidence_id).not.toBe(evidence.evidence_id); } finally { @@ -116,11 +123,13 @@ mcpTest("verifies one caller-selected debug file", async ({ mcp }) => { ); expect(evidence.normalized_result.verification?.status).toBe("matches"); expect(evidence.normalized_result.candidate?.debug_info).toBe("present"); - const meta = "_meta" in response ? response._meta : undefined; - if (meta !== undefined) - expect(meta).toMatchObject({ - provenance: { untrusted_content: true, source: "analysis_target" }, - }); + expect(evidence.locations).toContainEqual({ + kind: "artifact-path", + path: candidatePath, + }); + expect("_meta" in response ? response._meta : undefined).toMatchObject({ + provenance: { untrusted_content: true, source: "analysis_target" }, + }); } finally { await session.close(); } diff --git a/tests/support/providerLifecycleCoverage.ts b/tests/support/providerLifecycleCoverage.ts index 033b2db98d..69ee855236 100644 --- a/tests/support/providerLifecycleCoverage.ts +++ b/tests/support/providerLifecycleCoverage.ts @@ -1298,7 +1298,7 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< covered( test( "tests/acceptance/elfDebugLinkCli.test.ts", - "verifies a matching debug file from absolute and relative paths", + "verifies a debug file while preserving both relative caller paths", ), ), covered( @@ -1307,8 +1307,8 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< "returns typed resource and cancellation failures", ), test( - "src/native/elf/ElfDebugLinkProvider.test.ts", - "keeps a completed candidate stream's identity when cancellation arrives during close", + "tests/boundary/filesystem/elfDebugLink.test.ts", + "retains streamed candidate Evidence when cancelled during %s", ), ), ),