Skip to content

Commit ec27112

Browse files
committed
fix(artifacts): preserve path identity and exclusion applicability
Normalize path facts once at the owning filesystem boundary, preserve caller spelling and unavailable inventory members, and retain typed read failures. Record exclusion entry kinds so only proven directories can establish descendant symlink targets; omitted legacy kinds stay unknown. Reviewed fixes include #1969, #2642, #2759, and #2994. Validation: 26 reference graph source tests passed; prior artifact checks passed 275 tests with one Windows-only skip. Updated compiled import workflows are included in final validation after regeneration.
1 parent 55dd21a commit ec27112

41 files changed

Lines changed: 2022 additions & 122 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/application/BinaryTargetResolver.ts‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ import {
3232
} from "../domain/rawBinary.js";
3333
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
3434
import { observeMzWindowsHeader } from "../domain/dosMz.js";
35-
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
35+
import {
36+
createXmlPlistSignatureProbe,
37+
hasBinaryPlistSignature,
38+
MAX_XML_PLIST_PROBE_BYTES,
39+
} from "../domain/apple/appleArchiveFormat.js";
3640
import {
3741
hasZipSignature,
3842
isZipPackageFormat,
@@ -49,6 +53,8 @@ import {
4953
} from "../domain/binaryTarget.js";
5054
import type { PeCodeViewRecord } from "../domain/binaryTargetTypes.js";
5155

56+
const XML_PLIST_PROBE_CHUNK_BYTES = 64 * 1024;
57+
5258
/** Options for resolving a local binary target and its stable identity. */
5359
export interface BinaryTargetResolverOptions {
5460
readonly cwd?: string;
@@ -288,12 +294,12 @@ const detectArtifactFormat = async (
288294
> => {
289295
throwIfTargetResolutionCancelled(signal);
290296
const lower = path.toLowerCase();
291-
const magic = Buffer.alloc(8);
297+
const magic = Buffer.alloc(4096);
292298
const observed = await handle.read(magic, 0, magic.length, 0);
293299
throwIfTargetResolutionCancelled(signal);
294300
if (
295-
observed.bytesRead === 8 &&
296-
magic.equals(Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]))
301+
observed.bytesRead >= 8 &&
302+
magic.subarray(0, 8).equals(Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]))
297303
)
298304
throw new BinaryTargetError(
299305
path,
@@ -329,6 +335,37 @@ const detectArtifactFormat = async (
329335
return "dmg";
330336
}
331337
}
338+
// XML property lists can use archive-specific suffixes such as .archive.
339+
// The named-format check above keeps .js, .map, and .asar classifications.
340+
const xmlProbe = createXmlPlistSignatureProbe();
341+
let xmlState = xmlProbe.write(magic.subarray(0, observed.bytesRead));
342+
if (xmlState === "matched") return "plist";
343+
const chunk = Buffer.alloc(XML_PLIST_PROBE_CHUNK_BYTES);
344+
let bytesRead = observed.bytesRead;
345+
while (xmlState === "pending" && bytesRead < MAX_XML_PLIST_PROBE_BYTES) {
346+
throwIfTargetResolutionCancelled(signal);
347+
const read = await handle.read(
348+
chunk,
349+
0,
350+
Math.min(chunk.length, MAX_XML_PLIST_PROBE_BYTES - bytesRead),
351+
bytesRead,
352+
);
353+
throwIfTargetResolutionCancelled(signal);
354+
if (read.bytesRead === 0) break;
355+
bytesRead += read.bytesRead;
356+
xmlState = xmlProbe.write(chunk.subarray(0, read.bytesRead));
357+
if (xmlState === "matched") return "plist";
358+
}
359+
if (bytesRead === MAX_XML_PLIST_PROBE_BYTES) {
360+
const { size } = await handle.stat();
361+
throwIfTargetResolutionCancelled(signal);
362+
if (size > bytesRead)
363+
throw new BinaryTargetError(
364+
path,
365+
"XML plist prolog was not found within the 1 MiB format probe limit",
366+
{ constraint: "file_format_rejected" },
367+
);
368+
}
332369
return undefined;
333370
};
334371

‎src/application/ReferenceSourceImport.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ const createShouldExclude =
151151
throw new Error(`Ignored secret path has no matching rule: ${path}`);
152152
exclusions.push({
153153
path,
154+
entry_kind: kind,
154155
reason: "configured-secret",
155156
pattern: secretMatch.rule.pattern,
156157
});
@@ -167,7 +168,12 @@ const createShouldExclude =
167168
reason !== "caller-excluded"
168169
)
169170
throw new Error(`Ignored path has unknown rule origin: ${path}`);
170-
exclusions.push({ path, reason, pattern: match.rule.pattern });
171+
exclusions.push({
172+
path,
173+
entry_kind: kind,
174+
reason,
175+
pattern: match.rule.pattern,
176+
});
171177
return true;
172178
};
173179

