Skip to content

Commit eb4ded9

Browse files
ulughbeckclaude
andcommitted
fix(server): address review on multi-account PR routing
- Repository-scoped reads share the short-lived active token read; the unscoped routing guard still reads fresh. - A host is configured when a stored account read its repositories. - An aliased origin resolves like the primary remote. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c6e4a12 commit eb4ded9

6 files changed

Lines changed: 151 additions & 37 deletions

File tree

‎apps/server/src/project/RepositoryIdentityResolver.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,37 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
178178
},
179179
);
180180

181+
it.effect("resolves an aliased origin beside an aliased upstream", () => {
182+
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
183+
run: (input) =>
184+
Effect.succeed({
185+
stdout:
186+
input.command === "ssh"
187+
? "hostname github.com\n"
188+
: input.args.includes("rev-parse")
189+
? "/repo\n"
190+
: "origin\tgit@github-work:Me/repo.git (fetch)\nupstream\tgit@github-work:Team/repo.git (fetch)\n",
191+
stderr: "",
192+
code: ChildProcessSpawner.ExitCode(0),
193+
timedOut: false,
194+
stdoutTruncated: false,
195+
stderrTruncated: false,
196+
stdoutInvalidUtf8: false,
197+
stderrInvalidUtf8: false,
198+
}),
199+
});
200+
const resolverLayer = Layer.effect(
201+
RepositoryIdentityResolver.RepositoryIdentityResolver,
202+
RepositoryIdentityResolver.make(),
203+
).pipe(Layer.provide(processRunner));
204+
return Effect.gen(function* () {
205+
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
206+
const identity = yield* resolver.resolve("/repo");
207+
expect(identity?.canonicalKey).toBe("github.com/team/repo");
208+
expect(identity?.origin?.canonicalKey).toBe("github.com/me/repo");
209+
}).pipe(Effect.provide(resolverLayer));
210+
});
211+
181212
it.effect("does not treat an unknown HTTPS host as an SSH alias", () => {
182213
const calls: string[] = [];
183214
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {

‎apps/server/src/project/RepositoryIdentityResolver.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,13 +200,21 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn(
200200
const remote = pickPrimaryRemote(remotes);
201201
if (remote === null) return null;
202202
// Git keeps the alias in the locator; provider detection and API routing use its real host.
203-
const resolvedRemoteUrl =
204-
detectSourceControlProviderFromGitRemoteUrl(remote.remoteUrl)?.kind === "unknown"
205-
? yield* resolveSshAliasRemoteUrl(remote.remoteUrl)
206-
: remote.remoteUrl;
203+
const resolve = (remoteUrl: string) =>
204+
detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind === "unknown"
205+
? resolveSshAliasRemoteUrl(remoteUrl)
206+
: Effect.succeed(remoteUrl);
207+
const resolvedRemoteUrl = yield* resolve(remote.remoteUrl);
208+
// Origin is compared against the canonical key, so an aliased origin resolves the same way.
209+
const originUrl = remotes.get("origin");
207210
return buildRepositoryIdentity({
208211
...remote,
209-
originUrl: remote.remoteName === "origin" ? resolvedRemoteUrl : remotes.get("origin"),
212+
originUrl:
213+
originUrl === undefined
214+
? undefined
215+
: originUrl === remote.remoteUrl
216+
? resolvedRemoteUrl
217+
: yield* resolve(originUrl),
210218
rootPath: cacheKey,
211219
resolvedRemoteUrl,
212220
});

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

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,10 @@ const twoAccounts = (activeSource = "keyring") =>
244244

245245
const makeMockedCli = GitHubPullRequestCli.make.pipe(
246246
Effect.provide(
247-
Layer.merge(
247+
Layer.mergeAll(
248248
Layer.mock(GitHubCli.GitHubCli)({ execute: mockedExecute }),
249249
GitHubGraphQlBudget.layer,
250+
NodeCrypto.layer,
250251
),
251252
),
252253
);
@@ -312,7 +313,7 @@ it.effect("selects a repository-capable stored account without switching the CLI
312313
);
313314
const cli = yield* GitHubPullRequestCli.make.pipe(
314315
Effect.provideService(GitHubCli.GitHubCli, github),
315-
Effect.provide(GitHubGraphQlBudget.layer),
316+
Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, NodeCrypto.layer)),
316317
);
317318
const workInput = { cwd: "/work", host: "github.com", repository: "team/private" };
318319
const work = yield* cli.withVerifiedCredential(workInput, (identity) =>
@@ -410,6 +411,24 @@ it.effect.each(["single-account", "environment-token"] as const)(
410411
}),
411412
);
412413

414+
it.effect("shares the active token read across repository-scoped calls", () =>
415+
Effect.gen(function* () {
416+
mockedExecute.mockImplementation((input) => {
417+
if (input.args[1] === "status")
418+
return Effect.succeed(
419+
output(encodeJson({ hosts: { "github.com": [{ login: "active" }] } })),
420+
);
421+
if (input.args[1] === "token") return Effect.succeed(output("active-token"));
422+
return Effect.succeed(output('{"id":10,"login":"active"}'));
423+
});
424+
const cli = yield* makeMockedCli;
425+
yield* Effect.forEach(["a/one", "a/two", "a/three"], (repository) =>
426+
cli.getRoutingIdentity({ cwd: "/repo", host: "github.com", repository }),
427+
);
428+
expect(mockedExecute.mock.calls.filter(([input]) => input.args[1] === "token")).toHaveLength(1);
429+
}),
430+
);
431+
413432
it.effect("does not switch accounts when a repository probe fails for another reason", () =>
414433
Effect.gen(function* () {
415434
mockedExecute.mockImplementation((input) => {

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

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,8 +1252,9 @@ export const make = Effect.gen(function* () {
12521252
}),
12531253
),
12541254
);
1255-
// Choosing among stored accounts reads the CLI once per repository of a listing. Those reads
1256-
// are shared for that burst and expire quickly, so a user's account switch is seen next time.
1255+
// Every repository-scoped read and write selects a credential, and a listing selects one per
1256+
// repository. Those CLI reads are shared for the burst and expire quickly, so a user's account
1257+
// switch is seen on the next one.
12571258
const localCliRead = (args: ReadonlyArray<string>) =>
12581259
github.execute({ cwd: globalThis.process.cwd(), args, env: { GH_DEBUG: "" } });
12591260
const tokenReads = yield* Cache.makeWith(
@@ -1353,17 +1354,25 @@ export const make = Effect.gen(function* () {
13531354
const active = accounts.find((account) => account.active === true);
13541355
// An environment token (`GH_TOKEN` and friends) is the user's explicit choice.
13551356
if (accounts.length < 2 || active?.tokenSource?.endsWith("_TOKEN") === true) {
1356-
// Only the digest is retained. Never attach credential lookup output to an error.
1357-
const identity = yield* github
1358-
.execute({
1359-
cwd: input.cwd,
1360-
args: ["auth", "token", "--hostname", host],
1361-
env: { GH_DEBUG: "" },
1362-
})
1363-
.pipe(
1364-
Effect.flatMap((result) => verified(result.stdout.trim())),
1365-
Effect.mapError(unavailable),
1366-
);
1357+
// The routing guard asks without a repository and must see an account switch at once;
1358+
// repository reads share the short-lived token read. Only the digest is retained.
1359+
const token =
1360+
input.repository === undefined
1361+
? yield* github
1362+
.execute({
1363+
cwd: input.cwd,
1364+
args: ["auth", "token", "--hostname", host],
1365+
env: { GH_DEBUG: "" },
1366+
})
1367+
.pipe(
1368+
Effect.map((result) => result.stdout.trim()),
1369+
Effect.mapError(unavailable),
1370+
)
1371+
: yield* Cache.get(tokenReads, { host, login: null }).pipe(
1372+
Effect.map(Redacted.value),
1373+
Effect.mapError(unavailable),
1374+
);
1375+
const identity = yield* verified(token).pipe(Effect.mapError(unavailable));
13671376
return expected(identity) ? identity : yield* unavailable();
13681377
}
13691378
const probe = input.repository !== undefined && input.expectedAccountId === undefined;

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1484,6 +1484,42 @@ it.effect("does not read or cache counts under a replaced credential", () =>
14841484
}),
14851485
);
14861486

1487+
it.effect("reports a host configured when another stored account reads its repositories", () =>
1488+
Effect.gen(function* () {
1489+
const service = yield* makeService({
1490+
projects: [
1491+
project({
1492+
id: "work",
1493+
title: "work",
1494+
workspaceRoot: "/work",
1495+
repository: "Spherecast/spherecast",
1496+
}),
1497+
],
1498+
providers: [
1499+
fakeProvider("github", {
1500+
getViewer: () =>
1501+
Effect.fail(
1502+
new PullRequestProviderError({
1503+
provider: "github",
1504+
operation: "getViewer",
1505+
reason: "failed",
1506+
detail: "expired",
1507+
}),
1508+
),
1509+
withVerifiedCredential: (_input, use) =>
1510+
use({ accountId: "20", viewer: "bek-spherecast", credentialFingerprint: "work" }),
1511+
}),
1512+
],
1513+
});
1514+
const result = yield* service.list({ state: "open" });
1515+
assert.deepStrictEqual(
1516+
result.providers.map(({ configured, detail }) => ({ configured, detail })),
1517+
[{ configured: true, detail: null }],
1518+
);
1519+
assert.deepStrictEqual(result.errors, []);
1520+
}),
1521+
);
1522+
14871523
it.effect(
14881524
"reports unavailable repositories when host login succeeds but repository checks fail",
14891525
() =>

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

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -973,13 +973,14 @@ export const make = Effect.gen(function* () {
973973
? Effect.fail(routeRejected())
974974
: operation.pipe(Effect.provideService(routingCredential, identity), Effect.result),
975975
).pipe(
976-
Effect.catchTag("PullRequestProviderError", (error) =>
977-
Effect.fail(
978-
expectedAccountId === undefined
979-
? toPullRequestError("routeIdentity")(error)
980-
: routeRejected(),
981-
),
982-
),
976+
Effect.catchTags({
977+
PullRequestProviderError: (error) =>
978+
Effect.fail(
979+
expectedAccountId === undefined
980+
? toPullRequestError("routeIdentity")(error)
981+
: routeRejected(),
982+
),
983+
}),
983984
Effect.flatMap(Effect.fromResult),
984985
);
985986
};
@@ -1295,17 +1296,27 @@ export const make = Effect.gen(function* () {
12951296

12961297
// One summary per host, which is what the viewer lookup already answers for: two GitHub
12971298
// hosts sign in separately, so collapsing them by kind would report one as the other.
1299+
// A host whose active account failed is still configured when a repository on it was
1300+
// readable through another stored account.
12981301
const providers: ReadonlyArray<PullRequestProviderSummary> = [
1299-
...viewerResults.map((result) => ({
1300-
host: result.host,
1301-
kind: result.kind,
1302-
searchesOnHost:
1303-
projects.find((project) => project.host === result.host)?.api.capabilities.search ??
1304-
false,
1305-
projectCount: projectCounts.get(result.host) ?? 1,
1306-
configured: result.viewer !== null,
1307-
detail: result.error === null ? null : providerDetail(result.error),
1308-
})),
1302+
...viewerResults.map((result) => {
1303+
const configured =
1304+
result.viewer !== null ||
1305+
projects.some(
1306+
(project) =>
1307+
project.host === result.host && repositoryCredentials.get(project.cursorKey),
1308+
);
1309+
return {
1310+
host: result.host,
1311+
kind: result.kind,
1312+
searchesOnHost:
1313+
projects.find((project) => project.host === result.host)?.api.capabilities.search ??
1314+
false,
1315+
projectCount: projectCounts.get(result.host) ?? 1,
1316+
configured,
1317+
detail: configured || result.error === null ? null : providerDetail(result.error),
1318+
};
1319+
}),
13091320
...[...unimplemented].map(([host, { kind, projectCount }]) => ({
13101321
host,
13111322
kind,

0 commit comments

Comments
 (0)