Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/application/ReferenceSourceImportEntries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { logicalPathEscapesRoot } from "../domain/artifactIdentity.js";
import {
createReferenceSourcePathLookup,
decodeReferenceSourceModuleUrlPath,
isPortableAbsoluteReferenceTarget,
type ReferenceSourcePathLookup,
} from "../domain/referenceSourcePathIdentity.js";
import {
Expand Down Expand Up @@ -514,15 +513,24 @@ const appendReadEntry = (
});
return;
}
if (entry.targetState === "unknown") {
output.entries.push({
path: entry.path,
kind: "symlink",
target: null,
target_state: "unknown",
classifications,
limitations: [entry.limitation],
});
return;
}
output.entries.push({
path: entry.path,
kind: "symlink",
// The reader resolves inventory identities from its root; the persisted
// graph represents relative symlink targets from the link's directory.
// Only canonical internal identities are root-relative. Missing targets
// retain their path components, relative to the link's directory when local.
target:
entry.targetState === "internal" ||
(entry.targetState === "missing" &&
!isPortableAbsoluteReferenceTarget(entry.target))
entry.targetState === "internal"
? posix.relative(posix.dirname(entry.path), entry.target) || "."
: entry.target,
target_state: entry.targetState,
Expand Down
36 changes: 23 additions & 13 deletions src/reference/ReferenceSourceReaderEntries.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { BigIntStats, Dir, Dirent } from "node:fs";
import { opendir, readlink, realpath } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { opendir, readlink, realpath, stat } from "node:fs/promises";
import { join, normalize, sep } from "node:path";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactCleanupAttempt } from "../artifacts/ArtifactResourceScope.js";
import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
Expand Down Expand Up @@ -455,27 +455,37 @@ const readSymlinkTarget = async (
`Symlink target is not valid UTF-8 (raw target bytes: ${rawTarget.toString("hex")})`,
);
}
const lexicalTarget = resolve(dirname(absolute), target);
if (!isPathWithinRoot(root, lexicalTarget))
return {
status: "read",
kind: "symlink",
path,
target: lexicalTarget,
targetState: "external",
};
let canonicalTarget: string;
try {
canonicalTarget = await realpath(lexicalTarget);
// macOS realpath can discard a non-directory parent step or trailing
// separator. Validate native target lookup before canonicalizing it.
await stat(absolute);
// Resolve the observed link itself: normalizing its target first can change
// both the selected file and whether it lies inside the reference root.
// This observes metadata only; traversal never reads a symlink's contents.
canonicalTarget = await realpath(absolute);
} catch (cause: unknown) {
const code =
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
// The graph accepts normalized relative identities. A failed resolution
// cannot justify collapsing parent steps or directory intent into one;
// retain the observation as a limitation instead of naming another file.
const nativeTarget = target.replaceAll("/", sep);
if (normalize(nativeTarget) !== nativeTarget || nativeTarget.endsWith(sep))
return {
status: "read",
kind: "symlink",
path,
target: null,
targetState: "unknown",
limitation: `Symbolic link target ${JSON.stringify(target)} could not be resolved (${code}); its path intent cannot be normalized without changing the observation.`,
};
return {
status: "read",
kind: "symlink",
path,
target: pathFromRoot(root, lexicalTarget),
target: nativeTarget.split(sep).join("/"),
targetState: "missing",
};
}
Expand Down
10 changes: 9 additions & 1 deletion src/reference/ReferenceSourceReaderTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,18 @@ export type ReferenceSourceEntry =
readonly status: "read";
readonly kind: "symlink";
readonly path: string;
/** Internal and relative missing targets are resolved from the inventory root. */
/** Internal targets are root-relative; relative missing targets are link-relative, with native separators converted to '/'. */
readonly target: string;
readonly targetState: "internal" | "external" | "missing";
}
| {
readonly status: "read";
readonly kind: "symlink";
readonly path: string;
readonly target: null;
readonly targetState: "unknown";
readonly limitation: string;
}
| {
readonly status: "failed";
readonly kind: "file" | "directory" | "symlink" | "other" | "unknown";
Expand Down
100 changes: 100 additions & 0 deletions tests/boundary/filesystem/referenceSourceImport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
open,
realpath,
rm,
stat,
symlink,
writeFile,
} from "node:fs/promises";
Expand Down Expand Up @@ -131,6 +132,105 @@ describe("reference source import projections", () => {
});
});

