Skip to content
TypeScript

refactor(server): share a path check between file readers (#28041)

Theo Browne6eef6811c3d5
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index 11cb490901a..d2abfdcda34 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -644,6 +644,51 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect.skipIf(!symlinksSupported)("does not issue URLs for server state files", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const config = yield* ServerConfig.ServerConfig;
+ const stateFile = path.join(config.secretsDir, "example.bin");
+ yield* fs.makeDirectory(config.secretsDir, { recursive: true });
+ yield* fs.writeFile(stateFile, new Uint8Array(32).fill(7));
+ yield* fs.writeFileString(config.dbPath, "SQLite format 3");
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-state-" });
+ const alias = path.join(root, "alias");
+ yield* fs.symlink(stateFile, alias);
+ const threadId = ThreadId.make("thread-1");
+ for (const resource of [
+ { _tag: "media-file", threadId, path: stateFile, disposition: "attachment" },
+ { _tag: "media-file", threadId, path: alias, disposition: "attachment" },
+ {
+ _tag: "media-file",
+ threadId,
+ path: path.join(config.secretsDir, "..", "secrets", "example.bin"),
+ disposition: "attachment",
+ },
+ { _tag: "media-file", threadId, path: config.dbPath },
+ { _tag: "draft-workspace-file", cwd: config.stateDir, path: "statev2.sqlite" },
+ ] as const) {
+ const error = yield* issueAssetUrl({ resource }).pipe(Effect.flip);
+ expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
+ }
+
+ const icon = path.join(config.baseDir, "icon.png");
+ yield* fs.symlink(stateFile, icon);
+ yield* fs.writeFileString(path.join(config.baseDir, "page.html"), '<img src="icon.png">');
+ const page = yield* issueAssetUrl({
+ resource: { _tag: "draft-workspace-file", cwd: config.baseDir, path: "page.html" },
+ });
+ const pageToken = page.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length).split("/")[0]!;
+ expect(yield* resolveAsset(pageToken, "icon.png")).toBeNull();
+ const faviconError = yield* issueAssetUrl({
+ resource: { _tag: "project-favicon", cwd: root },
+ projectFaviconPath: icon,
+ }).pipe(Effect.flip);
+ expect(faviconError._tag).toBe("AssetProjectFaviconNotFoundError");
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect.skipIf(!symlinksSupported)(
"binds media URLs to the canonical target and rejects symlink substitution",
() =>
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index 8eb78946272..41f0d8e3a7e 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -54,6 +54,7 @@ import {
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
+import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
@@ -281,7 +282,9 @@ const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(funct
if (Option.isNone(canonicalFile)) return null;
const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile.value));
- return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
+ if (Option.isNone(info) || info.value.type !== "File") return null;
+ const isServerInternalPath = yield* makeIsServerInternalPath;
+ return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
});
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
@@ -309,7 +312,9 @@ const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWor
const info = yield* ProjectFaviconResolver.optionOnNotFound(
fileSystem.stat(canonicalFile.value),
);
- return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
+ if (Option.isNone(info) || info.value.type !== "File") return null;
+ const isServerInternalPath = yield* makeIsServerInternalPath;
+ return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
},
);
diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.ts
index 2f6b757abb1..023e57d68a7 100644
--- a/apps/server/src/auth/SessionStore.test.ts
+++ b/apps/server/src/auth/SessionStore.test.ts
@@ -357,7 +357,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect((yield* sessions.verify(uncapped.token)).runtimeModeCeiling).toBeUndefined();
}).pipe(Effect.provide(layerSessionStore())),
);
- it.effect("keeps recorded scopes unchanged for both token versions", () =>
+ it.effect("takes scopes from the session record", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const secrets = yield* ServerSecretStore.ServerSecretStore;
@@ -366,12 +366,19 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
const [encodedPayload] = issued.token.split(".");
const currentClaims = base64UrlDecodeUtf8(encodedPayload!);
expect(currentClaims).toContain('"v":1');
- const legacyPayload = base64UrlEncode(currentClaims.replace('"v":1', '"v":2'));
const secret = yield* secrets.getOrCreateRandom("server-signing-key", 32);
- const legacyToken = `${legacyPayload}.${signPayload(legacyPayload, secret)}`;
+ const resign = (claims: string) => {
+ const payload = base64UrlEncode(claims);
+ return `${payload}.${signPayload(payload, secret)}`;
+ };
+ const legacyToken = resign(currentClaims.replace('"v":1', '"v":2'));
+ const editedToken = resign(
+ currentClaims.replace(/"scopes":\[[^\]]*\]/, '"scopes":["access:write"]'),
+ );
expect((yield* sessions.verify(issued.token)).scopes).toEqual(legacyScopes);
expect((yield* sessions.verify(legacyToken)).scopes).toEqual(legacyScopes);
+ expect((yield* sessions.verify(editedToken)).scopes).toEqual(legacyScopes);
}).pipe(
Effect.provide(
SessionStore.layer.pipe(
diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts
index 51e0153c0ef..be4d1786126 100644
--- a/apps/server/src/auth/SessionStore.ts
+++ b/apps/server/src/auth/SessionStore.ts
@@ -840,7 +840,7 @@ const make = Effect.gen(function* () {
client: toClientMetadata(row.value.client),
expiresAt: expiresAt.value,
subject: claims.sub,
- scopes: claims.scopes,
+ scopes: row.value.scopes,
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
...(claims.plk === 1 ? { peerLink: true as const } : {}),
diff --git a/apps/server/src/auth/serverInternalPaths.ts b/apps/server/src/auth/serverInternalPaths.ts
new file mode 100644
index 00000000000..0c0cc295eda
--- /dev/null
+++ b/apps/server/src/auth/serverInternalPaths.ts
@@ -0,0 +1,29 @@
+// @effect-diagnostics nodeBuiltinImport:off - Effect's realPath keeps the requested letter case.
+import * as NodeFSP from "node:fs/promises";
+
+import * as Effect from "effect/Effect";
+import * as Path from "effect/Path";
+
+import * as ServerConfig from "../config.ts";
+import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
+
+/** Builds a check for the server's own state files, which client file reads do not serve. */
+export const makeIsServerInternalPath = Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const path = yield* Path.Path;
+ // Native realpath returns the on-disk letter case.
+ const realPath = (value: string) =>
+ Effect.promise(() => NodeFSP.realpath(value).catch(() => path.resolve(value)));
+ return Effect.fn("ServerInternalPaths.isServerInternalPath")(function* (filePath: string) {
+ const [file, stateDir, secretsDir] = yield* Effect.all(
+ [realPath(filePath), realPath(config.stateDir), realPath(config.secretsDir)],
+ { concurrency: "unbounded" },
+ );
+ return (
+ isWithinRoot(path, file, secretsDir) ||
+ (path.dirname(file) === stateDir && path.basename(file).includes(".sqlite")) ||
+ // macOS does not resolve `/dev/fd/N` to the open file's path.
+ isWithinRoot(path, file, "/dev/fd")
+ );
+ });
+});
diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts
index 421c240514e..de5a6f0c7ab 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.ts
@@ -51,6 +51,7 @@ import {
parseRemoteNamesInGitOrder,
parseRemoteRefWithRemoteNames,
} from "../git/remoteRefs.ts";
+import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
import * as ServerConfig from "../config.ts";
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
@@ -943,6 +944,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const { worktreesDir } = yield* ServerConfig.ServerConfig;
+ const isServerInternalPath = yield* makeIsServerInternalPath;
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcess.Platform;
const serviceScope = yield* Effect.scope;
@@ -3534,6 +3536,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
`Diff file '${input.newPath}' resolves outside the review workspace.`,
);
}
+ if (yield* isServerInternalPath(realTarget)) {
+ return yield* fileError("fs.realPath", `Diff file '${input.newPath}' is not available.`);
+ }
const info = yield* fileSystem
.stat(realTarget)
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
index 37d85a0fc68..63461314b50 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
@@ -45,7 +45,7 @@ const layerTest = Layer.empty.pipe(
Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
Layer.provideMerge(WorkspacePaths.layer),
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
- Layer.provide(
+ Layer.provideMerge(
ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-workspace-files-test-",
}),
@@ -206,6 +206,25 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
+ it.effect("does not read server state files", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const config = yield* ServerConfig.ServerConfig;
+ const path = yield* Path.Path;
+ const cwd = yield* makeTempDir;
+ yield* writeTextFile(config.secretsDir, "example.bin", "example\n");
+ yield* writeTextFile(config.stateDir, "statev2.sqlite", "example\n");
+
+ for (const input of [
+ { cwd, relativePath: path.join(config.secretsDir, "example.bin") },
+ { cwd: config.stateDir, relativePath: "statev2.sqlite" },
+ ]) {
+ const error = yield* workspaceFileSystem.readFile(input).pipe(Effect.flip);
+ expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
+ }
+ }),
+ );
+
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
"rejects a FIFO without blocking on open",
() =>
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts
index 053360572b3..ca617caac0e 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.ts
@@ -21,6 +21,7 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
import * as KnownWorkspaces from "./KnownWorkspaces.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
@@ -139,6 +140,7 @@ export const make = Effect.gen(function* () {
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
+ const isServerInternalPath = yield* makeIsServerInternalPath;
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
@@ -347,6 +349,12 @@ export const make = Effect.gen(function* () {
};
const realTargetPath = target.realTargetPath;
if (realTargetPath === null) return absentResult;
+ if (yield* isServerInternalPath(realTargetPath)) {
+ return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ });
+ }
return yield* Effect.acquireUseRelease(
Effect.tryPromise({