fix(artifacts): preserve ZIP identities and partial managed metadata
Reject malformed UTF-8 ZIP filenames at the decoding boundary while retaining CP437, Unicode Path overrides and leading U+FEFF. Preserve valid CustomAttribute parent and value facts when constructor identity is invalid, with an explicit partial-coverage issue. Validated ZIP integrity and filesystem-provider workflows, managed producer cases, temporary-file hygiene, package and static checks. Removed the superseded producer-only invalid-constructor regression.
This commit is contained in:
@@ -21,6 +21,11 @@ import {
|
||||
type StableRegularFileDescriptor,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
|
||||
const ZIP_UTF8_DECODER = new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
ignoreBOM: true,
|
||||
});
|
||||
|
||||
class NodeFileReader extends Reader<string> {
|
||||
#handle: FileHandle | undefined;
|
||||
#owner: OwnedFileHandle | undefined;
|
||||
@@ -148,7 +153,9 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
let index = 0;
|
||||
for await (const entry of this.#reader.getEntriesGenerator()) {
|
||||
for await (const entry of this.#reader.getEntriesGenerator({
|
||||
decodeText: decodeZipEntryText,
|
||||
})) {
|
||||
abortIfNeeded(signal);
|
||||
// ZIP member identity is its directory occurrence, not its filename.
|
||||
// Logical path uniqueness belongs to the artifact inventory boundary.
|
||||
@@ -207,7 +214,7 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
const projectZipEntry = (entry: Entry, index: number): ArtifactEntry => {
|
||||
const symlink = isSymlink(entry);
|
||||
return {
|
||||
path: entry.filename,
|
||||
path: zipEntryPath(entry),
|
||||
kind: entry.directory ? "directory" : symlink ? "symlink" : "file",
|
||||
declaredSize: entry.directory ? null : entry.uncompressedSize,
|
||||
compressedSize: entry.directory ? null : entry.compressedSize,
|
||||
@@ -221,6 +228,34 @@ const projectZipEntry = (entry: Entry, index: number): ArtifactEntry => {
|
||||
};
|
||||
};
|
||||
|
||||
const decodeZipEntryText = (
|
||||
bytes: Uint8Array,
|
||||
encoding: string,
|
||||
type: "filename" | "comment",
|
||||
): string | undefined => {
|
||||
if (type !== "filename" || encoding !== "utf-8") return undefined;
|
||||
return decodeStrictZipUtf8(bytes, "ZIP filename is not valid UTF-8");
|
||||
};
|
||||
|
||||
const zipEntryPath = (entry: Entry): string => {
|
||||
const field = entry.extraFieldUnicodePath;
|
||||
if (field?.valid !== true) return entry.filename;
|
||||
return decodeStrictZipUtf8(
|
||||
field.data.subarray(5),
|
||||
"ZIP Unicode Path extra field is not valid UTF-8",
|
||||
);
|
||||
};
|
||||
|
||||
const decodeStrictZipUtf8 = (bytes: Uint8Array, message: string): string => {
|
||||
try {
|
||||
// Keep the adapter's path semantics aligned with zip.js's default decoder:
|
||||
// a leading U+FEFF is part of a member name, not a transport signature.
|
||||
return ZIP_UTF8_DECODER.decode(bytes);
|
||||
} catch (cause: unknown) {
|
||||
throw new ArtifactReaderFailure("format", message, { cause });
|
||||
}
|
||||
};
|
||||
|
||||
const extractStream = (entry: FileEntry, signal?: AbortSignal): Readable => {
|
||||
const output = new PassThrough();
|
||||
const controller = new AbortController();
|
||||
|
||||
@@ -66,6 +66,7 @@ describe("managed artifact failure classification", () => {
|
||||
"System.Runtime",
|
||||
"System.Runtime",
|
||||
]);
|
||||
expect(artifact.attributes).toEqual([]);
|
||||
expect(artifact.coverage.issues.map(({ code }) => code)).toEqual(
|
||||
issueCodes,
|
||||
);
|
||||
|
||||
@@ -177,36 +177,29 @@ describe("managed artifact coded indexes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an invalid CustomAttribute constructor coded index", () => {
|
||||
const bytes = buildManagedPeFixture({ customAttributeTypeRaw: 19 });
|
||||
const result = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
);
|
||||
|
||||
expect(result.attributes).toEqual([]);
|
||||
expect(result.coverage).toMatchObject({
|
||||
state: "partial",
|
||||
issues: [
|
||||
expect.objectContaining({
|
||||
code: "invalid-row",
|
||||
scope: "metadata.CustomAttribute:0x0c000001",
|
||||
detail: expect.stringContaining(
|
||||
"coded index 0x13 is invalid: coded index selects row 2 in table 10, which has 1 rows",
|
||||
),
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports null for the required CustomAttribute constructor coded index", () => {
|
||||
const bytes = buildManagedPeFixture({ customAttributeTypeRaw: 0 });
|
||||
const result = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
managedPeFixtureTarget(bytes),
|
||||
);
|
||||
const text = Buffer.from(".NETCoreApp,Version=v8.0", "utf8");
|
||||
const attributeValue = Buffer.concat([
|
||||
Buffer.from([1, 0, text.length]),
|
||||
text,
|
||||
Buffer.alloc(2),
|
||||
]);
|
||||
|
||||
expect(result.attributes).toEqual([]);
|
||||
expect(result.attributes).toMatchObject([
|
||||
{
|
||||
parent_token: "0x20000001",
|
||||
constructor_token: null,
|
||||
type_name: null,
|
||||
value_length: attributeValue.length,
|
||||
value_sha256: createHash("sha256").update(attributeValue).digest("hex"),
|
||||
token: "0x0c000001",
|
||||
},
|
||||
]);
|
||||
expect(result.coverage).toMatchObject({
|
||||
state: "partial",
|
||||
issues: [
|
||||
@@ -227,7 +220,7 @@ describe("managed artifact coded indexes", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
references,
|
||||
extendsRaw: 9,
|
||||
customAttributeTypeRaw: 19,
|
||||
customAttributeTypeRaw: 0,
|
||||
});
|
||||
const layout = metadataLayoutFor(bytes);
|
||||
const artifact = inspectManagedArtifactBytes(
|
||||
|
||||
@@ -27,6 +27,13 @@ type AssemblyReference = ManagedArtifactInspection["references"][number];
|
||||
type ManagedResource = ManagedArtifactInspection["resources"][number];
|
||||
type CustomAttribute = ManagedArtifactInspection["attributes"][number];
|
||||
|
||||
const HAS_CUSTOM_ATTRIBUTE_TABLES = [
|
||||
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42, 44,
|
||||
43,
|
||||
] as const;
|
||||
|
||||
const CUSTOM_ATTRIBUTE_TYPE_TABLES = [undefined, undefined, 6, 10] as const;
|
||||
|
||||
const publicKeyIdentity = (
|
||||
bytes: Buffer,
|
||||
kind: "public-key" | "public-key-token",
|
||||
@@ -360,56 +367,56 @@ export const readCustomAttribute = (
|
||||
const parent = metadataCodedToken(
|
||||
parentRaw,
|
||||
5,
|
||||
[
|
||||
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42,
|
||||
44, 43,
|
||||
],
|
||||
HAS_CUSTOM_ATTRIBUTE_TABLES,
|
||||
layout.rowCounts,
|
||||
);
|
||||
const parentReason = metadataCodedTokenInvalidReason(
|
||||
parentRaw,
|
||||
5,
|
||||
[
|
||||
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42,
|
||||
44, 43,
|
||||
],
|
||||
layout.rowCounts,
|
||||
);
|
||||
if (parent === null)
|
||||
if (parent === null) {
|
||||
const parentReason = metadataCodedTokenInvalidReason(
|
||||
parentRaw,
|
||||
5,
|
||||
HAS_CUSTOM_ATTRIBUTE_TABLES,
|
||||
layout.rowCounts,
|
||||
);
|
||||
throw managedFailure(
|
||||
"invalid-row",
|
||||
`metadata.CustomAttribute:${metadataToken(12, row)}`,
|
||||
`CustomAttribute parent coded index 0x${parentRaw.toString(16)} is invalid${parentReason === null ? " because the required parent is null" : `: ${parentReason}`}`,
|
||||
cursor.start,
|
||||
);
|
||||
const typeReason = metadataCodedTokenInvalidReason(
|
||||
}
|
||||
const constructor = metadataCodedToken(
|
||||
typeRaw,
|
||||
3,
|
||||
[undefined, undefined, 6, 10],
|
||||
CUSTOM_ATTRIBUTE_TYPE_TABLES,
|
||||
layout.rowCounts,
|
||||
);
|
||||
if (typeReason !== null || typeRaw === 0)
|
||||
throw managedFailure(
|
||||
"invalid-row",
|
||||
`metadata.CustomAttribute:${metadataToken(12, row)}`,
|
||||
typeReason === null
|
||||
? "CustomAttribute constructor coded index 0x0 is null, but Type must reference a MethodDef or MemberRef row"
|
||||
: `CustomAttribute constructor coded index 0x${typeRaw.toString(16)} is invalid: ${typeReason}`,
|
||||
typeOffset,
|
||||
);
|
||||
const typeName =
|
||||
readManagedValue(
|
||||
() => attributeTypeName(bytes, layout, typeRaw, heapExtent),
|
||||
issues,
|
||||
) ?? null;
|
||||
return {
|
||||
parent_token: parent,
|
||||
constructor_token: metadataCodedToken(
|
||||
if (constructor === null) {
|
||||
const typeReason = metadataCodedTokenInvalidReason(
|
||||
typeRaw,
|
||||
3,
|
||||
[undefined, undefined, 6, 10],
|
||||
CUSTOM_ATTRIBUTE_TYPE_TABLES,
|
||||
layout.rowCounts,
|
||||
),
|
||||
);
|
||||
issues.push({
|
||||
code: "invalid-row",
|
||||
scope: `metadata.CustomAttribute:${metadataToken(12, row)}`,
|
||||
offset: typeOffset,
|
||||
detail:
|
||||
typeReason === null
|
||||
? "CustomAttribute constructor coded index 0x0 is null, but Type must reference a MethodDef or MemberRef row"
|
||||
: `CustomAttribute constructor coded index 0x${typeRaw.toString(16)} is invalid: ${typeReason}`,
|
||||
});
|
||||
}
|
||||
let typeName: string | null = null;
|
||||
if (constructor !== null)
|
||||
typeName =
|
||||
readManagedValue(
|
||||
() => attributeTypeName(bytes, layout, typeRaw, heapExtent),
|
||||
issues,
|
||||
) ?? null;
|
||||
return {
|
||||
parent_token: parent,
|
||||
constructor_token: constructor,
|
||||
type_name: typeName,
|
||||
value_length: value.length,
|
||||
value_sha256: managedDecodeBudget(layout).digest(value, "sha256"),
|
||||
|
||||
@@ -5,6 +5,7 @@ import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { writeOrderedZip } from "../../fixtures/artifactEntryOrder.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
@@ -12,6 +13,108 @@ import { ZipArtifactReader } from "../../../src/artifacts/ZipArtifactReader.js";
|
||||
import { withArtifactClient } from "../../support/artifactClientScope.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
|
||||
it.each([
|
||||
["legacy CP437", Buffer.from([0x82, 0x2e, 0x74, 0x78, 0x74]), false, "é.txt"],
|
||||
[
|
||||
"EFS with leading U+FEFF",
|
||||
Buffer.from([0xef, 0xbb, 0xbf, 0x61, 0x62]),
|
||||
true,
|
||||
"\uFEFFab",
|
||||
],
|
||||
] as const)(
|
||||
"preserves %s ZIP member names",
|
||||
async (_label, rawName, utf8Flag, logicalPath) => {
|
||||
const root = await createTestTempDirectory("rea-zip-decoded-name-");
|
||||
const path = join(root, "names.zip");
|
||||
await writeSingleEntryZip(path, "x.txt");
|
||||
const archive = await readFile(path);
|
||||
await writeFile(
|
||||
path,
|
||||
rewriteSingleEntryName(archive, "x.txt", rawName, utf8Flag),
|
||||
);
|
||||
|
||||
const inventory = await inventoryArtifact(path);
|
||||
expect(inventory.occurrences).toContainEqual(
|
||||
expect.objectContaining({
|
||||
logical_path: logicalPath,
|
||||
hash_status: "verified",
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves valid Info-ZIP Unicode Path overrides", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-unicode-path-");
|
||||
const path = join(root, "unicode-path.zip");
|
||||
const rawName = Buffer.from("legacy.txt");
|
||||
const unicodeName = Buffer.from("café.txt", "utf8");
|
||||
const field = Buffer.alloc(5 + unicodeName.length);
|
||||
field[0] = 1;
|
||||
field.writeUInt32LE(zipCrc32(rawName), 1);
|
||||
unicodeName.copy(field, 5);
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("legacy.txt", new TextReader("unicode path"), {
|
||||
extraField: new Map([[0x7075, field]]),
|
||||
});
|
||||
const archive = Buffer.from(await writer.close());
|
||||
await writeFile(
|
||||
path,
|
||||
rewriteSingleEntryName(archive, "legacy.txt", rawName, false),
|
||||
);
|
||||
|
||||
const inventory = await inventoryArtifact(path);
|
||||
expect(inventory.occurrences).toContainEqual(
|
||||
expect.objectContaining({
|
||||
logical_path: "café.txt",
|
||||
hash_status: "verified",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects malformed UTF-8 in flagged ZIP member names", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-invalid-utf8-name-");
|
||||
const path = join(root, "invalid-utf8.zip");
|
||||
await writeSingleEntryZip(path, "x.txt");
|
||||
const archive = await readFile(path);
|
||||
const malformedName = Buffer.from([0xc3, 0x28, 0x2e, 0x74, 0x78]);
|
||||
await writeFile(
|
||||
path,
|
||||
rewriteSingleEntryName(archive, "x.txt", malformedName, true),
|
||||
);
|
||||
|
||||
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "format",
|
||||
message: "ZIP filename is not valid UTF-8",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects malformed UTF-8 in a CRC-valid Unicode Path extra field", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-invalid-unicode-extra-");
|
||||
const path = join(root, "invalid-unicode-extra.zip");
|
||||
const rawName = Buffer.from("legacy.txt");
|
||||
const malformedName = Buffer.from([0xc3, 0x28, 0x2e, 0x74, 0x78]);
|
||||
const field = Buffer.alloc(5 + malformedName.length);
|
||||
field[0] = 1;
|
||||
field.writeUInt32LE(zipCrc32(rawName), 1);
|
||||
malformedName.copy(field, 5);
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("legacy.txt", new TextReader("malformed extra"), {
|
||||
extraField: new Map([[0x7075, field]]),
|
||||
});
|
||||
const archive = Buffer.from(await writer.close());
|
||||
await writeFile(
|
||||
path,
|
||||
rewriteSingleEntryName(archive, "legacy.txt", rawName, false),
|
||||
);
|
||||
|
||||
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "format",
|
||||
message: "ZIP Unicode Path extra field is not valid UTF-8",
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds a requested metadata read without rejecting the underlying valid ZIP", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-metadata-budget-");
|
||||
const path = join(root, "large-directory.zip");
|
||||
@@ -295,3 +398,66 @@ it("rejects a truncated ZIP through artifact inventory", async () => {
|
||||
error: { _tag: "ArtifactOperationError", reason: "io" },
|
||||
});
|
||||
});
|
||||
|
||||
const writeSingleEntryZip = async (
|
||||
path: string,
|
||||
name: string,
|
||||
): Promise<void> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(name, new TextReader("member bytes"));
|
||||
await writeFile(path, await writer.close());
|
||||
};
|
||||
|
||||
const rewriteSingleEntryName = (
|
||||
archive: Buffer,
|
||||
originalName: string,
|
||||
rawName: Buffer,
|
||||
utf8Flag: boolean,
|
||||
): Buffer => {
|
||||
const rewritten = Buffer.from(archive);
|
||||
const expectedName = Buffer.from(originalName, "utf8");
|
||||
for (const { signature, nameOffset, flagsOffset, lengthOffset } of [
|
||||
{
|
||||
signature: Buffer.from([0x50, 0x4b, 0x03, 0x04]),
|
||||
nameOffset: 30,
|
||||
flagsOffset: 6,
|
||||
lengthOffset: 26,
|
||||
},
|
||||
{
|
||||
signature: Buffer.from([0x50, 0x4b, 0x01, 0x02]),
|
||||
nameOffset: 46,
|
||||
flagsOffset: 8,
|
||||
lengthOffset: 28,
|
||||
},
|
||||
]) {
|
||||
const header = rewritten.indexOf(signature);
|
||||
if (header < 0) throw new Error("Expected ZIP member header");
|
||||
const nameLength = rewritten.readUInt16LE(header + lengthOffset);
|
||||
if (
|
||||
nameLength !== expectedName.length ||
|
||||
nameLength !== rawName.length ||
|
||||
!rewritten
|
||||
.subarray(header + nameOffset, header + nameOffset + nameLength)
|
||||
.equals(expectedName)
|
||||
)
|
||||
throw new Error("Expected the original ZIP member name");
|
||||
rawName.copy(rewritten, header + nameOffset);
|
||||
const flags = rewritten.readUInt16LE(header + flagsOffset);
|
||||
rewritten.writeUInt16LE(
|
||||
utf8Flag ? flags | 0x0800 : flags & ~0x0800,
|
||||
header + flagsOffset,
|
||||
);
|
||||
}
|
||||
return rewritten;
|
||||
};
|
||||
|
||||
const zipCrc32 = (bytes: Uint8Array): number => {
|
||||
let checksum = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
checksum ^= byte;
|
||||
for (let bit = 0; bit < 8; bit += 1)
|
||||
checksum =
|
||||
(checksum & 1) === 1 ? (checksum >>> 1) ^ 0xedb88320 : checksum >>> 1;
|
||||
}
|
||||
return (checksum ^ 0xffffffff) >>> 0;
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -142,6 +143,57 @@ const asManagedMemberResult = (execution: AnalysisExecution) =>
|
||||
const asManagedNativeBoundaryResult = (execution: AnalysisExecution) =>
|
||||
managedNativeBoundaryInspectionSchema.parse(execution.result);
|
||||
|
||||
it("preserves custom attribute value evidence through the filesystem provider when its constructor is invalid", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-attribute-");
|
||||
const path = join(directory, "fixture.exe");
|
||||
await writeFile(path, buildManagedPeFixture({ customAttributeTypeRaw: 19 }));
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const frameworkText = Buffer.from(".NETCoreApp,Version=v8.0", "utf8");
|
||||
const attributeValue = Buffer.concat([
|
||||
Buffer.from([1, 0, frameworkText.length]),
|
||||
frameworkText,
|
||||
Buffer.alloc(2),
|
||||
]);
|
||||
const client = new ManagedStaticProvider().createClient(parsed.value);
|
||||
try {
|
||||
const execution = await client.execute("inspect_managed_artifact", {});
|
||||
if (!execution.ok) throw execution.error;
|
||||
|
||||
const result = asManagedResult(execution.value);
|
||||
expect(result).toMatchObject({
|
||||
attributes: [
|
||||
{
|
||||
parent_token: "0x20000001",
|
||||
constructor_token: null,
|
||||
type_name: null,
|
||||
value_length: attributeValue.length,
|
||||
value_sha256: createHash("sha256")
|
||||
.update(attributeValue)
|
||||
.digest("hex"),
|
||||
token: "0x0c000001",
|
||||
},
|
||||
],
|
||||
coverage: {
|
||||
state: "partial",
|
||||
},
|
||||
});
|
||||
const attribute = result.attributes[0];
|
||||
if (attribute === undefined) throw new Error("Fixture omitted attribute");
|
||||
expect(result.coverage.issues).toEqual([
|
||||
expect.objectContaining({
|
||||
code: "invalid-row",
|
||||
scope: "metadata.CustomAttribute:0x0c000001",
|
||||
offset: attribute.row_offset + 2,
|
||||
detail:
|
||||
"CustomAttribute constructor coded index 0x13 is invalid: coded index selects row 2 in table 10, which has 1 rows",
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains U+FEFF metadata through the filesystem target and provider", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-bom-");
|
||||
const path = join(directory, "fixture.exe");
|
||||
|
||||
Reference in New Issue
Block a user