fix(reference): match exclusions against observed entry kinds

Inspect each entry without following links before applying directory-only patterns. Retain the winning rule and original entry path while pruning excluded directories before reading their children.

Validate directory exclusions, negation, symlinks, explicit secret rules, and compiled CLI provenance alongside reference reader failure and cancellation coverage.
This commit is contained in:
morluto
2026-10-11 04:43:02 +08:00
parent b74d9a1bb2
commit 6636045c9c
5 changed files with 169 additions and 82 deletions
+6 -4
View File
@@ -9,6 +9,7 @@ import {
} from "../domain/referenceSourceGraph.js";
import { err, ok, type Result } from "../domain/result.js";
import { readReferenceSource } from "../reference/ReferenceSourceReader.js";
import type { ReferenceSourceEntryKind } from "../reference/ReferenceSourceReaderTypes.js";
import { parseReferenceSourceEntries } from "./ReferenceSourceImportEntries.js";
import { readReferenceSourceVcs } from "./ReferenceSourceVcsAdapter.js";
import {
@@ -131,9 +132,10 @@ const createShouldExclude =
exclusions: HistoricalSourceGraphInput["exclusions"],
secrets: PreparedReferenceSourceImport["secrets"],
ignored: PreparedReferenceSourceImport["ignored"],
): ((path: string) => boolean) =>
(path) => {
const secretMatch = secrets.test(path);
): ((path: string, kind: ReferenceSourceEntryKind) => boolean) =>
(path, kind) => {
const patternPath = kind === "directory" ? `${path}/` : path;
const secretMatch = secrets.test(patternPath);
if (secretMatch.ignored) {
if (!secretMatch.rule)
throw new Error(`Ignored secret path has no matching rule: ${path}`);
@@ -144,7 +146,7 @@ const createShouldExclude =
});
return true;
}
const match = ignored.test(path);
const match = ignored.test(patternPath);
if (!match.ignored) return false;
if (!match.rule)
throw new Error(`Ignored path has no matching rule: ${path}`);
+23 -20
View File
@@ -20,6 +20,7 @@ import {
import {
type PendingDirectory,
type ReferenceSourceEntry,
type ReferenceSourceEntryKind,
type ReferenceSourceResult,
type TraversalState,
} from "./ReferenceSourceReaderTypes.js";
@@ -152,7 +153,20 @@ const processEntry = async (
if (isAborted(state.signal)) return { ok: false, error: cancelled() };
const absolute = join(current.path, name);
const path = pathFromRoot(state.root, absolute);
const excluded = applyExclusion(state.shouldExclude, path);
const metadata = await readMetadata(absolute);
if (isAborted(state.signal)) return { ok: false, error: cancelled() };
if (!metadata.ok) {
state.entries.push(entryFailure(path, "unknown", "io", metadata.message));
return { ok: true, value: undefined };
}
const kind = metadata.value.isSymbolicLink()
? "symlink"
: metadata.value.isDirectory()
? "directory"
: metadata.value.isFile()
? "file"
: "other";
const excluded = applyExclusion(state.shouldExclude, path, kind);
if (!excluded.ok)
return {
ok: false,
@@ -163,28 +177,14 @@ const processEntry = async (
},
};
if (excluded.value) return { ok: true, value: undefined };
const metadata = await readMetadata(absolute);
if (isAborted(state.signal)) return { ok: false, error: cancelled() };
if (!metadata.ok) {
state.entries.push(entryFailure(path, "unknown", "io", metadata.message));
return { ok: true, value: undefined };
}
if (isAborted(state.signal))
return {
ok: false,
error: {
tag: "reference-source-reader",
code: "cancelled",
message: "Reference source traversal cancelled",
},
};
if (metadata.value.isSymbolicLink())
if (kind === "symlink")
state.entries.push(
await describeSymlink(state.root, absolute, path, state.signal),
);
else if (metadata.value.isDirectory()) {
else if (kind === "directory") {
directories.push({ path: absolute });
} else if (!metadata.value.isFile())
} else if (kind !== "file")
state.entries.push(
entryFailure(
path,
@@ -298,11 +298,14 @@ const describeSymlink = async (
};
const applyExclusion = (
shouldExclude: ((path: string) => boolean) | undefined,
shouldExclude:
| ((path: string, kind: ReferenceSourceEntryKind) => boolean)
| undefined,
path: string,
kind: ReferenceSourceEntryKind,
): { readonly ok: true; readonly value: boolean } | { readonly ok: false } => {
try {
return { ok: true, value: shouldExclude?.(path) === true };
return { ok: true, value: shouldExclude?.(path, kind) === true };
} catch (cause: unknown) {
// Exclusion predicates are caller-supplied; a throwing predicate fails
// closed and the caller-visible `{ ok: false }` preserves the rejection
+14 -2
View File
@@ -2,9 +2,18 @@ import { type BigIntStats } from "node:fs";
import { type Result } from "../domain/result.js";
export type ReferenceSourceEntryKind =
| "file"
| "directory"
| "symlink"
| "other";
export interface ReferenceSourceReaderOptions {
readonly signal?: AbortSignal;
readonly shouldExclude?: (path: string) => boolean;
readonly shouldExclude?: (
path: string,
kind: ReferenceSourceEntryKind,
) => boolean;
}
export type ReferenceSourceFailureCode =
@@ -66,7 +75,10 @@ export type TraversalState = {
readonly root: string;
readonly rootIdentity: BigIntStats;
readonly signal?: AbortSignal;
readonly shouldExclude?: (path: string) => boolean;
readonly shouldExclude?: (
path: string,
kind: ReferenceSourceEntryKind,
) => boolean;
readonly entries: ReferenceSourceEntry[];
readonly pending: PendingDirectory[];
bytesRead: number;
@@ -1,5 +1,5 @@
import fs from "node:fs";
import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { chmod, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { add, commit, init } from "isomorphic-git";
@@ -444,13 +444,24 @@ describe.skipIf(process.platform === "win32")(
const root = await createTestTempDirectory(
"rea-reference-ignore-origin-",
);
await mkdir(join(root, "dist"), { recursive: true });
await mkdir(join(root, "project-parent"), { recursive: true });
await mkdir(join(root, "caller-parent"), { recursive: true });
const directories = [
"dist",
"project-parent",
"caller-parent",
"node_modules/pkg",
"empty-ignored",
"secret-dir",
"keep-as-dir",
"link-target",
];
await Promise.all(
directories.map((path) => mkdir(join(root, path), { recursive: true })),
);
const secretChild = join(root, "secret-dir", "unreadable.ts");
await Promise.all([
writeFile(
join(root, ".gitignore"),
"project.tmp\n*.log\n!keep.log\nproject-parent/\n!project-parent/keep.ts\n!default.log\n",
"project.tmp\n*.log\n!keep.log\nproject-parent/\n!project-parent/keep.ts\n!default.log\nempty-ignored/\nkeep-as-dir\n!keep-as-dir/\nlinkdir/\n",
),
writeFile(join(root, "project.tmp"), "project rule\n"),
writeFile(join(root, "project.log"), "project rule\n"),
@@ -460,56 +471,112 @@ describe.skipIf(process.platform === "win32")(
writeFile(join(root, "dist", "output.js"), "generated output\n"),
writeFile(join(root, "project-parent", "keep.ts"), "parent ignored\n"),
writeFile(join(root, "caller-parent", "keep.ts"), "caller parent\n"),
writeFile(join(root, "node_modules/pkg/package.json"), "{}\n"),
writeFile(join(root, "secret-dir", "unreadable.ts"), "secret\n"),
writeFile(join(root, "keep-as-dir", "kept.ts"), "re-included\n"),
writeFile(join(root, "link-target", "source.ts"), "target\n"),
writeFile(join(root, "selected.ts"), "selected source\n"),
]);
await symlink(join(root, "link-target"), join(root, "linkdir"));
const imported = await importReferenceSource({
root,
caller: "reference-import-test",
policy: { secretPatterns: ["project.log"] },
excludePaths: ["caller-parent/", "!selected.ts", "!caller-keep.log"],
});
if (!imported.ok) throw imported.error;
const canRestrictPermissions =
process.platform !== "win32" && process.getuid?.() !== 0;
if (canRestrictPermissions) await chmod(secretChild, 0);
expect(imported.value.exclusions).toEqual(
expect.arrayContaining([
{
path: "project.tmp",
reason: "project-ignored",
pattern: "project.tmp",
},
{
path: "project.log",
reason: "configured-secret",
pattern: "project.log",
},
{ path: "keep.log", reason: "default-ignored", pattern: "*.log" },
{
path: "dist/output.js",
reason: "default-ignored",
pattern: "dist/",
},
{
path: "project-parent/keep.ts",
reason: "project-ignored",
pattern: "project-parent/",
},
{
path: "caller-parent/keep.ts",
reason: "caller-excluded",
pattern: "caller-parent/",
},
]),
);
expect(imported.value.entries).toContainEqual(
expect.objectContaining({ path: "selected.ts", kind: "file" }),
);
expect(imported.value.entries).toContainEqual(
expect.objectContaining({ path: "caller-keep.log", kind: "file" }),
);
expect(imported.value.exclusions).not.toContainEqual(
expect.objectContaining({ path: "selected.ts" }),
);
try {
const imported = await importReferenceSource({
root,
caller: "reference-import-test",
policy: { secretPatterns: ["project.log", "secret-dir/"] },
excludePaths: ["caller-parent/", "!selected.ts", "!caller-keep.log"],
});
if (!imported.ok) throw imported.error;
expect(imported.value.exclusions).toEqual(
expect.arrayContaining([
{
path: "project.tmp",
reason: "project-ignored",
pattern: "project.tmp",
},
{
path: "project.log",
reason: "configured-secret",
pattern: "project.log",
},
{
path: "keep.log",
reason: "default-ignored",
pattern: "*.log",
},
{
path: "dist",
reason: "default-ignored",
pattern: "dist/",
},
{
path: "node_modules",
reason: "default-ignored",
pattern: "node_modules/",
},
{
path: "empty-ignored",
reason: "project-ignored",
pattern: "empty-ignored/",
},
{
path: "project-parent",
reason: "project-ignored",
pattern: "project-parent/",
},
{
path: "caller-parent",
reason: "caller-excluded",
pattern: "caller-parent/",
},
{
path: "secret-dir",
reason: "configured-secret",
pattern: "secret-dir/",
},
]),
);
expect(imported.value.entries).toContainEqual(
expect.objectContaining({ path: "selected.ts", kind: "file" }),
);
expect(imported.value.entries).toContainEqual(
expect.objectContaining({ path: "caller-keep.log", kind: "file" }),
);
expect(imported.value.entries).toContainEqual(
expect.objectContaining({
path: "keep-as-dir/kept.ts",
kind: "file",
}),
);
expect(imported.value.entries).toContainEqual(
expect.objectContaining({ path: "linkdir", kind: "symlink" }),
);
for (const path of [
"dist",
"node_modules",
"empty-ignored",
"project-parent",
"caller-parent",
"secret-dir",
])
expect(
imported.value.entries.some(
(entry) =>
entry.path === path || entry.path.startsWith(`${path}/`),
),
path,
).toBe(false);
expect(imported.value.exclusions).not.toContainEqual(
expect.objectContaining({ path: "selected.ts" }),
);
} finally {
if (canRestrictPermissions) await chmod(secretChild, 0o600);
}
});
},
);
@@ -127,22 +127,25 @@ describe("readReferenceSource entries", () => {
});
describe("readReferenceSource failures and exclusions", () => {
it("applies exclusions to normalized paths before reading entries", async () => {
it("applies exclusions to normalized paths after no-follow type inspection", async () => {
const root = await createTestTempDirectory("rea-reference-");
await mkdir(join(root, "ignored"));
await writeFile(join(root, "ignored", "secret"), "secret");
await writeFile(join(root, "kept"), "kept");
const checked: string[] = [];
const checked: Array<[string, string]> = [];
const result = await readReferenceSource(root, {
shouldExclude: (path) => {
checked.push(path);
shouldExclude: (path, kind) => {
checked.push([path, kind]);
return path === "ignored";
},
});
if (!result.ok) throw result.error;
expect(checked).toEqual(["ignored", "kept"]);
expect(checked).toEqual([
["ignored", "directory"],
["kept", "file"],
]);
expect(result.value.entries.map(({ path }) => path)).toEqual(["kept"]);
});