Skip to content

Commit e6d0d3f

Browse files
Merge main into fix/issue-22181
2 parents c7a89c4 + b5a226e commit e6d0d3f

18 files changed

Lines changed: 327 additions & 30 deletions

‎apps/mobile/src/lib/markdownMedia.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ describe("resolveMarkdownMediaPreview", () => {
3838
["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
3939
["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png"],
4040
["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
41-
["file://server/share/frame.png", "\\\\server\\share\\frame.png"],
42-
["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png"],
43-
])("keeps encoded filename and UNC semantics for %s", (href, path) => {
44-
expect(resolveMarkdownMediaPreview(href, input)).toMatchObject({
41+
["file://server/share/frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
42+
["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
43+
])("keeps encoded filename and UNC semantics for %s", (href, path, workspaceRoot = "/repo") => {
44+
expect(resolveMarkdownMediaPreview(href, { ...input, workspaceRoot })).toMatchObject({
4545
kind: "image",
4646
source: {
4747
resource: { path },

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import * as FileSystem from "effect/FileSystem";
1717
import * as Layer from "effect/Layer";
1818
import * as Redacted from "effect/Redacted";
1919
import * as Path from "effect/Path";
20+
import * as PlatformError from "effect/PlatformError";
2021
import * as Schema from "effect/Schema";
2122
import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http";
2223
import { vi } from "vite-plus/test";
@@ -359,6 +360,47 @@ describe("AssetAccess", () => {
359360
}).pipe(Effect.provide(layerTest)),
360361
);
361362

363+
// Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
364+
// Windows user's NTLM credentials to attacker.test.
365+
it.effect("never resolves a network media path outside the thread's project", () =>
366+
Effect.gen(function* () {
367+
const fs = yield* FileSystem.FileSystem;
368+
const path = yield* Path.Path;
369+
const resolved: Array<string> = [];
370+
const recordingFileSystem = FileSystem.FileSystem.of({
371+
...fs,
372+
realPath: (requestedPath) => {
373+
resolved.push(requestedPath);
374+
return Effect.fail(
375+
PlatformError.systemError({
376+
_tag: "NotFound",
377+
module: "FileSystem",
378+
method: "realPath",
379+
pathOrDescriptor: requestedPath,
380+
}),
381+
);
382+
},
383+
});
384+
const share = "//nas.test/share/project";
385+
for (const resource of [
386+
{
387+
_tag: "media-file",
388+
threadId: ThreadId.make("thread-1"),
389+
path: "//attacker.test/s/a.png",
390+
},
391+
{ _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
392+
{ _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
393+
] as const) {
394+
const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
395+
Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
396+
Effect.flip,
397+
);
398+
expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
399+
}
400+
expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
401+
}).pipe(Effect.provide(layerTest)),
402+
);
403+
362404
it.effect.skipIf(!symlinksSupported)(
363405
"rejects non-previewable files, disguised targets, and directories",
364406
() =>

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
isProjectFaviconPath,
3737
PROJECT_FAVICON_FALLBACK_MARKER,
3838
} from "@t3tools/shared/projectFavicon";
39+
import { isNetworkPath } from "@t3tools/shared/path";
3940
import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
4041
import * as Clock from "effect/Clock";
4142
import * as Crypto from "effect/Crypto";
@@ -60,6 +61,7 @@ import * as ServerConfig from "../config.ts";
6061
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
6162
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
6263
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
64+
import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
6365
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
6466
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
6567
import { extractIcnsPng } from "./icns.ts";
@@ -349,11 +351,27 @@ const readImageDimensionsFromHeader = (filePath: string) =>
349351
const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
350352
function* (input: {
351353
readonly requestedPath: string;
354+
readonly workspaceRoot: string | undefined;
352355
readonly resource: AssetResource;
353356
readonly expiresAt: number;
354357
}) {
355358
const path = yield* Path.Path;
356-
const canonicalFile = yield* resolveCanonicalFile(input.requestedPath).pipe(
359+
// Resolving a network path makes Windows sign in to its host with the
360+
// user's NTLM credentials, so only the thread's own project may be on a share.
361+
// Windows reads a `\\?\` path as written, `..` included, so the lookup gets
362+
// the resolved path this check approved.
363+
const requestedPath = path.resolve(input.requestedPath);
364+
if (
365+
isNetworkPath(input.requestedPath) &&
366+
(input.workspaceRoot === undefined ||
367+
!isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
368+
) {
369+
return yield* new AssetWorkspaceAssetNotFoundError({
370+
resource: input.resource,
371+
checkedPath: input.requestedPath,
372+
});
373+
}
374+
const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
357375
Effect.mapError(
358376
(cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
359377
),
@@ -524,6 +542,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
524542
}
525543
const finalized = yield* finalizeAbsoluteMediaFileAsset({
526544
requestedPath,
545+
workspaceRoot: input.workspaceRoot,
527546
resource: input.resource,
528547
expiresAt,
529548
});
@@ -566,6 +585,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
566585
if (path.isAbsolute(hostPath)) {
567586
const finalized = yield* finalizeAbsoluteMediaFileAsset({
568587
requestedPath: hostPath,
588+
workspaceRoot: draftWorkspaceRoot,
569589
resource: input.resource,
570590
expiresAt,
571591
});

‎apps/server/src/storageCleanup.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1299,6 +1299,36 @@ describe("storage cleanup reports and local file policies", () => {
12991299
}),
13001300
),
13011301
);
1302+
// An agent can write this manifest. Statting its store sent the Windows
1303+
// user's NTLM credentials to attacker.test during a background sweep.
1304+
it.live.each([
1305+
{ storeDir: "\\\\attacker.test\\s" },
1306+
{ storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" },
1307+
])("never stats a network pnpm store %o", (manifest) =>
1308+
runCleanupTest(
1309+
Effect.gen(function* () {
1310+
const fs = yield* FileSystem.FileSystem;
1311+
const statted: Array<string> = [];
1312+
const { service, worktree, setPolicy } = yield* cleanupFixture().pipe(
1313+
Effect.provideService(FileSystem.FileSystem, {
1314+
...fs,
1315+
stat: (target) => {
1316+
statted.push(target);
1317+
return fs.stat(target);
1318+
},
1319+
}),
1320+
);
1321+
setPolicy("tracked-changes");
1322+
yield* fs.makeDirectory(`${worktree}/node_modules`);
1323+
yield* fs.writeFileString(
1324+
`${worktree}/node_modules/.modules.yaml`,
1325+
JSON.stringify(manifest),
1326+
);
1327+
expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
1328+
expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]);
1329+
}),
1330+
),
1331+
);
13021332
it.live("still removes a worktree when measuring its size fails", () =>
13031333
runCleanupTest(
13041334
Effect.gen(function* () {

‎apps/server/src/storageCleanup.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
5050
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
5151
import * as HostProcess from "@t3tools/shared/HostProcess";
5252
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
53+
import { isNetworkPath } from "@t3tools/shared/path";
5354

5455
const decodeCleanupThread = Schema.decodeUnknownEffect(
5556
Schema.fromJsonString(OrchestrationV2AppThreadJson),
@@ -265,6 +266,11 @@ const make = Effect.gen(function* () {
265266
const nodeModules = path.join(root, "node_modules");
266267
const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml"));
267268
const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text)));
269+
// An agent can write this manifest, and statting a network path makes
270+
// Windows sign in to its host with the user's NTLM credentials.
271+
if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) {
272+
return null;
273+
}
268274
const virtualStore = path.resolve(nodeModules, manifest.virtualStoreDir ?? ".pnpm");
269275
const [store, virtual] = yield* Effect.all([
270276
fs.stat(manifest.storeDir),

‎apps/server/src/workspace/WorkspaceFileSystem.test.ts‎

Lines changed: 100 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO.
1+
// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath.
22
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeFSP from "node:fs/promises";
34

5+
import * as NodePath from "@effect/platform-node/NodePath";
46
import * as NodeServices from "@effect/platform-node/NodeServices";
57
import { it, describe, expect } from "@effect/vitest";
68
import * as Effect from "effect/Effect";
@@ -17,6 +19,12 @@ import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
1719
import * as WorkspacePaths from "./WorkspacePaths.ts";
1820
import * as HostProcess from "@t3tools/shared/HostProcess";
1921
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
22+
import { vi } from "vite-plus/test";
23+
24+
vi.mock("node:fs/promises", async (importOriginal) => {
25+
const actual = await importOriginal<typeof NodeFSP>();
26+
return { ...actual, realpath: vi.fn(actual.realpath) };
27+
});
2028

2129
// Temp folders count as known workspaces unless named as unknown.
2230
const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
@@ -123,6 +131,35 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
123131
]);
124132
}),
125133
);
134+
135+
// A file chip for `file://attacker.test/s/a.ts` in an agent's message sent
136+
// the Windows user's NTLM credentials to attacker.test as it rendered.
137+
it.effect("never stats a network path", () =>
138+
Effect.gen(function* () {
139+
const fs = yield* FileSystem.FileSystem;
140+
const statted: Array<string> = [];
141+
const service = yield* WorkspaceFileSystem.make.pipe(
142+
Effect.provideService(
143+
FileSystem.FileSystem,
144+
FileSystem.FileSystem.of({
145+
...fs,
146+
stat: (requestedPath) => {
147+
statted.push(requestedPath);
148+
return fs.stat(requestedPath);
149+
},
150+
}),
151+
),
152+
Effect.provide(layerKnownWorkspacesTest),
153+
);
154+
const paths = [
155+
"\\\\attacker.test\\s\\a.ts",
156+
"//attacker.test/s/a.ts",
157+
"/\\attacker.test\\s",
158+
];
159+
expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]);
160+
expect(statted).toEqual([]);
161+
}),
162+
);
126163
});
127164

128165
describe("readFile", () => {
@@ -199,6 +236,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
199236
}),
200237
);
201238

239+
it.effect("refuses a network path outside the workspace", () =>
240+
Effect.gen(function* () {
241+
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
242+
243+
const error = yield* workspaceFileSystem
244+
.readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
245+
.pipe(Effect.flip);
246+
247+
expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
248+
}),
249+
);
250+
251+
// This resolves inside the project, but Windows reads `\\?\` paths as
252+
// written, so realpath on the raw string signed in to attacker.test.
253+
it.effect("reads the network path it checked", () =>
254+
Effect.gen(function* () {
255+
const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
256+
Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
257+
);
258+
// Rejects without touching the filesystem, so a Windows runner never looks the share up.
259+
const realpath = vi
260+
.mocked(NodeFSP.realpath)
261+
.mockClear()
262+
.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
263+
264+
yield* workspaceFileSystem
265+
.readFile({
266+
cwd: "\\\\?\\UNC\\nas.test\\share\\project",
267+
relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
268+
})
269+
.pipe(Effect.exit);
270+
271+
expect(realpath.mock.calls.map(([target]) => target)).toEqual([
272+
"\\\\?\\UNC\\nas.test\\share\\project\\a.md",
273+
]);
274+
}),
275+
);
276+
277+
// Resolving `..` before realpath would read beside the link instead of its target.
278+
// Windows collapses `..` before the filesystem sees a path, so it has no such reads.
279+
it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
280+
"reads `..` after a link from the link's target",
281+
() =>
282+
Effect.gen(function* () {
283+
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
284+
const fs = yield* FileSystem.FileSystem;
285+
const path = yield* Path.Path;
286+
const root = yield* makeTempDir;
287+
yield* writeTextFile(root, "target/parent.md", "beside the target\n");
288+
yield* writeTextFile(root, "parent.md", "beside the link\n");
289+
yield* fs.makeDirectory(path.join(root, "target", "child"));
290+
yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
291+
292+
const result = yield* workspaceFileSystem.readFile({
293+
cwd: root,
294+
relativePath: `${root}/link/../parent.md`,
295+
});
296+
297+
expect(result.contents).toBe("beside the target\n");
298+
}),
299+
);
300+
202301
it.effect.skipIf(!symlinksSupported)(
203302
"rejects symlinks that resolve outside the workspace root",
204303
() =>

‎apps/server/src/workspace/WorkspaceFileSystem.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
} from "@t3tools/contracts";
1414
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
1515
import * as HostProcess from "@t3tools/shared/HostProcess";
16+
import { isNetworkPath } from "@t3tools/shared/path";
1617
import * as Context from "effect/Context";
1718
import * as Effect from "effect/Effect";
1819
import * as FileSystem from "effect/FileSystem";
@@ -142,7 +143,9 @@ export const make = Effect.gen(function* () {
142143

143144
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
144145
const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
145-
if (!path.isAbsolute(expandedPath)) return null;
146+
// Chips ask as soon as an agent's message renders, and touching a network
147+
// path makes Windows sign in to its host with the user's NTLM credentials.
148+
if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null;
146149
const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
147150
if (stat._tag === "None") return null;
148151
if (stat.value.type === "Directory") return { kind: "directory" } as const;
@@ -222,7 +225,8 @@ export const make = Effect.gen(function* () {
222225
/**
223226
* Workspace-relative paths must stay inside the root, symlinks included. An
224227
* absolute or `~/` path reads a host file in place, such as a report an agent
225-
* wrote to a temp directory; it gets no root check.
228+
* wrote to a temp directory; it gets no root check. A network path does, since
229+
* Windows signs in to its host with the user's NTLM credentials.
226230
*/
227231
const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
228232
input: ProjectReadFileInput,
@@ -231,15 +235,28 @@ export const make = Effect.gen(function* () {
231235
const hostPath = requestedPath.startsWith("~/")
232236
? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
233237
: requestedPath;
238+
if (
239+
isNetworkPath(hostPath) &&
240+
!KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd))
241+
) {
242+
return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
243+
workspaceRoot: input.cwd,
244+
relativePath: input.relativePath,
245+
});
246+
}
234247
if (path.isAbsolute(hostPath)) {
248+
// Native realpath hands Windows a `\\?\` path as written, `..` included,
249+
// so a network path must be the resolved one the check above approved.
250+
// Others keep POSIX `link/..` semantics, which resolving first would change.
251+
const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath;
235252
const realTargetPath = yield* Effect.tryPromise({
236-
try: () => NodeFSP.realpath(hostPath),
253+
try: () => NodeFSP.realpath(absolutePath),
237254
catch: (cause) =>
238255
new WorkspaceFileSystemOperationError({
239256
workspaceRoot: input.cwd,
240257
relativePath: input.relativePath,
241-
resolvedPath: hostPath,
242-
operationPath: hostPath,
258+
resolvedPath: absolutePath,
259+
operationPath: absolutePath,
243260
operation: "realpath-target",
244261
cause,
245262
}),

‎apps/server/src/ws.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
246246
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
247247
import * as SessionStore from "./auth/SessionStore.ts";
248248
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
249+
import { isNetworkPath } from "@t3tools/shared/path";
249250
import * as RelayClient from "@t3tools/shared/relayClient";
250251
import { isTelemetryIdHash } from "@t3tools/shared/telemetryId";
251252
import {
@@ -2721,7 +2722,10 @@ export const layerWsRpc = (
27212722
input.resource._tag === "native-app-icon" ||
27222723
input.resource._tag === "tool-output-image" ||
27232724
input.resource._tag === "github-media" ||
2724-
(input.resource._tag === "media-file" && path.isAbsolute(input.resource.path))
2725+
// A network path is served only from the thread's project, looked up below.
2726+
(input.resource._tag === "media-file" &&
2727+
path.isAbsolute(input.resource.path) &&
2728+
!isNetworkPath(input.resource.path))
27252729
) {
27262730
return yield* issueAssetUrl({ resource: input.resource });
27272731
}

0 commit comments

Comments
 (0)