Skip to content
TypeScript

fix(server): pull requests load for credentials that cannot read /user (#18780)

Lanny Bose71b2ac4f9b59
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
index feb0cd94eab..6a5bd625c94 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
@@ -88,6 +88,7 @@ const coreResponse = (pullRequest: Readonly<Record<string, unknown>> = {}) => ({
type ApiCall =
| {
readonly kind: "graphql";
+ readonly authorization: string | undefined;
readonly partial?: boolean;
/** The generated operation's name, which the routes below match on. */
readonly operationName?: string;
@@ -137,6 +138,7 @@ const mockHttp = Layer.succeed(
: { query: "", operationName: "", variables: {} };
const call: ApiCall = {
kind: "graphql",
+ authorization: request.headers["authorization"],
host,
operation: "batch",
operationName: sent.operationName,
@@ -3742,6 +3744,139 @@ layer("GitHubPullRequestApi.layer", (it) => {
}),
);
+ it.effect("verifies a REST-forbidden account through GraphQL with the pinned credential", () =>
+ Effect.gen(function* () {
+ const input = { cwd: "/w", host: "github.identity-fallback.test" };
+ const original = {
+ token: Redacted.make("original-token"),
+ fingerprint: `${input.host}:original`,
+ };
+ mockedCredential.mockReturnValue(Effect.succeed(original));
+ mockedExecute.mockImplementation((call) =>
+ Effect.gen(function* () {
+ expect(yield* SourceControlRateLimit.CredentialScope).toBe(original.fingerprint);
+ if (call.kind === "rest") {
+ expect(call.path).toBe("user");
+ expect(yield* GitHubRequestPolicy.PinnedGitHubCredential).toMatchObject({
+ host: input.host,
+ credentialFingerprint: original.fingerprint,
+ });
+ mockedCredential.mockReturnValue(
+ Effect.succeed({
+ token: Redacted.make("replacement-token"),
+ fingerprint: `${input.host}:replacement`,
+ }),
+ );
+ return yield* new GitHubRequestPolicy.GitHubApiResponseError({
+ host: input.host,
+ operation: "getRoutingIdentity",
+ status: 403,
+ githubErrors: ["Resource not accessible by integration"],
+ });
+ }
+ expect(call.host).toBe(input.host);
+ expect(call.authorization).toBe("Bearer original-token");
+ expect(call.query).toMatch(/viewer\s*\{/);
+ expect(call.query).toContain("databaseId");
+ expect(call.query).toContain("login");
+ return output(
+ '{"data":{"viewer":{"databaseId":789,"login":"acme-app[bot]"}}}',
+ false,
+ false,
+ graphqlQuota(0),
+ );
+ }),
+ );
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+ const quota = yield* GitHubQuota.GitHubQuota;
+ yield* quota
+ .observe(input.host, graphqlQuota(1))
+ .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, original.fingerprint));
+ const identity = { accountId: "789", viewer: "acme-app[bot]" };
+ expect(yield* cli.getRoutingIdentity(input)).toEqual(identity);
+
+ mockedCredential.mockReturnValue(Effect.succeed(original));
+ expect(yield* cli.getRoutingIdentity(input)).toEqual(identity);
+ expect(mockedExecute).toHaveBeenCalledTimes(2);
+
+ const exhausted = yield* quota
+ .admit(input.host, "graphql")
+ .pipe(
+ Effect.provideService(SourceControlRateLimit.CredentialScope, original.fingerprint),
+ Effect.flip,
+ );
+ expect(exhausted._tag).toBe("SourceControlRateLimitPausedError");
+ yield* quota
+ .admit(input.host, "graphql")
+ .pipe(
+ Effect.provideService(
+ SourceControlRateLimit.CredentialScope,
+ `${input.host}:replacement`,
+ ),
+ );
+ }),
+ );
+
+ it.effect("rejects a null GraphQL account id without caching it", () =>
+ Effect.gen(function* () {
+ const input = { cwd: "/w", host: "github.identity-null.test" };
+ const forbidden = new GitHubRequestPolicy.GitHubApiResponseError({
+ host: input.host,
+ operation: "getRoutingIdentity",
+ status: 403,
+ });
+ mockedExecute
+ .mockReturnValueOnce(Effect.fail(forbidden))
+ .mockReturnValueOnce(
+ Effect.succeed(output('{"data":{"viewer":{"databaseId":null,"login":"acme-app[bot]"}}}')),
+ )
+ .mockReturnValueOnce(Effect.fail(forbidden))
+ .mockReturnValueOnce(
+ Effect.succeed(output('{"data":{"viewer":{"databaseId":789,"login":"acme-app[bot]"}}}')),
+ );
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+ const error = yield* cli.getRoutingIdentity(input).pipe(Effect.flip);
+ expect(error._tag).toBe("GitHubViewerLoginUnavailableError");
+ expect(yield* cli.getRoutingIdentity(input)).toEqual({
+ accountId: "789",
+ viewer: "acme-app[bot]",
+ });
+ expect(mockedExecute).toHaveBeenCalledTimes(4);
+ }),
+ );
+
+ it.effect.each([
+ new GitHubRequestPolicy.GitHubApiAuthenticationError({
+ host: "github.identity-auth-error.test",
+ operation: "getRoutingIdentity",
+ }),
+ new GitHubRequestPolicy.GitHubApiRateLimitError({
+ host: "github.identity-rate-error.test",
+ operation: "getRoutingIdentity",
+ retryAt: 123_456,
+ }),
+ new GitHubRequestPolicy.GitHubApiRequestError({
+ host: "github.identity-network-error.test",
+ operation: "getRoutingIdentity",
+ cause: new Error("connection refused"),
+ }),
+ new GitHubRequestPolicy.GitHubApiResponseError({
+ host: "github.identity-server-error.test",
+ operation: "getRoutingIdentity",
+ status: 500,
+ }),
+ ])("preserves $_tag from REST identity verification without trying GraphQL", (error) =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.fail(error));
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+ expect(yield* cli.getRoutingIdentity({ cwd: "/w", host: error.host }).pipe(Effect.flip)).toBe(
+ error,
+ );
+ expect(mockedExecute).toHaveBeenCalledTimes(1);
+ expect(callAt(0)).toMatchObject({ kind: "rest", path: "user" });
+ }),
+ );
+
it.effect("reuses verified credentials offline and refuses an unverified replacement", () =>
Effect.gen(function* () {
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
index 634a8cb24bb..0833d2d4339 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
@@ -907,6 +907,9 @@ export const make = Effect.gen(function* () {
const sourceControlHost = yield* SourceControlHost.SourceControlHost;
const fileSystem = yield* FileSystem.FileSystem;
const revalidateChecks = yield* makeChecksRevalidator;
+ const client = yield* GraphQLClient.make(PullRequestGraphQLGroup).pipe(
+ Effect.provide(GitHubGraphQlClient.layer),
+ );
const routingIdentities = new Map<
string,
{
@@ -915,14 +918,12 @@ export const make = Effect.gen(function* () {
}
>();
const identityLocks = new Map<string, { gate: Semaphore.Semaphore; users: number }>();
- const decodeRoutingIdentity = Schema.decodeUnknownEffect(
- Schema.fromJsonString(
- Schema.Struct({
- id: PositiveInt,
- login: TrimmedNonEmptyString,
- }),
- ),
- );
+ const RoutingIdentity = Schema.Struct({
+ id: PositiveInt,
+ login: TrimmedNonEmptyString,
+ });
+ const decodeRoutingIdentity = Schema.decodeUnknownEffect(Schema.fromJsonString(RoutingIdentity));
+ const decodeViewerIdentity = Schema.decodeUnknownEffect(RoutingIdentity);
const captureVerifiedCredential = Effect.fn("GitHubPullRequestApi.captureVerifiedCredential")(
function* (input: { readonly cwd: string; readonly host: string }) {
const unavailable = () => new GitHubViewerLoginUnavailableError({ cwd: input.cwd });
@@ -943,16 +944,36 @@ export const make = Effect.gen(function* () {
const cached = routingIdentities.get(key);
if (cached !== undefined && now - cached.at < 10 * 60_000)
return { ...credential, ...cached.value };
- // Pin this read so an auth switch cannot poison its cache entry.
- const response = yield* api
+ // Pin verification so an auth switch cannot poison its cache entry.
+ const identity = yield* api
.rest({ host, operation: "getRoutingIdentity", path: "user", allowReserve: true })
.pipe(
+ Effect.flatMap((response) =>
+ decodeRoutingIdentity(response.body).pipe(Effect.mapError(unavailable)),
+ ),
+ Effect.catchTags({
+ GitHubApiResponseError: (error) =>
+ Effect.gen(function* () {
+ if (error.status !== 403) return yield* error;
+ const { viewer } = yield* client.RoutingIdentityViewer({}).pipe(
+ GitHubGraphQlClient.call({
+ host,
+ operation: "getRoutingIdentity",
+ allowReserve: true,
+ }),
+ Effect.catchTags({
+ GraphQLClientError: () => Effect.fail(unavailable()),
+ }),
+ );
+ return yield* decodeViewerIdentity({
+ id: viewer.databaseId,
+ login: viewer.login,
+ }).pipe(Effect.mapError(unavailable));
+ }),
+ }),
Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, credential),
Effect.provideService(SourceControlRateLimit.CredentialScope, key),
);
- const identity = yield* decodeRoutingIdentity(response.body).pipe(
- Effect.mapError(unavailable),
- );
const value = { accountId: String(identity.id), viewer: identity.login };
if (routingIdentities.size >= 128)
routingIdentities.delete(routingIdentities.keys().next().value!);
@@ -989,10 +1010,6 @@ export const make = Effect.gen(function* () {
Effect.map(({ accountId, viewer }) => ({ accountId, viewer })),
);
- const client = yield* GraphQLClient.make(PullRequestGraphQLGroup).pipe(
- Effect.provide(GitHubGraphQlClient.layer),
- );
-
const readError = (cwd: string, operation: string, cause: unknown) =>
new GitHubPullRequestReadError({ cwd, operation, cause });
diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql
index b6aadc05ce2..da3778d6af8 100644
--- a/packages/source-control-github/src/server/pullRequestReads.graphql
+++ b/packages/source-control-github/src/server/pullRequestReads.graphql
@@ -1,4 +1,11 @@
-# Reads of one pull request, or of the repository it belongs to.
+# Reads of the signed-in account, one pull request, or its repository.
+
+query RoutingIdentityViewer {
+ viewer {
+ databaseId
+ login
+ }
+}
# Resolves a listing's authors to avatars, which no listing field carries.
query ActorAvatars($ids: [ID!]!) {
diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts
index 64f21634e55..bbf591bb641 100644
--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts
+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts
@@ -82,6 +82,34 @@ export const CheckContext = Schema.Union([
])
export type CheckContext = typeof CheckContext.Type
+/** A user is an individual's account on GitHub that owns repositories and can make new content. */
+export const ViewerUser = Schema.Struct({
+ /** Identifies the primary key from the database. */
+ databaseId: Schema.NullOr(Shared.Int),
+ /** The username used to login. */
+ login: Schema.String
+})
+export interface ViewerUser extends Schema.Struct.Type<typeof ViewerUser.fields> {}
+
+/** `query RoutingIdentityViewer` */
+export const RoutingIdentityViewer = GraphQL.query("RoutingIdentityViewer", {
+ document: {
+ variables: [],
+ selections: [
+ { name: "viewer", body: ["{databaseId login}"] }
+ ],
+ fragments: []
+ },
+ result: Schema.Struct({
+ /** The currently authenticated user. */
+ viewer: ViewerUser
+ })
+})
+export declare namespace RoutingIdentityViewer {
+ export type Variables = typeof RoutingIdentityViewer.variables.Type
+ export type Result = typeof RoutingIdentityViewer.result.Type
+}
+
/** A user is an individual's account on GitHub that owns repositories and can make new content. */
export const ActorAvatarsNodesUser = Schema.Struct({
__typename: Schema.Literal("User"),
@@ -1495,4 +1523,4 @@ export declare namespace PullRequestSourceBranch {
}
/** Every operation in pullRequestReads.graphql. */
-export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)
+export const PullRequestReadsGraphQLGroup = GraphQLGroup.make(RoutingIdentityViewer, ActorAvatars, PullRequestCore, PullRequestCheckContexts, PullRequestPreview, PullRequestActivity, PullRequestHeads, PullRequestNodeId, PullRequestSubject, ViewerPermissions, ReviewerCandidates, LabelCandidates, PullRequestFilesViewed, PullRequestMergeMessage, PullRequestActionState, PullRequestBranchToDelete, PullRequestSourceBranch)