Harden asset symlink handling and fix image output pairing
- Re-resolve browser-artifact and thread-image claims on every request so post-issuance symlink swaps cannot redirect a signed token - Verify canonical containment and media extension after realPath - Render unscoped image outputs when no turn is unsettled - Keep the image activity id paired with its path across collapsing Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
6f9e892da8
commit
e3edf9bc8e
7 files changed
+280
-20
No files matched your search
@@ -111,6 +111,7 @@ describe("AssetAccess", () => {
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const artifactPath = path.join(config.browserArtifactsDir, "browser-recording-demo.webm");
|
||||
yield* fileSystem.writeFileString(artifactPath, "webm-bytes");
|
||||
const canonicalArtifactPath = yield* fileSystem.realPath(artifactPath);
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(config.browserArtifactsDir, "notes.txt"),
|
||||
"not media",
|
||||
@@ -123,7 +124,7 @@ describe("AssetAccess", () => {
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
expect(yield* resolveAsset(token, "browser-recording-demo.webm")).toEqual({
|
||||
kind: "file",
|
||||
path: artifactPath,
|
||||
path: canonicalArtifactPath,
|
||||
});
|
||||
|
||||
// Non-media files and traversal-style names are not issuable.
|
||||
@@ -335,6 +336,107 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects image view symlinks that escape to non-image files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-view-symlink-",
|
||||
});
|
||||
const secretPath = path.join(directory, "secret.env");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
const disguisedPath = path.join(directory, "disguised.png");
|
||||
yield* fileSystem.symlink(secretPath, disguisedPath);
|
||||
const resource = {
|
||||
_tag: "thread-image" as const,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
};
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath: disguisedPath,
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AssetThreadImageNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-resolves image view claims so post-issuance swaps are rejected", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-view-swap-",
|
||||
});
|
||||
const imagePath = path.join(directory, "tool-output.png");
|
||||
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
const outsidePath = path.join(directory, "secret.png");
|
||||
yield* fileSystem.writeFileString(outsidePath, "SECRET");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "thread-image" as const,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
},
|
||||
threadImagePath: imagePath,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
|
||||
// Swap the issued file for a symlink pointing elsewhere.
|
||||
yield* fileSystem.remove(imagePath);
|
||||
yield* fileSystem.symlink(outsidePath, imagePath);
|
||||
expect(yield* resolveAsset(token, "tool-output.png")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects browser artifact symlinks that escape the artifacts directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-artifact-outside-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.png");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
yield* fileSystem.symlink(secretPath, path.join(config.browserArtifactsDir, "escape.png"));
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "escape.png" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-resolves browser artifact claims so post-issuance swaps are rejected", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-artifact-swap-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.png");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
const artifactPath = path.join(config.browserArtifactsDir, "swapped.png");
|
||||
yield* fileSystem.writeFile(artifactPath, new Uint8Array([137, 80, 78, 71]));
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "swapped.png" },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
|
||||
yield* fileSystem.remove(artifactPath);
|
||||
yield* fileSystem.symlink(secretPath, artifactPath);
|
||||
expect(yield* resolveAsset(token, "swapped.png")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues project favicon capabilities with a signed fallback", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -162,6 +162,40 @@ const statIsFile = (path: string) =>
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
/**
|
||||
* Resolve a browser artifact to its canonical path, rejecting anything that
|
||||
* escapes the artifacts directory. Names are validated before and after
|
||||
* `realPath` so a symlink with an allowed media name cannot redirect to an
|
||||
* arbitrary (or non-media) server-readable file.
|
||||
*/
|
||||
const resolveCanonicalBrowserArtifact = Effect.fn("AssetAccess.resolveCanonicalBrowserArtifact")(
|
||||
function* (fileName: string) {
|
||||
const normalized = normalizeBrowserArtifactFileName(fileName);
|
||||
if (!normalized) return null;
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const [canonicalDir, canonicalFile] = yield* Effect.all([
|
||||
optionOnNotFound(fileSystem.realPath(config.browserArtifactsDir)),
|
||||
optionOnNotFound(fileSystem.realPath(path.join(config.browserArtifactsDir, normalized))),
|
||||
]).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to resolve the browser artifact path.", { fileName, cause }),
|
||||
),
|
||||
Effect.orElseSucceed(() => [Option.none<string>(), Option.none<string>()] as const),
|
||||
);
|
||||
if (Option.isNone(canonicalDir) || Option.isNone(canonicalFile)) return null;
|
||||
|
||||
// Artifacts are stored flat, so the canonical parent must be the
|
||||
// canonical artifacts directory itself.
|
||||
if (path.dirname(canonicalFile.value) !== canonicalDir.value) return null;
|
||||
if (!normalizeBrowserArtifactFileName(path.basename(canonicalFile.value))) return null;
|
||||
|
||||
return (yield* statIsFile(canonicalFile.value)) ? canonicalFile.value : null;
|
||||
},
|
||||
);
|
||||
|
||||
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
|
||||
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -318,12 +352,8 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
break;
|
||||
}
|
||||
case "browser-artifact": {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const artifactFileName = normalizeBrowserArtifactFileName(input.resource.fileName);
|
||||
const artifactPath = artifactFileName
|
||||
? path.join(config.browserArtifactsDir, artifactFileName)
|
||||
: null;
|
||||
if (!artifactFileName || !artifactPath || !(yield* statIsFile(artifactPath))) {
|
||||
if (!artifactFileName || !(yield* resolveCanonicalBrowserArtifact(artifactFileName))) {
|
||||
return yield* new AssetBrowserArtifactNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
@@ -372,7 +402,14 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(info) || info.value.type !== "File") {
|
||||
// The extension check above ran on the pre-realPath input; re-check the
|
||||
// canonical target so a symlink named `*.png` cannot smuggle out an
|
||||
// arbitrary non-image file.
|
||||
if (
|
||||
Option.isNone(info) ||
|
||||
info.value.type !== "File" ||
|
||||
!isWorkspaceImagePreviewPath(canonicalPath.value)
|
||||
) {
|
||||
return yield* new AssetThreadImageNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
@@ -503,22 +540,32 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
}
|
||||
|
||||
if (claims.kind === "browser-artifact") {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const artifactFileName = normalizeBrowserArtifactFileName(claims.fileName);
|
||||
if (!artifactFileName) return null;
|
||||
const path = yield* Path.Path;
|
||||
const artifactPath = path.join(config.browserArtifactsDir, artifactFileName);
|
||||
return (yield* statIsFile(artifactPath))
|
||||
? ({ kind: "file", path: artifactPath } satisfies ResolvedAsset)
|
||||
: null;
|
||||
// Re-resolved on every request: a signed token must not keep serving a
|
||||
// path that was replaced by a symlink after issuance.
|
||||
const artifactPath = yield* resolveCanonicalBrowserArtifact(claims.fileName);
|
||||
return artifactPath ? ({ kind: "file", path: artifactPath } satisfies ResolvedAsset) : null;
|
||||
}
|
||||
|
||||
if (claims.kind === "thread-image") {
|
||||
const decodedPath = decodeRelativePath(relativePath);
|
||||
const path = yield* Path.Path;
|
||||
if (decodedPath !== path.basename(claims.path)) return null;
|
||||
if (!isWorkspaceImagePreviewPath(claims.path)) return null;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(claims.path)).pipe(
|
||||
// The claim stores the path that was canonical at issuance. Re-canonicalize
|
||||
// on every request so a file later replaced by a symlink cannot redirect
|
||||
// this token to somewhere else on disk.
|
||||
const canonicalPath = yield* optionOnNotFound(fileSystem.realPath(claims.path)).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to resolve image view asset.", {
|
||||
path: claims.path,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
if (Option.isNone(canonicalPath) || canonicalPath.value !== claims.path) return null;
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(canonicalPath.value)).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to inspect image view asset.", {
|
||||
path: claims.path,
|
||||
@@ -528,7 +575,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
return Option.isSome(info) && info.value.type === "File"
|
||||
? ({ kind: "file", path: claims.path } satisfies ResolvedAsset)
|
||||
? ({ kind: "file", path: canonicalPath.value } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
@@ -261,6 +261,61 @@ describe("resolveAssistantMessageCopyState", () => {
|
||||
});
|
||||
|
||||
describe("deriveMessagesTimelineRows", () => {
|
||||
it("renders unscoped image output when no turn is unsettled", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "unscoped-image-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
entry: {
|
||||
id: "unscoped-image-activity",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
turnId: null,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/unscoped.png",
|
||||
toolLifecycleStatus: "completed" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-message" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Here is the image.",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:21Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
expandedTurnIds: new Set(),
|
||||
});
|
||||
|
||||
const imageOutputRow = rows.find((row) => row.kind === "image-output");
|
||||
expect(imageOutputRow).toMatchObject({
|
||||
kind: "image-output",
|
||||
id: "image-output:unscoped",
|
||||
images: [
|
||||
{
|
||||
entry: { id: "unscoped-image-activity" },
|
||||
imagePath: "/tmp/unscoped.png",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("deduplicates and groups image output after the terminal assistant message", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
|
||||
@@ -277,7 +277,9 @@ function appendImageOutputRows(input: {
|
||||
if (entry.itemType !== "image_view" || !entry.imagePath) {
|
||||
continue;
|
||||
}
|
||||
if (entry.turnId === input.unsettledTurnId) {
|
||||
// Only skip images that belong to the in-flight turn; an unscoped entry
|
||||
// (null turnId) must still render when no turn is unsettled.
|
||||
if (input.unsettledTurnId !== null && entry.turnId === input.unsettledTurnId) {
|
||||
continue;
|
||||
}
|
||||
const turnId = entry.turnId ?? null;
|
||||
|
||||
@@ -1975,7 +1975,7 @@ function ImageOutputThumbnail({
|
||||
const assetUrl = useAssetUrlState(activeThreadEnvironmentId, {
|
||||
_tag: "thread-image",
|
||||
threadId: threadRef.threadId,
|
||||
activityId: EventId.make(image.entry.id),
|
||||
activityId: EventId.make(image.entry.imageActivityId ?? image.entry.id),
|
||||
});
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
const loadedUrl = assetUrl._tag === "Success" && assetUrl.url !== failedUrl ? assetUrl.url : null;
|
||||
|
||||
@@ -1057,6 +1057,49 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the image activity id paired with the path when collapsing entries", () => {
|
||||
const imagePath = "/tmp/codex-preview.png";
|
||||
const entries = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "image-view-with-path",
|
||||
kind: "tool.updated",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "in_progress",
|
||||
title: "Image view",
|
||||
data: {
|
||||
toolCallId: "call-image-1",
|
||||
item: { id: "call-image-1", path: imagePath, type: "imageView" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
// The completion for the same tool call carries no path; collapsing
|
||||
// adopts its id, so the path's owning activity id must be retained.
|
||||
makeActivity({
|
||||
id: "image-view-without-path",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "completed",
|
||||
title: "Image view",
|
||||
data: {
|
||||
toolCallId: "call-image-1",
|
||||
item: { id: "call-image-1", type: "imageView" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "image-view-without-path",
|
||||
imagePath,
|
||||
imageActivityId: "image-view-with-path",
|
||||
});
|
||||
});
|
||||
|
||||
it("unwraps PowerShell command wrappers for displayed command text", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
|
||||
@@ -70,6 +70,12 @@ export interface WorkLogEntry {
|
||||
rawCommand?: string;
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
imagePath?: string;
|
||||
/**
|
||||
* Activity that carried `imagePath`. Collapsing can merge a later activity's
|
||||
* `id` onto an earlier activity's `imagePath`, and the asset lookup resolves
|
||||
* the path from this activity's payload — so it must stay paired with it.
|
||||
*/
|
||||
imageActivityId?: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
toolTitle?: string;
|
||||
toolData?: unknown;
|
||||
@@ -752,6 +758,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
: null;
|
||||
if (imagePath) {
|
||||
entry.imagePath = imagePath;
|
||||
entry.imageActivityId = entry.id;
|
||||
}
|
||||
}
|
||||
if (itemType) {
|
||||
@@ -825,7 +832,11 @@ function mergeDerivedWorkLogEntries(
|
||||
const detail = next.detail ?? previous.detail;
|
||||
const command = next.command ?? previous.command;
|
||||
const rawCommand = next.rawCommand ?? previous.rawCommand;
|
||||
// Keep the owning activity id paired with the path it came from.
|
||||
const imagePath = next.imagePath ?? previous.imagePath;
|
||||
const imageActivityId = next.imagePath
|
||||
? (next.imageActivityId ?? next.id)
|
||||
: (previous.imageActivityId ?? previous.id);
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
@@ -839,7 +850,7 @@ function mergeDerivedWorkLogEntries(
|
||||
...(detail ? { detail } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
...(imagePath ? { imagePath } : {}),
|
||||
...(imagePath ? { imagePath, imageActivityId } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
|
||||
Reference in new issue
Block a user