Skip to content

Commit c85d6ab

Browse files
committed
fix(pull-requests): don't check out a PR into a project that only lent its credentials
A PR whose repository matches no local checkout (a renamed or transferred repository, or a link to a repository that isn't checked out here) is read through the first project on its host. Resolve, Fix and Checkout then treated that donor as the PR's project, so the worktree, the setup script and the task landed in an unrelated repository. The server now marks a borrowed route with `borrowedProject` on summary and detail, and both hand-off paths refuse the checkout with a message naming the repository. Fixes #16455
1 parent d60a71e commit c85d6ab

6 files changed

Lines changed: 129 additions & 4 deletions

File tree

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2243,10 +2243,52 @@ it.effect("routes a hosted reference to another repository through a project on
22432243
);
22442244

22452245
assert.strictEqual(summary.number, 7);
2246+
assert.strictEqual(summary.borrowedProject, true);
22462247
assert.deepStrictEqual(seen, [{ cwd: "/web", repository: "acme/api", host: "github.com" }]);
22472248
}),
22482249
);
22492250

2251+
it.effect("reports a borrowed project so hand-offs do not check out into it", () =>
2252+
Effect.gen(function* () {
2253+
const service = yield* makeService({
2254+
// The unrelated project comes first, which is the one the host fallback lends.
2255+
projects: [
2256+
project({
2257+
id: "unrelated",
2258+
title: "unrelated",
2259+
workspaceRoot: "/unrelated",
2260+
repository: "acme/unrelated",
2261+
}),
2262+
project({ id: "app", title: "app", workspaceRoot: "/app", repository: "acme/app" }),
2263+
],
2264+
providers: [
2265+
fakeProvider("github", {
2266+
getChangeRequest: () => Effect.succeed(hostedChangeRequest("Description")),
2267+
}),
2268+
],
2269+
});
2270+
2271+
// A link recorded before the repository was renamed matches no checkout, so the read borrows.
2272+
const renamed = yield* service.detail({
2273+
projectId: "app" as ProjectId,
2274+
host: "github.com",
2275+
repository: "old-org/app",
2276+
number: 1,
2277+
});
2278+
assert.strictEqual(renamed.projectId, "unrelated");
2279+
assert.strictEqual(renamed.borrowedProject, true);
2280+
2281+
const own = yield* service.detail({
2282+
projectId: "app" as ProjectId,
2283+
host: "github.com",
2284+
repository: "acme/app",
2285+
number: 1,
2286+
});
2287+
assert.strictEqual(own.projectId, "app");
2288+
assert.strictEqual(own.borrowedProject, undefined);
2289+
}),
2290+
);
2291+
22502292
it.effect("routes Azure reads and writes through the requested organization's checkout", () =>
22512293
Effect.gen(function* () {
22522294
const seen: string[] = [];

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,8 @@ export interface SupportedProject {
324324
* Unique where `repository` is not: Azure's is a bare name that repeats across an organisation.
325325
*/
326326
readonly remote: string;
327+
/** Set when this project only lends its credentials to a repository it is not a checkout of. */
328+
readonly borrowed?: true;
327329
}
328330

329331
/**
@@ -385,6 +387,15 @@ function parseListCursor(raw: string): ListCursor | null {
385387
};
386388
}
387389

390+
/** A held summary, minus the routing answer a fresher read decides again. */
391+
function withoutBorrowedProject(
392+
summary: PullRequestSummary | undefined,
393+
): Omit<PullRequestSummary, "borrowedProject"> | undefined {
394+
if (summary?.borrowedProject === undefined) return summary;
395+
const { borrowedProject: _borrowedProject, ...rest } = summary;
396+
return rest;
397+
}
398+
388399
/**
389400
* How a listing tells two repositories apart. The host is part of it because the same
390401
* `owner/repo` exists on github.com and on an Enterprise install, and they are two repositories.
@@ -889,6 +900,7 @@ export const make = Effect.gen(function* () {
889900
...route,
890901
repository,
891902
remote: normalizeGitRemoteUrl(`https://${host}/${repository}`),
903+
borrowed: true,
892904
},
893905
);
894906
}),
@@ -1593,6 +1605,7 @@ export const make = Effect.gen(function* () {
15931605
Effect.map(({ value: changeRequest, observedAt }): PullRequestSummary => ({
15941606
provider: project.api.kind,
15951607
projectId: project.project.id,
1608+
...(project.borrowed ? { borrowedProject: true } : {}),
15961609
repository: project.repository,
15971610
number: changeRequest.number,
15981611
title: changeRequest.title,
@@ -1686,6 +1699,7 @@ export const make = Effect.gen(function* () {
16861699
projectId: project.project.id,
16871700
projectTitle: project.project.title,
16881701
workspaceRoot: project.project.workspaceRoot,
1702+
...(project.borrowed ? { borrowedProject: true } : {}),
16891703
repository: project.repository,
16901704
number: changeRequest.number,
16911705
title: changeRequest.title,
@@ -2945,9 +2959,10 @@ export const make = Effect.gen(function* () {
29452959
previous: PullRequestSummary | undefined,
29462960
): PullRequestSummary => ({
29472961
// Detail does not carry review/check summaries. Keep the last summary observation.
2948-
...previous,
2962+
...withoutBorrowedProject(previous),
29492963
provider: detail.provider,
29502964
projectId: detail.projectId,
2965+
...(detail.borrowedProject ? { borrowedProject: true } : {}),
29512966
repository: detail.repository,
29522967
number: detail.number,
29532968
title: detail.title,

‎apps/web/src/components/pullRequest/PullRequestDetailPanel.test.tsx‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ vi.mock("~/state/pullRequests", async (importOriginal) => ({
5050
vi.mock("~/state/vcs", () => ({ vcsEnvironment: { listRefs: () => null } }));
5151
vi.mock("~/state/query", () => ({
5252
useEnvironmentQuery: (query: string) => ({
53-
data: query === "detail" ? detail : null,
53+
data: query === "detail" ? servedDetail : null,
5454
isPending: false,
5555
isSuccess: true,
5656
error: null,
@@ -141,6 +141,7 @@ vi.mock("./PullRequestCodeTab", () => ({
141141
),
142142
}));
143143

144+
import { toastManager } from "../ui/toast";
144145
import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
145146
import { pullRequestPanelContext } from "./pullRequestDetail.logic";
146147

@@ -196,6 +197,8 @@ const detail: PullRequestDetailView = {
196197
},
197198
};
198199

200+
let servedDetail = detail;
201+
199202
const threadRef: ScopedThreadRef = {
200203
environmentId: EnvironmentId.make("env-1"),
201204
threadId: ThreadId.make("thread-1"),
@@ -208,6 +211,8 @@ beforeEach(() => {
208211
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
209212
vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
210213
useComposerDraftStore.setState({ draftsByThreadKey: {} });
214+
servedDetail = detail;
215+
vi.mocked(toastManager.add).mockClear();
211216
newThread
212217
.mockReset()
213218
.mockResolvedValue({ draftId: newDraftId, threadId: ThreadId.make("new-thread") });
@@ -336,3 +341,36 @@ describe.each([
336341
}
337342
});
338343
});
344+
345+
describe("a pull request read through another project's credentials", () => {
346+
it.each(["Resolve conflicts", "In a separate worktree"])(
347+
"%s does not check out into the project that lent them",
348+
async (action) => {
349+
servedDetail = { ...detail, borrowedProject: true };
350+
await act(async () => {
351+
renderer = create(
352+
<PullRequestDetailPanel
353+
environmentId={threadRef.environmentId}
354+
reference={detail}
355+
context="page"
356+
shortcutsEnabled={false}
357+
getShortcutContext={() => ({
358+
terminalFocus: false,
359+
terminalOpen: false,
360+
previewFocus: false,
361+
previewOpen: false,
362+
isWeb: true,
363+
isDesktop: false,
364+
})}
365+
/>,
366+
);
367+
});
368+
await click(action);
369+
expect(newThread).not.toHaveBeenCalled();
370+
expect(prepareThread).not.toHaveBeenCalled();
371+
expect(toastManager.add).toHaveBeenCalledWith(
372+
expect.objectContaining({ type: "error", title: "No checkout of this repository" }),
373+
);
374+
},
375+
);
376+
});

‎apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ import {
166166
writePullRequestDetailSnapshot,
167167
} from "./pullRequestDetail.logic";
168168
import { canEditPullRequestChangeRequest } from "./pullRequestEditing.logic";
169+
import { refuseBorrowedCheckout } from "./usePullRequestActions";
169170
import {
170171
resolvePickableEnvironments,
171172
type PickableEnvironment,
@@ -1197,7 +1198,7 @@ export function PullRequestDetailPanel({
11971198
});
11981199
return;
11991200
}
1200-
if (checkoutRoot === null) return;
1201+
if (checkoutRoot === null || refuseBorrowedCheckout(handoffSummary)) return;
12011202
setHandoff(kind);
12021203
// The menu closes on the press and takes its "Preparing..." label with it, so this is the
12031204
// only thing answering for the checkout. It carries no timeout of its own: a loading toast

‎apps/web/src/components/pullRequest/usePullRequestActions.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type {
1212
PullRequestDetail,
1313
PullRequestMergeMethod,
1414
PullRequestRef,
15+
PullRequestSummary,
1516
} from "@t3tools/contracts";
1617
import { useState } from "react";
1718

@@ -124,9 +125,26 @@ export interface PullRequestThreadTask {
124125
/** What a hand-off needs to know about the pull request it is handing over. */
125126
export type PullRequestHandoffDetail = Pick<
126127
PullRequestDetail,
127-
"projectId" | "workspaceRoot" | "url"
128+
"projectId" | "workspaceRoot" | "url" | "repository" | "borrowedProject"
128129
>;
129130

131+
/**
132+
* Stops a checkout when the pull request was only read through another project's credentials.
133+
* That project is not a checkout of the pull request's repository, so the branch, its worktree and
134+
* the task would all land in an unrelated repository while the hand-off reported success.
135+
*/
136+
export function refuseBorrowedCheckout(
137+
pullRequest: Pick<PullRequestSummary, "repository" | "borrowedProject">,
138+
): boolean {
139+
if (pullRequest.borrowedProject !== true) return false;
140+
toastManager.add({
141+
type: "error",
142+
title: "No checkout of this repository",
143+
description: `No project here is a checkout of ${pullRequest.repository}. Add it as a project, then try again from there.`,
144+
});
145+
return true;
146+
}
147+
130148
/**
131149
* What the last hand-off wrote into each draft, kept outside React because the panel that wrote it
132150
* is closed by the time the next one opens. It is how a prompt the reader has since edited is told
@@ -239,6 +257,7 @@ export function usePullRequestHandoffs({
239257
mode: "worktree" | "local" = "worktree",
240258
) => {
241259
if (!detail || handoff !== null) return;
260+
if (refuseBorrowedCheckout(detail)) return;
242261
setHandoff(kind);
243262
// The menu closes on the press and takes its "Preparing..." label with it, so this is the
244263
// only thing answering for the checkout. It carries no timeout of its own: a loading toast

‎packages/contracts/src/pullRequest.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,11 @@ export type PullRequestPreview = typeof PullRequestPreview.Type;
728728
export const PullRequestSummary = Schema.Struct({
729729
provider: SourceControlProviderKind,
730730
projectId: ProjectId,
731+
/**
732+
* Present when no project here is a checkout of `repository`: `projectId` only lent its
733+
* credentials for the read, so nothing about this pull request should be checked out there.
734+
*/
735+
borrowedProject: Schema.optional(Schema.Boolean),
731736
repository: TrimmedNonEmptyString,
732737
number: PositiveInt,
733738
title: TrimmedNonEmptyString,
@@ -832,6 +837,11 @@ export const PullRequestDetail = Schema.Struct({
832837
projectId: ProjectId,
833838
projectTitle: TrimmedNonEmptyString,
834839
workspaceRoot: TrimmedNonEmptyString,
840+
/**
841+
* Present when no project here is a checkout of `repository`: `projectId` only lent its
842+
* credentials for the read, so nothing about this pull request should be checked out there.
843+
*/
844+
borrowedProject: Schema.optional(Schema.Boolean),
835845
repository: TrimmedNonEmptyString,
836846
number: PositiveInt,
837847
title: TrimmedNonEmptyString,

0 commit comments

Comments
 (0)