‎src/application/ReferenceSourceVcsAdapter.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,14 +162,21 @@ const resolveSourceHead = async (
162162
// The library probes readFile() without a path to detect promise APIs.
163163
// Reject that invocation without attributing it to a source read.
164164
if (path === undefined)
165-
throw new TypeError("Git filesystem read requires a path");
165+
throw new TypeError("Git metadata path is required");
166166
try {
167167
const bytes = await readMetadataBytes(path);
168168
const encoding =
169-
typeof options === "string" ? options : options?.encoding;
170-
return encoding === undefined || encoding === null
171-
? bytes
172-
: bytes.toString(encoding);
169+
typeof options === "string"
170+
? options
171+
: typeof options === "object" &&
172+
options !== null &&
173+
"encoding" in options
174+
? options.encoding
175+
: undefined;
176+
if (encoding === undefined || encoding === null) return bytes;
177+
if (typeof encoding !== "string" || !Buffer.isEncoding(encoding))
178+
throw new TypeError("Unsupported Git metadata text encoding");
179+
return bytes.toString(encoding);
173180
} catch (cause: unknown) {
174181
if (cause instanceof ArtifactReaderFailure) {
175182
cleanupFailures.push(cause);

‎src/artifacts/ArtifactHash.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import type { Readable } from "node:stream";
33

44
import { ArtifactReaderFailure } from "./ArtifactReader.js";
55
import { streamChunkToBuffer } from "./StreamBytes.js";
6+
import {
7+
createXmlPlistSignatureProbe,
8+
MAX_XML_PLIST_PROBE_BYTES,
9+
} from "../domain/apple/appleArchiveFormat.js";
610

711
/** Full stream digest and byte count with bounded classification evidence. */
812
export type HashResult = {
@@ -31,19 +35,32 @@ export const hashReadable = async (
3135
const hash = createHash("sha256");
3236
const prefixes: Buffer[] = [];
3337
let prefixBytes = 0;
38+
const xmlProbe = createXmlPlistSignatureProbe();
3439
let bytes = 0;
3540
for await (const raw of stream) {
3641
abortIfNeeded(signal);
3742
const chunk = streamChunkToBuffer(raw);
3843
bytes += chunk.length;
3944
hash.update(chunk);
40-
if (prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES) {
45+
let chunkOffset = 0;
46+
while (
47+
chunkOffset < chunk.length &&
48+
(prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES ||
49+
(xmlProbe.state === "pending" &&
50+
prefixBytes < MAX_XML_PLIST_PROBE_BYTES))
51+
) {
52+
const limit =
53+
prefixBytes < ARTIFACT_CLASSIFICATION_PREFIX_BYTES
54+
? ARTIFACT_CLASSIFICATION_PREFIX_BYTES
55+
: MAX_XML_PLIST_PROBE_BYTES;
4156
const selected = chunk.subarray(
42-
0,
43-
ARTIFACT_CLASSIFICATION_PREFIX_BYTES - prefixBytes,
57+
chunkOffset,
58+
Math.min(chunkOffset + limit - prefixBytes, chunk.length),
4459
);
4560
prefixes.push(selected);
4661
prefixBytes += selected.length;
62+
chunkOffset += selected.length;
63+
xmlProbe.write(selected);
4764
}
4865
}
4966
return { sha256: hash.digest("hex"), bytes, prefix: Buffer.concat(prefixes) };

‎src/artifacts/ArtifactPaths.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { logicalPathNfc } from "../domain/artifactIdentity.js";
44
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
55
import { ArtifactReaderFailure } from "./ArtifactReader.js";
66

7-
const DRIVE_OR_UNC = /^(?:[A-Za-z]:|\\|\/\/)/u;
7+
const DRIVE_PREFIX = /^[A-Za-z]:/u;
88

99
/**
1010
* English Unicode case folding used only to describe logical names a
@@ -20,14 +20,9 @@ export const ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION = `Logical archive names
2020
export const DESTINATION_CASE_COLLISION_PREFIX =
2121
"Destination filesystem cannot store both ";
2222

23-
/** Normalize an untrusted logical archive path without touching filesystem. */
23+
/** Normalize slash-separated logical names; backslashes are literal components. */
2424
export const normalizeArtifactPath = (input: string): string => {
25-
if (
26-
input.includes("\0") ||
27-
input.includes("\\") ||
28-
input.startsWith("/") ||
29-
DRIVE_OR_UNC.test(input)
30-
)
25+
if (input.includes("\0") || input.startsWith("/") || DRIVE_PREFIX.test(input))
3126
throw new ArtifactReaderFailure(
3227
"path",
3328
`Artifact path is absolute or unsafe: ${JSON.stringify(input)}`,

‎src/artifacts/DirectoryArtifactReader.ts‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ interface DirectoryTraversalOptions extends ArtifactTraversalOptions {
3030
export class DirectoryArtifactReader implements ArtifactReader {
3131
readonly format = "directory" as const;
3232
#rootPromise: Promise<string> | undefined;
33+
#rootIdentity: { readonly dev: bigint; readonly ino: bigint } | undefined;
3334
readonly #rootPath: string;
3435
readonly #directories = new Set<OwnedDirectoryHandle>();
3536
readonly #files = new Map<OwnedFileHandle, string>();
@@ -52,7 +53,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
5253
const directory = pending.pop();
5354
if (directory === undefined) break;
5455
await withDirectoryIoContext("inspect directory", directory, () =>
55-
assertContainedDirectory(root, directory),
56+
assertContainedDirectory(root, directory, this.#rootIdentity),
5657
);
5758
for await (const entry of this.#readDirectory(
5859
directory,
@@ -62,21 +63,26 @@ export class DirectoryArtifactReader implements ArtifactReader {
6263
))
6364
yield entry;
6465
await withDirectoryIoContext("inspect directory", directory, () =>
65-
assertContainedDirectory(root, directory),
66+
assertContainedDirectory(root, directory, this.#rootIdentity),
6667
);
6768
}
6869
}
6970

7071
async #resolveRoot(): Promise<string> {
71-
return (this.#rootPromise ??= realpath(this.#rootPath)).catch(
72-
(cause: unknown) => {
73-
throw directoryIoFailure(
74-
"resolve artifact root",
75-
this.#rootPath,
76-
cause,
72+
return (this.#rootPromise ??= (async () => {
73+
const root = await realpath(this.#rootPath);
74+
const metadata = await lstat(root, { bigint: true });
75+
if (metadata.isSymbolicLink() || !metadata.isDirectory())
76+
throw new ArtifactReaderFailure(
77+
"path",
78+
"Artifact root changed during traversal",
7779
);
78-
},
79-
);
80+
this.#rootIdentity = { dev: metadata.dev, ino: metadata.ino };
81+
return root;
82+
})().catch((cause: unknown) => {
83+
if (cause instanceof ArtifactReaderFailure) throw cause;
84+
throw directoryIoFailure("resolve artifact root", this.#rootPath, cause);
85+
}));
8086
}
8187

8288
async *#readDirectory(
@@ -100,6 +106,9 @@ export class DirectoryArtifactReader implements ArtifactReader {
100106
};
101107
try {
102108
for (;;) {
109+
await withDirectoryIoContext("inspect directory", directory, () =>
110+
assertContainedDirectory(root, directory, this.#rootIdentity),
111+
);
103112
const child = await handle.handle.read();
104113
if (child === null) break;
105114
abortIfNeeded(signal);
@@ -440,11 +449,16 @@ const abortIfNeeded = (signal?: AbortSignal): void => {
440449
const assertContainedDirectory = async (
441450
root: string,
442451
directory: string,
452+
rootIdentity: { readonly dev: bigint; readonly ino: bigint } | undefined,
443453
): Promise<void> => {
444454
const canonical = await realpath(directory);
445455
const fromRoot = relative(root, canonical);
446456
const metadata = await lstat(directory);
457+
const currentRoot = await lstat(root, { bigint: true });
447458
if (
459+
rootIdentity === undefined ||
460+
currentRoot.dev !== rootIdentity.dev ||
461+
currentRoot.ino !== rootIdentity.ino ||
448462
metadata.isSymbolicLink() ||
449463
!metadata.isDirectory() ||
450464
fromRoot === ".." ||

‎src/artifacts/SafeOutputTree.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,11 @@ const normalizeDestinationPath = (
580580
platform: NodeJS.Platform,
581581
): string => {
582582
const path = normalizeArtifactPath(relativePath);
583+
if (platform === "win32" && path.includes("\\"))
584+
throw new ArtifactReaderFailure(
585+
"path",
586+
`Windows destination cannot materialize artifact path: ${JSON.stringify(path)}; backslashes denote path separators.`,
587+
);
583588
if (platform === "win32" && path.includes(":"))
584589
throw new ArtifactReaderFailure(
585590
"path",
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import { createHash } from "node:crypto";
2+
import { mkdir, writeFile } from "node:fs/promises";
3+
import { join } from "node:path";
4+
5+
import { describe, expect, it } from "vitest";
6+
7+
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
8+
import { preflightPropertyListDecode } from "./InterfaceBuilderDecodeBudget.js";
9+
import { parseXmlPropertyList } from "../../domain/propertyListKeys.js";
10+
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
11+
12+
const example = "<!DOCTYPE document [ harmless example ]>";
13+
const archive = (content: string, comment = "") =>
14+
`<?xml version="1.0"?><plist version="1.0">${comment}<dict><key>$archiver</key><string>NSKeyedArchiver</string><key>$objects</key><array><string>$null</string><dict><key>$class</key><dict><key>CF$UID</key><integer>2</integer></dict><key>title</key><string>${content}</string></dict><dict><key>$classname</key><string>NSButton</string><key>$classes</key><array><string>NSButton</string><string>NSObject</string></array></dict></array><key>$top</key><dict><key>root</key><dict><key>CF$UID</key><integer>1</integer></dict></dict></dict></plist>`;
15+
16+
const inertDeclarations = [
17+
{
18+
kind: "CDATA text",
19+
xml: archive(`<![CDATA[${example}]]>`),
20+
title: example,
21+
},
22+
{
23+
kind: "XML comment",
24+
xml: archive("Build", `<!-- ${example} -->`),
25+
title: "Build",
26+
},
27+
] as const;
28+
29+
describe("inert XML declaration examples in Interface Builder archives", () => {
30+
it.each(inertDeclarations)(
31+
"preflights $kind without treating it as entity expansion",
32+
({ xml }) => {
33+
expect(() => parseXmlPropertyList(xml)).not.toThrow();
34+
expect(
35+
preflightPropertyListDecode(Buffer.from(xml), 16 * 1024 * 1024),
36+
).toMatchObject({
37+
binaryPrototypeKeyObserved: false,
38+
});
39+
},
40+
);
41+
42+
it.each(inertDeclarations)(
43+
"retains $kind and archive provenance through bundle decoding",
44+
async ({ xml, title }) => {
45+
const root = await createTestTempDirectory("rea-ib-inert-declaration-");
46+
const bundle = join(root, "Example.app");
47+
await mkdir(bundle);
48+
const bytes = Buffer.from(xml);
49+
await writeFile(join(bundle, "Panel.nib"), bytes);
50+
51+
const result = await analyzeInterfaceBuilderBundle({
52+
bundlePath: bundle,
53+
targetSha256: "a".repeat(64),
54+
});
55+
56+
expect(result.documents).toContainEqual(
57+
expect.objectContaining({
58+
relative_path: "Panel.nib",
59+
archive_sha256: createHash("sha256").update(bytes).digest("hex"),
60+
}),
61+
);
62+
expect(result.graph.nodes.map(({ name }) => name)).toContain(title);
63+
expect(result.graph.coverage).toContainEqual(
64+
expect.objectContaining({
65+
facet: "archive_decode",
66+
status: "complete",
67+
}),
68+
);
69+
},
70+
);
71+
72+
it("continues to refuse an actual internal entity declaration before decoding", () => {
73+
const xml = archive("&harmless;").replace(
74+
"<plist",
75+
'<!DOCTYPE plist [<!ENTITY harmless "value">]><plist',
76+
);
77+
expect(() =>
78+
preflightPropertyListDecode(Buffer.from(xml), 16 * 1024 * 1024),
79+
).toThrow(
80+
"XML plist internal entity expansion exceeds the aggregate Interface Builder decode budget",
81+
);
82+
});
83+
84+
it("does not mistake a bracket in a quoted external identifier for an internal subset", () => {
85+
const xml = archive("Build").replace(
86+
"<plist",
87+
'<!DOCTYPE plist SYSTEM "example[edition].dtd"><plist',
88+
);
89+
expect(() => parseXmlPropertyList(xml)).not.toThrow();
90+
expect(() =>
91+
preflightPropertyListDecode(Buffer.from(xml), 16 * 1024 * 1024),
92+
).not.toThrow();
93+
});
94+
95+
it.each([
96+
'<!DOCTYPE plist SYSTEM "example>[edition].dtd">',
97+
"<!DOCTYPE plist SYSTEM 'example>[edition].dtd'>",
98+
"<?example <!DOCTYPE document [ harmless example ]> ?>",
99+
])("consumes quoted or opaque declaration text once: %s", (declaration) => {
100+
const xml = archive("Build").replace("<plist", `${declaration}<plist`);
101+
expect(() => parseXmlPropertyList(xml)).not.toThrow();
102+
expect(
103+
preflightPropertyListDecode(Buffer.from(xml), 16 * 1024 * 1024),
104+
).toMatchObject({ binaryPrototypeKeyObserved: false });
105+
});
106+
});

0 commit comments

Comments
 (0)