diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index f3eb1cf55c..160234daf1 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -21,7 +21,6 @@ import { abortIfNeeded, DirectoryArtifactEntryAccessDenied, DirectoryArtifactReader, - DirectoryArtifactTraversalLimit, } from "../../resources/index.js"; import { ArtifactTraversalObservation, @@ -45,6 +44,7 @@ import { type ArtifactParentResolution, type MutableOccurrence, } from "./ArtifactGraphConstruction.js"; +import { invariantViolation } from "../../domain/internalInvariant.js"; import type { ArtifactIntegrityPolicyName } from "../../domain/artifactIntegrityPolicy.js"; import { hashReadable } from "../ArtifactHash.js"; @@ -119,6 +119,14 @@ export const scanReader = async ( traversal: { status: "complete", limitations: [] }, rootContradiction: undefined, }; + const maximumEntries = acquisitionLimits?.maximumEntries; + if ( + maximumEntries !== undefined && + (!Number.isSafeInteger(maximumEntries) || maximumEntries < 0) + ) + throw invariantViolation( + "Artifact inventory maximumEntries must be a nonnegative safe integer", + ); const context: ScanContext = { acquisitionLimits, entriesExamined: 0, @@ -196,6 +204,13 @@ class InventoryAcquisitionLimit extends ArtifactReaderFailure { } } +const admitExaminedEntry = (context: ScanContext): void => { + if (context.acquisitionLimits === undefined) return; + if (context.entriesExamined >= context.acquisitionLimits.maximumEntries) + throw new InventoryAcquisitionLimit(); + context.entriesExamined += 1; +}; + const inventoryEntries = ( context: ScanContext, reader: ArtifactReader, @@ -206,8 +221,7 @@ const inventoryEntries = ( ...(reader instanceof DirectoryArtifactReader && context.acquisitionLimits !== undefined ? { - maximumEntries: - context.acquisitionLimits.maximumEntries - context.entriesExamined, + admitExaminedEntry: () => admitExaminedEntry(context), } : {}), onOmission: (omission) => @@ -247,12 +261,8 @@ const visitArtifactEntries = async ( continue; } const entry = next.value; - if ( - context.acquisitionLimits !== undefined && - context.entriesExamined >= context.acquisitionLimits.maximumEntries - ) - throw new InventoryAcquisitionLimit(); - context.entriesExamined += 1; + if (!(frame.reader instanceof DirectoryArtifactReader)) + admitExaminedEntry(context); const logicalPath = normalizeArtifactPath( frame.prefix.length === 0 ? entry.path @@ -362,10 +372,7 @@ const visitArtifactEntries = async ( } } } catch (cause: unknown) { - if ( - cause instanceof InventoryAcquisitionLimit || - cause instanceof DirectoryArtifactTraversalLimit - ) + if (cause instanceof InventoryAcquisitionLimit) context.traversal.record({ status: "unknown", limitations: [cause.message], diff --git a/src/resources/ArtifactPaths.test.ts b/src/resources/ArtifactPaths.test.ts index 8e0b313e8e..48143b7455 100644 --- a/src/resources/ArtifactPaths.test.ts +++ b/src/resources/ArtifactPaths.test.ts @@ -9,34 +9,34 @@ import { normalizeArtifactPath, } from "./ArtifactPaths.js"; -it.each(["drive", "escaped", "normalization", "prefix", "collision"])( - "bounds path failure diagnostics at the owning boundary: %s", - (kind) => { - const name = "x".repeat(1024 * 1024); - const registry = new ArtifactPathRegistry(); - const fail = () => { - if (kind === "drive") normalizeArtifactPath("C:/" + name); - else if (kind === "escaped") - normalizeArtifactPath("\0".repeat(name.length)); - else if (kind === "normalization") - normalizeArtifactPath(name + "/../child"); - else { - registry.add(name, "file"); - registry.add(kind === "prefix" ? name + "/child" : name, "directory"); - } - }; - const failure = (() => { - try { - fail(); - } catch (cause: unknown) { - return cause; - } - return undefined; - })(); +const longName = "x".repeat(2_048); + +const obstructedDestination = (path: string) => { + const registry = new ArtifactPathRegistry(); + registry.add(longName, "file"); + registry.add(path, "directory"); +}; + +it.each([ + ["absolute or unsafe", () => normalizeArtifactPath(`C:/${longName}`)], + [ + "absolute or unsafe", + () => normalizeArtifactPath("\0".repeat(longName.length)), + ], + ["not normalized", () => normalizeArtifactPath(`${longName}/../child`)], + ["prefix conflict", () => obstructedDestination(`${longName}/child`)], + ["path collision", () => obstructedDestination(longName)], +] as const)("bounds the %s path diagnostic", (diagnostic, fail) => { + expect.assertions(3); + try { + fail(); + } catch (failure: unknown) { expect(failure).toMatchObject({ reason: "path" }); - expect((failure as Error).message.length).toBeLessThan(1024); - }, -); + if (!(failure instanceof Error)) throw failure; + expect(failure.message).toContain(diagnostic); + expect(failure.message.length).toBeLessThan(1_024); + } +}); it.each(["a:b", "C:cache/file.txt", "a:"])( "preserves a literal POSIX colon name %s", @@ -70,9 +70,6 @@ const expectCollision = ( expect(limitations).toHaveLength(1); const warning = limitations?.[0] ?? ""; for (const fact of facts) expect(warning).toContain(fact); - expect(warning).toMatch(/collid.*English.*case folding/iu); - expect(warning).toMatch(/case.insensitive destination.*cannot store both/iu); - expect(warning).toMatch(/not a filesystem observation/iu); }; describe("English Unicode case collisions", () => { @@ -85,47 +82,42 @@ describe("English Unicode case collisions", () => { ); }); - it("names the other spelling of a colliding file", () => { - const { limitation, byPath } = annotate([".", "Main.js", "main.js", "x"]); - expect(limitation).toBe(ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION); - expectCollision(byPath.get("Main.js"), "Main.js", "main.js"); - expectCollision(byPath.get("main.js"), "main.js", "Main.js"); - expect(byPath.get("x")).toEqual([]); - }); - - it("records a directory collision once at the diverging segment", () => { - const { byPath } = annotate([ + it("reports colliding spellings at the diverging segment only", () => { + const { limitation, byPath } = annotate([ + "Main.js", + "main.js", + "a.TXT", + "A.txt", + "a.txt", "res/Foo", "res/Foo/a.txt", "res/foo", "res/foo/b.txt", + "unrelated", ]); - expectCollision(byPath.get("res/Foo"), "res/Foo", "res/foo"); + expect(limitation).toBe(ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION); + expectCollision(byPath.get("Main.js"), "Main.js collides", "with main.js;"); + expectCollision(byPath.get("main.js"), "main.js collides", "with Main.js;"); + expectCollision(byPath.get("a.txt"), "with A.txt and 1 other spelling;"); + expectCollision(byPath.get("res/Foo"), "res/Foo collides", "with res/foo;"); expectCollision( byPath.get("res/foo/b.txt"), - "res/foo/b.txt", - "under res/foo", - "res/Foo", + "res/foo/b.txt is under res/foo", + "with res/Foo;", ); - }); - - it("counts further spellings, each of which is its own occurrence", () => { - const { byPath } = annotate(["A.txt", "a.txt", "a.TXT"]); - expectCollision(byPath.get("a.txt"), "a.txt", "A.txt", "1 other spelling"); + expect(byPath.get("unrelated")).toEqual([]); + for (const path of ["Main.js", "res/foo/b.txt"]) + expect(byPath.get(path)?.[0]).toMatch( + /English.*case folding.*case-insensitive destination cannot store both.*not a filesystem observation/iu, + ); }); it("retains every spelling in a high-cardinality folded sibling group", () => { const count = 8_192; - const variants = caseVariants("abcdefghijklm", count); - const { limitation, byPath } = annotate(variants); - const ordered = [...variants].sort(); - const first = ordered[0]; - const second = ordered[1]; - const original = variants[0]; - if (first === undefined || second === undefined || original === undefined) { - throw new Error("Expected at least two case variants"); - } - expect(limitation).toBe(ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION); + const original = "abcdefghijklm"; + const { byPath } = annotate(caseVariants(original, count)); + const first = "ABCDEFGHIJKLM"; + const second = "ABCDEFGHIJKLm"; expect(byPath.size).toBe(count); expectCollision( byPath.get(first), @@ -148,11 +140,13 @@ describe("English Unicode case collisions", () => { `foo/b${String(index)}.txt`, ]).flat(); const { byPath } = annotate(paths); - for (const path of paths) { - const limitations = byPath.get(path) ?? []; - expect(limitations).toHaveLength(1); - expect(limitations[0]?.length).toBeLessThan(300); - } + const incorrect = paths.find((path) => { + const limitations = byPath.get(path); + return ( + limitations?.length !== 1 || (limitations[0]?.length ?? 300) >= 300 + ); + }); + expect(incorrect).toBeUndefined(); }); it("walks names with more components than the call stack holds", () => { @@ -163,14 +157,16 @@ describe("English Unicode case collisions", () => { }); }); -const caseVariants = (lowercase: string, count: number): string[] => - Array.from({ length: count }, (_, mask) => - [...lowercase] +const caseVariants = (lowercase: string, count: number): string[] => { + const characters = [...lowercase]; + return Array.from({ length: count }, (_, mask) => + characters .map((character, index) => (mask & (1 << index)) === 0 ? character : character.toUpperCase(), ) .join(""), ); +}; it("retains both source spellings and the native failure in a destination collision", () => { const cause = Object.assign(new Error("exclusive create refused"), { diff --git a/src/resources/DirectoryArtifactReader.ts b/src/resources/DirectoryArtifactReader.ts index f365f4c2c1..8f71eeead3 100644 --- a/src/resources/DirectoryArtifactReader.ts +++ b/src/resources/DirectoryArtifactReader.ts @@ -51,6 +51,8 @@ interface DirectoryTraversalOptions extends ArtifactTraversalOptions { readonly descendInto?: (path: string) => boolean; /** Bound examined children, including omitted special entries. */ readonly maximumEntries?: number; + /** Charge an examined child to a caller's shared allowance before inspection. */ + readonly admitExaminedEntry?: () => void; } /** Exhausted an examined-entry budget; unrelated I/O and cleanup failures stay distinct. */ @@ -125,6 +127,7 @@ export class DirectoryArtifactReader implements ArtifactReader { const examine = () => { if (maximum !== undefined && examined >= maximum) throw new DirectoryArtifactTraversalLimit(examined, maximum); + options?.admitExaminedEntry?.(); examined += 1; }; const pending = [root]; diff --git a/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts b/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts index 7d2abdeab7..84192cec6e 100644 --- a/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts +++ b/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts @@ -68,6 +68,79 @@ it.skipIf(process.platform === "win32")( }, ); +it("shares the examined-entry allowance across directory and embedded archive traversal", async () => { + const root = await createTestTempDirectory("rea-inventory-shared-budget-"); + const archive = asarHeaderBytes( + '{"files":{"main.js":{"size":0,"offset":"0"}}}', + ); + await writeFile(join(root, "app.asar"), archive); + await writeFile(join(root, "sibling.txt"), "ordinary input"); + const options = { + acquisitionLimits: { maximumEntries: 2, maximumBytes: 2_048 }, + }; + + await expect( + inventoryArtifact(root, { + acquisitionLimits: { ...options.acquisitionLimits, maximumEntries: NaN }, + }), + ).rejects.toMatchObject({ _tag: "InternalInvariantError" }); + const bounded = await inventoryArtifact(root, options); + expect(bounded.coverage).toEqual({ + scope: "container-entries", + status: "unknown", + }); + expect(bounded.occurrences).toHaveLength(3); // The root does not consume a member slot. + expect(bounded.limitations).toEqual( + expect.arrayContaining([ + expect.stringContaining("acquisition allowance exhausted"), + ]), + ); + + await rm(join(root, "sibling.txt")); + const exact = await inventoryArtifact(root, options); + expect(exact.coverage).toEqual({ + scope: "container-entries", + status: "complete", + }); + expect( + exact.occurrences.map(({ logical_path }) => logical_path).sort(), + ).toEqual([".", "app.asar", "app.asar/main.js"]); +}); + +it.skipIf(process.platform === "win32")( + "charges an omitted directory entry to the inventory allowance shared with embedded members", + async () => { + const root = await createTestTempDirectory("rea-inventory-omitted-budget-"); + await writeFile( + join(root, "app.asar"), + asarHeaderBytes('{"files":{"main.js":{"size":0,"offset":"0"}}}'), + ); + await promisify(execFile)("mkfifo", [join(root, "pipe")]); + + const bounded = await inventoryArtifact(root, { + acquisitionLimits: { maximumEntries: 2, maximumBytes: 2_048 }, + }); + expect(bounded.coverage).toEqual({ + scope: "container-entries", + status: "unknown", + }); + const sawMember = bounded.occurrences.some( + ({ logical_path }) => logical_path === "app.asar/main.js", + ); + const sawPipe = bounded.limitations.some((message) => + message.includes('omitted fifo at "pipe"'), + ); + // Native listings can put either child first. Only one can use the budget + // slot that remains after admitting the archive itself. + expect(Number(sawMember) + Number(sawPipe)).toBe(1); + expect(bounded.limitations).toEqual( + expect.arrayContaining([ + expect.stringContaining("acquisition allowance exhausted"), + ]), + ); + }, +); + it("rejects a root path replaced between its initial stat and open", async () => { const root = await createTestTempDirectory("rea-artifact-root-replaced-"); const path = join(root, "input.bin"); diff --git a/tests/boundary/filesystem/wideDirectoryTraversal.test.ts b/tests/boundary/filesystem/wideDirectoryTraversal.test.ts index 306b01574e..81f3c2c6d7 100644 --- a/tests/boundary/filesystem/wideDirectoryTraversal.test.ts +++ b/tests/boundary/filesystem/wideDirectoryTraversal.test.ts @@ -1,4 +1,4 @@ -import { mkdir } from "node:fs/promises"; +import { mkdir, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; @@ -24,7 +24,7 @@ const missingChildren = (paths: Iterable): string[] => { const traverse = async ( root: string, maximumEntries: number, - stopAfter?: { readonly entries: number; readonly reason: Error }, + onEntry?: (path: string, controller: AbortController) => void | Promise, ): Promise<{ readonly paths: string[]; readonly failure: unknown }> => { const reader = new DirectoryArtifactReader(root); const controller = new AbortController(); @@ -34,8 +34,8 @@ const traverse = async ( maximumEntries, })) { paths.push(entry.path); - if (paths.length === stopAfter?.entries) - controller.abort(stopAfter.reason); + const observation = onEntry?.(entry.path, controller); + if (observation !== undefined) await observation; } return { paths, failure: undefined }; } catch (failure: unknown) { @@ -68,19 +68,31 @@ describe("directory traversal of a parent wider than call arguments allow", () = }); it("schedules the artifact reader's children within the selected entry budget", async () => { - // Cancel once the parent listing is complete. The next cancellation - // checkpoint follows scheduling its children for descent. - const reason = new Error("Stop after the wide parent listing"); - const listed = await traverse(root, CHILD_DIRECTORIES, { - entries: CHILD_DIRECTORIES, - reason, + const reason = new Error("Stop after visiting a scheduled child"); + let marker: string | undefined; + const listed = await traverse( + root, + CHILD_DIRECTORIES + 1, + (path, controller) => { + if (marker === undefined) { + // Populate the first observed child so native directory order does not + // require walking every scheduled directory to witness descent. + marker = `${path}/probe.txt`; + return writeFile(join(root, marker), "scheduled child"); + } + if (path === marker) controller.abort(reason); + return undefined; + }, + ).finally(async () => { + if (marker !== undefined) await rm(join(root, marker), { force: true }); }); expect(listed.failure).toBeInstanceOf(ArtifactReaderFailure); expect(listed.failure).toMatchObject({ reason: "cancelled", cause: reason, }); - expect(listed.paths).toHaveLength(CHILD_DIRECTORIES); + expect(listed.paths).toHaveLength(CHILD_DIRECTORIES + 1); + expect(listed.paths.at(-1)).toBe(marker); expect(missingChildren(listed.paths)).toEqual([]); // A smaller selected allowance stays a typed refusal at its actual bound.