Skip to content

Commit 34ebe0e

Browse files
committed
feat(github): route pull request operations across matching accounts
1 parent 25da986 commit 34ebe0e

17 files changed

Lines changed: 1106 additions & 95 deletions

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ export const RPC_REQUIRED_SCOPES = {
6868
[WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
6969
[WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
7070
[WS_METHODS.pullRequestsSummary]: AuthOrchestrationReadScope,
71+
[WS_METHODS.pullRequestsRouting]: AuthOrchestrationReadScope,
7172
[WS_METHODS.pullRequestsStack]: AuthOrchestrationReadScope,
7273
[WS_METHODS.pullRequestsLinkedThreads]: AuthOrchestrationReadScope,
7374
[WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,

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

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2458,12 +2458,79 @@ layer("GitHubPullRequestCli.layer", (it) => {
24582458
mockedExecute.mockReturnValueOnce(Effect.succeed(output(" ")));
24592459
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
24602460

2461-
const error = yield* Effect.flip(cli.getViewerLogin({ cwd: "/w" }));
2461+
const error = yield* Effect.flip(cli.getViewerLogin({ cwd: "/w", host: "github.com" }));
24622462

24632463
assert.strictEqual(error._tag, "GitHubViewerLoginUnavailableError");
24642464
}),
24652465
);
24662466

2467+
it.effect("looks up the authenticated account on the requested enterprise host", () =>
2468+
Effect.gen(function* () {
2469+
mockedExecute
2470+
.mockReturnValueOnce(Effect.succeed(output("enterprise-test-credential")))
2471+
.mockReturnValueOnce(Effect.succeed(output('{"id":456,"login":"enterprise-user"}')));
2472+
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
2473+
2474+
const login = yield* cli.getViewerLogin({ cwd: "/w", host: "github.acme.com" });
2475+
2476+
expect(login).toBe("enterprise-user");
2477+
expect(callAt(0).args).toEqual(["auth", "token", "--hostname", "github.acme.com"]);
2478+
expect(callAt(1).args).toEqual(["api", "user", "--hostname", "github.acme.com"]);
2479+
}),
2480+
);
2481+
2482+
it.effect("reuses verified credentials offline and refuses an unverified replacement", () =>
2483+
Effect.gen(function* () {
2484+
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
2485+
const input = { cwd: "/w", host: "github.identity-cache.test" };
2486+
mockedExecute
2487+
.mockReturnValueOnce(Effect.succeed(output("test-credential-a")))
2488+
.mockReturnValueOnce(Effect.succeed(output('{"id":123,"login":"maria-rcks"}')));
2489+
expect(yield* cli.getRoutingIdentity(input)).toEqual({
2490+
accountId: "123",
2491+
viewer: "maria-rcks",
2492+
});
2493+
expect(callAt(1).env).toMatchObject({
2494+
GH_ENTERPRISE_TOKEN: "test-credential-a",
2495+
GH_DEBUG: "",
2496+
});
2497+
2498+
mockedExecute.mockReturnValueOnce(Effect.succeed(output("test-credential-a")));
2499+
expect(yield* cli.getRoutingIdentity(input)).toEqual({
2500+
accountId: "123",
2501+
viewer: "maria-rcks",
2502+
});
2503+
expect(mockedExecute).toHaveBeenCalledTimes(3);
2504+
2505+
mockedExecute
2506+
.mockReturnValueOnce(Effect.succeed(output("test-credential-b")))
2507+
.mockReturnValueOnce(
2508+
Effect.fail(
2509+
new GitHubCli.GitHubCliCommandError({
2510+
command: "gh",
2511+
cwd: "/w",
2512+
cause: new Error("upstream failed with test-credential-b"),
2513+
}),
2514+
),
2515+
);
2516+
const failure = yield* cli.getRoutingIdentity(input).pipe(Effect.flip);
2517+
expect(failure._tag).toBe("GitHubViewerLoginUnavailableError");
2518+
expect(String(failure)).not.toContain("test-credential-b");
2519+
expect(callAt(4).env).toMatchObject({
2520+
GH_ENTERPRISE_TOKEN: "test-credential-b",
2521+
GH_DEBUG: "",
2522+
});
2523+
2524+
mockedExecute
2525+
.mockReturnValueOnce(Effect.succeed(output("test-credential-b")))
2526+
.mockReturnValueOnce(Effect.succeed(output('{"id":456,"login":"maria-rcks"}')));
2527+
expect(yield* cli.getRoutingIdentity(input)).toEqual({
2528+
accountId: "456",
2529+
viewer: "maria-rcks",
2530+
});
2531+
}),
2532+
);
2533+
24672534
it.effect("sends a whole review as one request body over stdin", () =>
24682535
Effect.gen(function* () {
24692536
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));

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

Lines changed: 71 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import { runGitHubStackAction, type GitHubStackActionError } from "./githubStackActions.ts";
22
import * as Context from "effect/Context";
3+
import * as Clock from "effect/Clock";
4+
import * as NodeCrypto from "node:crypto";
35
import * as Effect from "effect/Effect";
46
import * as Layer from "effect/Layer";
57
import * as Result from "effect/Result";
68
import * as Schema from "effect/Schema";
79
import {
810
resolvePullRequestAuthorFilter,
11+
PositiveInt,
12+
TrimmedNonEmptyString,
913
type PullRequestAction,
1014
type PullRequestStackHead,
1115
type PullRequestActor,
@@ -413,8 +417,16 @@ export interface GitHubPullRequestDiffSlice {
413417
export class GitHubPullRequestCli extends Context.Service<
414418
GitHubPullRequestCli,
415419
{
420+
readonly getRoutingIdentity: (input: {
421+
readonly cwd: string;
422+
readonly host: string;
423+
}) => Effect.Effect<
424+
{ readonly accountId: string; readonly viewer: string },
425+
GitHubPullRequestCliError
426+
>;
416427
readonly getViewerLogin: (input: {
417428
readonly cwd: string;
429+
readonly host: string;
418430
}) => Effect.Effect<string, GitHubPullRequestCliError>;
419431

420432
readonly listPullRequests: (input: {
@@ -991,6 +1003,63 @@ function actionArgs(
9911003
export const make = Effect.gen(function* () {
9921004
const github = yield* GitHubCli.GitHubCli;
9931005
const graphQlBudget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
1006+
const routingIdentities = new Map<
1007+
string,
1008+
{
1009+
at: number;
1010+
value: { accountId: string; viewer: string };
1011+
}
1012+
>();
1013+
const decodeRoutingIdentity = Schema.decodeUnknownEffect(
1014+
Schema.fromJsonString(
1015+
Schema.Struct({
1016+
id: PositiveInt,
1017+
login: TrimmedNonEmptyString,
1018+
}),
1019+
),
1020+
);
1021+
const getRoutingIdentity = Effect.fn("GitHubPullRequestCli.getRoutingIdentity")(
1022+
function* (input: { readonly cwd: string; readonly host: string }) {
1023+
const unavailable = () =>
1024+
new GitHubViewerLoginUnavailableError({ command: "gh", cwd: input.cwd });
1025+
const host = input.host.toLowerCase();
1026+
// Only the digest is retained. Never attach credential lookup output to an error.
1027+
const token = (yield* github
1028+
.execute({
1029+
cwd: input.cwd,
1030+
args: ["auth", "token", "--hostname", host],
1031+
env: { GH_DEBUG: "" },
1032+
})
1033+
.pipe(Effect.mapError(unavailable))).stdout.trim();
1034+
if (!token) return yield* unavailable();
1035+
const key = `${host}:${NodeCrypto.createHash("sha256").update(token).digest("hex")}`;
1036+
const now = yield* Clock.currentTimeMillis;
1037+
const cached = routingIdentities.get(key);
1038+
if (cached !== undefined && now - cached.at < 10 * 60_000) return cached.value;
1039+
// Pin this read to the captured credential so an auth switch cannot poison its cache entry.
1040+
const response = yield* github
1041+
.execute({
1042+
cwd: input.cwd,
1043+
args: ["api", "user", "--hostname", host],
1044+
env: {
1045+
GH_TOKEN: token,
1046+
GITHUB_TOKEN: token,
1047+
GH_ENTERPRISE_TOKEN: token,
1048+
GITHUB_ENTERPRISE_TOKEN: token,
1049+
GH_DEBUG: "",
1050+
},
1051+
})
1052+
.pipe(Effect.mapError(unavailable));
1053+
const identity = yield* decodeRoutingIdentity(response.stdout).pipe(
1054+
Effect.mapError(unavailable),
1055+
);
1056+
const value = { accountId: String(identity.id), viewer: identity.login };
1057+
if (routingIdentities.size >= 128)
1058+
routingIdentities.delete(routingIdentities.keys().next().value!);
1059+
routingIdentities.set(key, { at: now, value });
1060+
return value;
1061+
},
1062+
);
9941063

9951064
/**
9961065
* The pull request's own node id, which is what a mutation against the pull request itself is
@@ -1468,15 +1537,9 @@ export const make = Effect.gen(function* () {
14681537
);
14691538

14701539
return GitHubPullRequestCli.of({
1540+
getRoutingIdentity,
14711541
getViewerLogin: (input) =>
1472-
github.execute({ cwd: input.cwd, args: ["api", "user", "--jq", ".login"] }).pipe(
1473-
Effect.flatMap((result) => {
1474-
const login = result.stdout.trim();
1475-
return login.length > 0
1476-
? Effect.succeed(login)
1477-
: Effect.fail(new GitHubViewerLoginUnavailableError({ command: "gh", cwd: input.cwd }));
1478-
}),
1479-
),
1542+
getRoutingIdentity(input).pipe(Effect.map((identity) => identity.viewer)),
14801543

14811544
listPullRequests: (input) => {
14821545
const fallbackMaxRows = Math.max(input.limit + 1, PULL_REQUEST_FALLBACK_MAX_ROWS);

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,36 @@ it.effect("propagates workflow discovery rate limits", () =>
513513
);
514514

515515
describe("getViewerPermissions", () => {
516+
it.effect("checks fresh access without reading branch details for unrelated operations", () => {
517+
let accessReads = 0;
518+
return Effect.gen(function* () {
519+
const provider = yield* make;
520+
const permissions = yield* provider.getViewerPermissions({
521+
cwd: "/w",
522+
repository: "acme/web",
523+
host: "github.com",
524+
number: 7,
525+
includeUpdateBranch: false,
526+
});
527+
528+
expect(accessReads).toBe(1);
529+
expect(permissions.actions).toContain("merge");
530+
expect(permissions.actions).not.toContain("update-branch");
531+
}).pipe(
532+
Effect.provide(
533+
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
534+
getPullRequestDetail: () => Effect.die("Unexpected detail read"),
535+
getPullRequestBaseComparison: () => Effect.die("Unexpected comparison read"),
536+
getViewerAccess: () =>
537+
Effect.sync(() => {
538+
accessReads++;
539+
return { canWrite: true, canTriage: true, canUpdate: true, didAuthor: false };
540+
}),
541+
}),
542+
),
543+
);
544+
});
545+
516546
const layerWithComparison = (
517547
comparison: Effect.Effect<{
518548
readonly behindBy: number | null;

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

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -212,9 +212,13 @@ export const make = Effect.gen(function* () {
212212
const provider: PullRequestProviderApi = {
213213
kind: "github",
214214
capabilities: CAPABILITIES,
215+
getRoutingIdentity: (input) =>
216+
cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
215217

216218
getViewer: (input) =>
217-
cli.getViewerLogin({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
219+
cli
220+
.getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
221+
.pipe(Effect.mapError(fail("getViewer"))),
218222

219223
listChangeRequests: (input) =>
220224
cli
@@ -494,20 +498,22 @@ export const make = Effect.gen(function* () {
494498
// comparison only resolves through the head ref the detail carries. A failure here
495499
// withholds that one action rather than the whole answer, the way the detail path
496500
// leaves the banner unknown.
497-
cli.getPullRequestDetail(input).pipe(
498-
Effect.flatMap((pullRequest) =>
499-
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
500-
? Effect.succeed(false)
501-
: cli
502-
.getPullRequestBaseComparison({
503-
...input,
504-
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
505-
allowReserve: true,
506-
})
507-
.pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
508-
),
509-
Effect.orElseSucceed(() => false),
510-
),
501+
input.includeUpdateBranch === false
502+
? Effect.succeed(false)
503+
: cli.getPullRequestDetail(input).pipe(
504+
Effect.flatMap((pullRequest) =>
505+
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
506+
? Effect.succeed(false)
507+
: cli
508+
.getPullRequestBaseComparison({
509+
...input,
510+
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
511+
allowReserve: true,
512+
})
513+
.pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
514+
),
515+
Effect.orElseSucceed(() => false),
516+
),
511517
],
512518
{ concurrency: 2 },
513519
).pipe(

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,12 +276,20 @@ export interface ProviderRepositoryRef {
276276
* failing at call time.
277277
*/
278278
export interface PullRequestProviderApi {
279+
readonly getRoutingIdentity?: (input: {
280+
readonly cwd: string;
281+
readonly host: string;
282+
}) => Effect.Effect<
283+
{ readonly accountId: string; readonly viewer: string },
284+
PullRequestProviderError
285+
>;
279286
readonly kind: SourceControlProviderKind;
280287
readonly capabilities: PullRequestCapabilities;
281288

282289
/** The signed-in account, which is what involvement filtering compares against. */
283290
readonly getViewer: (input: {
284291
readonly cwd: string;
292+
readonly host?: string;
285293
}) => Effect.Effect<string, PullRequestProviderError>;
286294

287295
readonly listChangeRequests: (
@@ -397,7 +405,11 @@ export interface PullRequestProviderApi {
397405
* is no request at all.
398406
*/
399407
readonly getViewerPermissions: (
400-
input: ProviderRepositoryRef & { readonly number: number },
408+
input: ProviderRepositoryRef & {
409+
readonly number: number;
410+
/** Skip branch comparison when checking permission for an unrelated operation. */
411+
readonly includeUpdateBranch?: boolean;
412+
},
401413
) => Effect.Effect<PullRequestViewerPermissions, PullRequestProviderError>;
402414

403415
/**

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

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -975,6 +975,49 @@ it.effect("tries another workspace on the same host for the viewer", () =>
975975
}),
976976
);
977977

978+
it.effect("routing verifies the current account on the requested host without caching it", () =>
979+
Effect.gen(function* () {
980+
let viewer = "first-account";
981+
const service = yield* makeService({
982+
projects: [
983+
project({
984+
id: "p1",
985+
title: "web",
986+
workspaceRoot: "/a",
987+
repository: "acme/web",
988+
host: "github.example.test",
989+
}),
990+
],
991+
providers: [
992+
fakeProvider("github", {
993+
getRoutingIdentity: (input) => {
994+
assert.deepStrictEqual(input, { cwd: "/a", host: "github.example.test" });
995+
return Effect.succeed({
996+
viewer,
997+
accountId: viewer === "first-account" ? "123" : "456",
998+
});
999+
},
1000+
}),
1001+
],
1002+
});
1003+
const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1004+
assert.deepStrictEqual(yield* service.routing(ref), {
1005+
host: "github.example.test",
1006+
provider: "github",
1007+
viewer: "first-account",
1008+
accountId: "123",
1009+
});
1010+
viewer = "second-account";
1011+
assert.strictEqual((yield* service.routing(ref)).viewer, "second-account");
1012+
viewer = " ";
1013+
const failure = yield* service.routing(ref).pipe(Effect.flip);
1014+
assert.strictEqual(failure._tag, "PullRequestOperationError");
1015+
if (failure._tag === "PullRequestOperationError") {
1016+
assert.strictEqual(failure.operation, "routeIdentity");
1017+
}
1018+
}),
1019+
);
1020+
9781021
it.effect("refuses an action the host never claimed it could run", () =>
9791022
Effect.gen(function* () {
9801023
let ran = false;
@@ -3596,9 +3639,7 @@ it.effect("shares linked summaries and reuses them for display without asking th
35963639

35973640
yield* TestClock.adjust("61 seconds");
35983641
failing = true;
3599-
const strict = yield* Effect.flip(
3600-
service.summary(reference, { recoverTransientFailure: false }),
3601-
);
3642+
const strict = yield* Effect.flip(service.summary({ ...reference, allowStale: false }));
36023643
assert.strictEqual(strict._tag, "PullRequestOperationError");
36033644

36043645
const stale = yield* service.summary(reference);
@@ -3867,6 +3908,8 @@ it.effect("keeps recent detail on a transient refresh failure but not after inva
38673908
yield* service.detail(reference);
38683909
yield* TestClock.adjust("16 seconds");
38693910
failing = true;
3911+
const strict = yield* Effect.flip(service.detail({ ...reference, allowStale: false }));
3912+
assert.strictEqual(strict._tag, "PullRequestOperationError");
38703913
const stale = yield* service.detail(reference);
38713914
assert.strictEqual(stale.body, "last good body");
38723915

0 commit comments

Comments
 (0)