Skip to content

Commit 19e6229

Browse files
committed
fix(workspace): bound conditional reads and preserve PR host validation (#11251)
1 parent 1637192 commit 19e6229

4 files changed

Lines changed: 154 additions & 12 deletions

File tree

‎apps/server/src/pullRequest/PullRequestService.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4748,6 +4748,66 @@ it.effect("keeps scoped summary, activity, diff and stats reads in their checkou
47484748
}),
47494749
);
47504750

4751+
for (const validHost of [undefined, "GITHUB.COM"] as const) {
4752+
it.effect(
4753+
`keeps mismatched scoped stats hosts out of reads and caches (${validHost ?? "implicit"})`,
4754+
() =>
4755+
Effect.gen(function* () {
4756+
const reads: string[] = [];
4757+
const service = yield* makeService({
4758+
projects: [project({ id: "p1", title: "wrapper", workspaceRoot: "/wrapper" })],
4759+
threads: [scopedThread],
4760+
repositories: () => [
4761+
{
4762+
path: "projects/app",
4763+
name: "app",
4764+
cwd: "/task/projects/app",
4765+
kind: "repository",
4766+
available: true,
4767+
repositoryIdentity: appIdentity,
4768+
},
4769+
],
4770+
providers: [
4771+
fakeProvider("github", {
4772+
listChangeRequestStats: ({ host, changeRequests }) => {
4773+
reads.push(host);
4774+
return Effect.succeed(
4775+
changeRequests.map(({ repository, number }) => ({
4776+
repository,
4777+
number,
4778+
additions: 10,
4779+
deletions: 2,
4780+
})),
4781+
);
4782+
},
4783+
}),
4784+
],
4785+
});
4786+
const invalid = { ...scopedRef, host: "other.example" };
4787+
const valid = { ...scopedRef, ...(validHost === undefined ? {} : { host: validHost }) };
4788+
assert.deepStrictEqual(yield* service.listStats({ refs: [invalid] }), { stats: [] });
4789+
assert.deepStrictEqual(reads, []);
4790+
const expected = {
4791+
stats: [
4792+
{
4793+
projectId: scopedRef.projectId,
4794+
repository: scopedRef.repository,
4795+
number: scopedRef.number,
4796+
workspace: scopedRef.workspace,
4797+
additions: 10,
4798+
deletions: 2,
4799+
},
4800+
],
4801+
};
4802+
assert.deepStrictEqual(yield* service.listStats({ refs: [invalid, valid] }), expected);
4803+
assert.deepStrictEqual(yield* service.listStats({ refs: [invalid] }), { stats: [] });
4804+
assert.deepStrictEqual(yield* service.listStats({ refs: [valid] }), expected);
4805+
assert.deepStrictEqual(yield* service.listStats({ refs: [valid, invalid] }), expected);
4806+
assert.deepStrictEqual(reads, ["github.com"]);
4807+
}),
4808+
);
4809+
}
4810+
47514811
it.effect("publishes child repository merges with their workspace scope", () =>
47524812
Effect.scoped(
47534813
Effect.gen(function* () {

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2146,6 +2146,11 @@ export const make = Effect.gen(function* () {
21462146
}),
21472147
);
21482148

2149+
// The public stats omit host, but cache recording must retain the reference that passed validation.
2150+
type ValidatedPullRequestDiffStat = PullRequestDiffStat & {
2151+
readonly requestedHost?: string | null;
2152+
};
2153+
21492154
/**
21502155
* The line counts for rows already on the page, which the listing left out because on GitHub
21512156
* they cost more than everything else on the row put together.
@@ -2156,7 +2161,14 @@ export const make = Effect.gen(function* () {
21562161
* remote points at, is dropped rather than refused: it is one row's two numbers, and the page
21572162
* that asked has already moved on.
21582163
*/
2159-
const listStatsUncached: PullRequestService["Service"]["listStats"] = (input) =>
2164+
const listStatsUncached = (
2165+
input: PullRequestListStatsInput,
2166+
): Effect.Effect<
2167+
{
2168+
readonly stats: ReadonlyArray<ValidatedPullRequestDiffStat>;
2169+
},
2170+
PullRequestError
2171+
> =>
21602172
Effect.gen(function* () {
21612173
if (input.refs.length === 0) return { stats: [] };
21622174
const scoped = input.refs.filter((ref) => ref.workspace !== undefined);
@@ -2217,6 +2229,7 @@ export const make = Effect.gen(function* () {
22172229
...stat,
22182230
projectId: ref.projectId,
22192231
workspace: ref.workspace,
2232+
requestedHost: ref.host?.trim().toLowerCase() ?? null,
22202233
}))
22212234
: [],
22222235
),
@@ -2776,11 +2789,14 @@ export const make = Effect.gen(function* () {
27762789
(key: string) => {
27772790
const [, refs] = JSON.parse(key) as [
27782791
number,
2779-
ReadonlyArray<[string, string, number, number, PullRequestRef["workspace"] | null]>,
2792+
ReadonlyArray<
2793+
[string, string | null, string, number, number, PullRequestRef["workspace"] | null]
2794+
>,
27802795
];
27812796
return listStatsUncached({
2782-
refs: refs.map(([projectId, repository, number, , workspace]) => ({
2797+
refs: refs.map(([projectId, host, repository, number, , workspace]) => ({
27832798
projectId,
2799+
...(host === null ? {} : { host }),
27842800
repository,
27852801
number,
27862802
...(workspace ? { workspace } : {}),
@@ -2804,15 +2820,14 @@ export const make = Effect.gen(function* () {
28042820
(ref) =>
28052821
[
28062822
ref.projectId,
2823+
ref.host?.trim().toLowerCase() ?? null,
28072824
ref.repository,
28082825
ref.number,
28092826
refEpoch(ref),
28102827
ref.workspace ?? null,
28112828
] as const,
28122829
)
2813-
.toSorted((left, right) =>
2814-
`${left[0]} ${left[1]} ${left[2]}`.localeCompare(`${right[0]} ${right[1]} ${right[2]}`),
2815-
),
2830+
.toSorted((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right))),
28162831
]);
28172832
// Exact batches share in-flight reads; overlapping pages reuse each row already fetched.
28182833
const listStats: PullRequestService["Service"]["listStats"] = Effect.fn(
@@ -2840,11 +2855,24 @@ export const make = Effect.gen(function* () {
28402855
stat.projectId === ref.projectId &&
28412856
stat.repository.toLowerCase() === ref.repository.toLowerCase() &&
28422857
stat.number === ref.number &&
2843-
JSON.stringify(stat.workspace ?? null) === JSON.stringify(ref.workspace ?? null),
2858+
JSON.stringify(stat.workspace ?? null) === JSON.stringify(ref.workspace ?? null) &&
2859+
(ref.workspace === undefined ||
2860+
stat.requestedHost === (ref.host?.trim().toLowerCase() ?? null)),
28442861
);
2845-
if (stat !== undefined) recordStats(key, stat, at);
2862+
if (stat !== undefined) {
2863+
const { requestedHost: _, ...value } = stat;
2864+
recordStats(key, value, at);
2865+
}
28462866
}
2847-
return { stats: [...held, ...result.stats] };
2867+
return {
2868+
stats: [
2869+
...held,
2870+
...result.stats.map((stat) => {
2871+
const { requestedHost: _, ...value } = stat;
2872+
return value;
2873+
}),
2874+
],
2875+
};
28482876
});
28492877

28502878
const invalidate: PullRequestService["Service"]["invalidate"] = (input) => {

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,53 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
284284
}),
285285
);
286286

287+
it.effect("rejects a truncated matching prefix without changing the oversized file", () =>
288+
Effect.gen(function* () {
289+
const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;
290+
const fileSystem = yield* FileSystem.FileSystem;
291+
const path = yield* Path.Path;
292+
const cwd = yield* makeTempDir;
293+
const prefix = "a".repeat(1024 * 1024);
294+
const original = `${prefix}extra bytes`;
295+
yield* writeTextFile(cwd, "large.txt", original);
296+
const error = yield* files
297+
.writeFile({
298+
cwd,
299+
relativePath: "large.txt",
300+
contents: "replacement",
301+
expectedContents: prefix,
302+
})
303+
.pipe(Effect.flip);
304+
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileChangedError);
305+
expect(yield* fileSystem.readFileString(path.join(cwd, "large.txt"))).toBe(original);
306+
}),
307+
);
308+
it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
309+
"rejects conditional writes to a FIFO without blocking",
310+
() =>
311+
Effect.gen(function* () {
312+
const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;
313+
const path = yield* Path.Path;
314+
const cwd = yield* makeTempDir;
315+
yield* Effect.promise(
316+
() =>
317+
new Promise<void>((resolve, reject) =>
318+
NodeChildProcess.execFile("mkfifo", [path.join(cwd, "pipe")], (error) =>
319+
error ? reject(error) : resolve(),
320+
),
321+
),
322+
);
323+
const error = yield* files
324+
.writeFile({
325+
cwd,
326+
relativePath: "pipe",
327+
contents: "replacement",
328+
expectedContents: null,
329+
})
330+
.pipe(Effect.flip);
331+
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
332+
}),
333+
);
287334
it.effect("conditionally creates missing files without overwriting a newly created file", () =>
288335
Effect.gen(function* () {
289336
const files = yield* WorkspaceFileSystem.WorkspaceFileSystem;

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ export class WorkspaceFileSystemOperationError extends Schema.TaggedError<Worksp
5656
}
5757
}
5858

59+
const isWorkspaceFileSystemOperationError = Schema.is(WorkspaceFileSystemOperationError);
60+
5961
export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
6062
"WorkspaceFilePathEscapeError",
6163
{
@@ -339,13 +341,18 @@ export const make = Effect.gen(function* () {
339341
.withPermits(1)(
340342
Effect.gen(function* () {
341343
if (input.expectedContents !== undefined) {
342-
const current = yield* fileSystem.readFileString(target.absolutePath).pipe(
344+
const current = yield* readFile(input).pipe(
343345
Effect.catchIf(
344-
(error) => error.reason._tag === "NotFound",
346+
(error) =>
347+
isWorkspaceFileSystemOperationError(error) &&
348+
(error.operation === "realpath-target" || error.operation === "open") &&
349+
error.cause instanceof Error &&
350+
"code" in error.cause &&
351+
error.cause.code === "ENOENT",
345352
() => Effect.succeed(null),
346353
),
347354
);
348-
if (current !== input.expectedContents) {
355+
if (current?.truncated || (current?.contents ?? null) !== input.expectedContents) {
349356
return yield* new WorkspaceFileChangedError({ relativePath: input.relativePath });
350357
}
351358
}

0 commit comments

Comments
 (0)