describe("reference source selected symlink paths", () => {
it.skipIf(process.platform === "win32")(
"records physical link targets and retains unresolved path intent",
async () => {
const workspace = await createTestTempDirectory(
"rea-reference-link-targets-",
);
const root = join(workspace, "source");
const outside = join(workspace, "outside");
await mkdir(join(root, "actual", "nested"), { recursive: true });
await mkdir(join(outside, "nested"), { recursive: true });
await writeFile(join(root, "target.js"), "export const decoy = 1;\n");
await writeFile(join(root, "actual", "target.js"), "export {};\n");
await writeFile(join(outside, "private.js"), "OUTSIDE_NOT_READ");
await symlink("actual/nested", join(root, "current"));
await symlink("../outside/nested", join(root, "outward"));
await symlink(root, join(outside, "back"));
const targets = new Map([
["relative.js", "current/../target.js"],
["absolute.js", `${root}/current/../target.js`],
["return.js", "../outside/back/actual/target.js"],
["external.js", "../outside/private.js"],
["escape.js", "outward/../private.js"],
["missing.js", "absent.js"],
["literal-backslash.js", "literal\\absent.js"],
["actual/missing.js", "../absent.js"],
["broken.js", "absent/../target.js"],
["absolute-broken.js", `${root}/absent/../target.js`],
["not-directory.js", "target.js/../target.js"],
["directory-intent.js", "target.js/"],
]);
for (const [name, target] of targets)
await symlink(target, join(root, name));
const expectedTarget = join(root, "actual", "target.js");
for (const name of ["relative.js", "absolute.js", "return.js"])
expect(await realpath(join(root, name))).toBe(expectedTarget);
const ambiguous = [
"broken.js",
"absolute-broken.js",
"not-directory.js",
"directory-intent.js",
];
// Native lookup rejects these targets even when macOS realpath drops
// a non-directory parent step or trailing separator.
for (const name of ambiguous)
await expect(stat(join(root, name))).rejects.toMatchObject({
code: expect.stringMatching(/^(?:ENOENT|ENOTDIR)$/u),
});

const imported = await importTree(root);
if (!imported.ok) throw imported.error;
const entries = new Map(
imported.value.entries.map((entry) => [entry.path, entry]),
);
for (const name of ["relative.js", "absolute.js", "return.js"])
expect(entries.get(name)).toMatchObject({
kind: "symlink",
target: "actual/target.js",
target_state: "internal",
limitations: [],
});
for (const name of ["external.js", "escape.js"])
expect(entries.get(name)).toMatchObject({
kind: "symlink",
target: join(outside, "private.js"),
target_state: "external",
});
expect(entries.get("missing.js")).toMatchObject({
kind: "symlink",
target: "absent.js",
target_state: "missing",
});
expect(entries.get("actual/missing.js")).toMatchObject({
kind: "symlink",
target: "../absent.js",
target_state: "missing",
});
expect(entries.get("literal-backslash.js")).toMatchObject({
kind: "symlink",
target: "literal\\absent.js",
target_state: "missing",
});
for (const name of ambiguous)
expect(entries.get(name)).toMatchObject({
kind: "symlink",
target: null,
target_state: "unknown",
limitations: [expect.stringContaining(targets.get(name) ?? "")],
});
expect(
imported.value.entries
.filter(({ kind }) => kind === "file")
.map(({ path }) => path),
).toEqual(["actual/target.js", "target.js"]);
expect(JSON.stringify(imported.value)).not.toContain("OUTSIDE_NOT_READ");
},
);
});

describe("reference source ignore policy read failures", () => {
it("preserves a late-aborted physical admission failure identical to the reason", async () => {
const root = await createTestTempDirectory("rea-reference-admission-read-");
Expand Down
3 changes: 3 additions & 0 deletions tests/process-global/referenceSourceSymlinkRace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import {
readFile,
rename,
unlink,
utimes,
writeFile,
symlink,
} from "node:fs/promises";
Expand Down Expand Up @@ -164,6 +165,8 @@ it.skipIf(process.platform === "win32").each(["contents", "root"] as const)(
await mkdir(root);
const source = join(root, "source.txt");
await writeFile(source, "already observed source");
// Make the rename observable even with coarse filesystem timestamps.
await utimes(root, 0, 0);
race.directory = root;
race.afterDirectoryClose = () =>
changed === "contents"
Expand Down
Loading