fix: Require GitHub account ownership when connecting an installation (#14323)

This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-24 18:52:43 -04:00
1 parent b0b307259a
commit 71af4d6901
6 files changed
+304 -15

No files matched your search

+26
View File
@@ -18,6 +18,7 @@ import Time from "~/components/Time";
import env from "~/env";
import useQuery from "~/hooks/useQuery";
import useStores from "~/hooks/useStores";
import isCloudHosted from "~/utils/isCloudHosted";
import { isTruthyQueryValue } from "~/utils/urls";
import GitHubIcon from "./Icon";
import { GitHubConnectButton } from "./components/GitHubButton";
@@ -58,6 +59,31 @@ function GitHub() {
</Trans>
</Notice>
)}
{error === "denied" && (
<Notice>
<Trans>
Only an owner of the GitHub account or organization can connect it
to {{ appName }}.
</Trans>
</Notice>
)}
{error === "missing_permission" && (
<Notice>
{isCloudHosted ? (
<Trans>
The GitHub app needs new permissions for the organization. Ask an
owner of the organization to accept them in GitHub, then try
again.
</Trans>
) : (
<Trans>
The GitHub app needs the “Members” read permission for the
organization. Add this permission to your GitHub app, then ask an
owner of the organization to accept it in GitHub and try again.
</Trans>
)}
</Notice>
)}
{isTruthyQueryValue(installRequest) && (
<Notice>
<Trans>
+45 -1
View File
@@ -1,10 +1,54 @@
import { buildUser, buildViewer } from "@server/test/factories";
import { IntegrationService } from "@shared/types";
import { Integration } from "@server/models";
import { buildAdmin, buildUser, buildViewer } from "@server/test/factories";
import { getTestServer } from "@server/test/support";
import { GitHub, InstallationAccess } from "../github";
import { SetupAction } from "./schema";
const server = getTestServer();
describe("#github.callback", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("should reject an installation the user cannot manage", async () => {
const user = await buildAdmin();
const state = JSON.stringify({ teamId: user.teamId, nonce: "nonce" });
const client = {
requestAppInstallations: async () => [
{ id: 1, permissions: { issues: "read" }, account: null },
],
} as unknown as Awaited<ReturnType<typeof GitHub.authenticateAsUser>>;
vi.spyOn(GitHub, "authenticateAsUser").mockResolvedValue(client);
const spy = vi
.spyOn(GitHub, "canManageInstallation")
.mockResolvedValue(InstallationAccess.Denied);
const res = await server.get(
`/api/github.callback?state=${encodeURIComponent(
state
)}&code=123&setup_action=${SetupAction.install}&installation_id=1`,
user,
{
redirect: "manual",
headers: { Cookie: "githubOAuthNonce=nonce" },
}
);
expect(res.status).toEqual(302);
expect(res.headers.get("location")).toContain("error=denied");
expect(spy).toHaveBeenCalledWith(
client,
expect.objectContaining({ id: 1 })
);
expect(
await Integration.count({
where: { teamId: user.teamId, service: IntegrationService.GitHub },
})
).toEqual(0);
});
it("should reject callback when state cookie is missing", async () => {
const user = await buildUser();
const state = JSON.stringify({
+6 -1
View File
@@ -15,7 +15,7 @@ import { verifyOAuthStateNonce } from "@server/utils/oauth";
import { RequestHelper } from "@server/utils/RequestHelper";
import { GitHubOAuthNonceCookie, GitHubUtils } from "../../shared/GitHubUtils";
import env from "../env";
import { GitHub } from "../github";
import { GitHub, InstallationAccess } from "../github";
import GitHubWebhookTask from "../tasks/GitHubWebhookTask";
import * as T from "./schema";
@@ -75,6 +75,11 @@ router.get(
return ctx.redirect(GitHubUtils.errorUrl("unauthenticated"));
}
const access = await GitHub.canManageInstallation(client, installation);
if (access !== InstallationAccess.Allowed) {
return ctx.redirect(GitHubUtils.errorUrl(access));
}
const scopes = Object.entries(installation.permissions).map(
([name, permission]) => `${name}:${String(permission)}`
);
+125
View File
@@ -0,0 +1,125 @@
import { RequestError } from "octokit";
import { GitHub, InstallationAccess } from "./github";
type Client = Parameters<typeof GitHub.canManageInstallation>[0];
type UserInstallation = Parameters<typeof GitHub.canManageInstallation>[1];
function buildInstallation(
targetType: string,
permissions: Record<string, string> = {}
) {
return {
id: 1,
target_type: targetType,
account: { id: 100, login: "acme" },
permissions,
} as unknown as UserInstallation;
}
function buildClient({
userId = 100,
membership,
}: {
userId?: number;
membership?: { state: string; role: string } | RequestError;
}) {
return {
requestAuthenticatedUser: async () => ({ data: { id: userId } }),
requestOrgMembership: async () => {
if (membership instanceof RequestError) {
throw membership;
}
return { data: membership };
},
} as unknown as Client;
}
function buildRequestError(status: number) {
return new RequestError("error", status, {
request: { method: "GET", url: "https://api.github.com", headers: {} },
});
}
describe("GitHub.canManageInstallation", () => {
it("should allow the owner of a personal account", async () => {
const client = buildClient({ userId: 100 });
expect(
await GitHub.canManageInstallation(client, buildInstallation("User"))
).toBe(InstallationAccess.Allowed);
});
it("should deny another user on a personal account", async () => {
const client = buildClient({ userId: 200 });
expect(
await GitHub.canManageInstallation(client, buildInstallation("User"))
).toBe(InstallationAccess.Denied);
});
it("should allow an active organization admin", async () => {
const client = buildClient({
membership: { state: "active", role: "admin" },
});
expect(
await GitHub.canManageInstallation(
client,
buildInstallation("Organization", { members: "read" })
)
).toBe(InstallationAccess.Allowed);
});
it("should deny an organization member who is not an admin", async () => {
const client = buildClient({
membership: { state: "active", role: "member" },
});
expect(
await GitHub.canManageInstallation(
client,
buildInstallation("Organization", { members: "read" })
)
).toBe(InstallationAccess.Denied);
});
it("should deny a pending organization admin", async () => {
const client = buildClient({
membership: { state: "pending", role: "admin" },
});
expect(
await GitHub.canManageInstallation(
client,
buildInstallation("Organization", { members: "read" })
)
).toBe(InstallationAccess.Denied);
});
it("should deny a user outside the organization", async () => {
const client = buildClient({ membership: buildRequestError(404) });
expect(
await GitHub.canManageInstallation(
client,
buildInstallation("Organization", { members: "read" })
)
).toBe(InstallationAccess.Denied);
});
it("should report a missing members permission", async () => {
const client = buildClient({
membership: { state: "active", role: "admin" },
});
expect(
await GitHub.canManageInstallation(
client,
buildInstallation("Organization")
)
).toBe(InstallationAccess.MissingPermission);
});
it("should deny an installation on an enterprise", async () => {
const client = buildClient({});
expect(
await GitHub.canManageInstallation(
client,
buildInstallation("Enterprise")
)
).toBe(InstallationAccess.Denied);
});
});
+99 -13
View File
@@ -1,12 +1,11 @@
import {
createOAuthUserAuth,
createAppAuth,
type OAuthWebFlowAuthOptions,
type GitHubAppUserAuthentication,
type InstallationAuthOptions,
} from "@octokit/auth-app";
import { Sequelize } from "sequelize";
import type { Endpoints, OctokitResponse } from "@octokit/types";
import { Octokit } from "octokit";
import { Octokit, RequestError } from "octokit";
import pluralize from "pluralize";
import { toError, errToString } from "@shared/utils/error";
import type { IntegrationType } from "@shared/types";
@@ -22,12 +21,21 @@ import type {
import { GitHubUtils } from "../shared/GitHubUtils";
import env from "./env";
/** The access a user has to a GitHub app installation. */
export enum InstallationAccess {
Allowed = "allowed",
Denied = "denied",
MissingPermission = "missing_permission",
}
type PR =
Endpoints["GET /repos/{owner}/{repo}/pulls/{pull_number}"]["response"]["data"];
type Issue =
Endpoints["GET /repos/{owner}/{repo}/issues/{issue_number}"]["response"]["data"];
type Installation =
Endpoints["GET /app/installations/{installation_id}"]["response"]["data"];
type UserInstallation =
Endpoints["GET /user/installations"]["response"]["data"]["installations"][number];
type ParsedIssueOrPR = {
owner: string;
@@ -145,6 +153,34 @@ const requestPlugin = (octokit: Octokit) => ({
};
},
/**
* Fetches the authenticated user.
*
* @returns the user's GitHub profile.
*/
requestAuthenticatedUser: async () =>
octokit.rest.users.getAuthenticated({
headers: {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
}),
/**
* Fetches the authenticated user's membership in an organization.
*
* @param org login of the organization.
* @returns the membership, including role and state.
*/
requestOrgMembership: async (org: string) =>
octokit.rest.orgs.getMembershipForAuthenticatedUser({
org,
headers: {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
}),
/**
* Fetches app installations accessible to the user
*
@@ -202,6 +238,8 @@ const requestPlugin = (octokit: Octokit) => ({
const CustomOctokit = Octokit.plugin(requestPlugin);
type GitHubClient = InstanceType<typeof CustomOctokit>;
export class GitHub {
private static appId = env.GITHUB_APP_ID;
private static appKey = env.GITHUB_APP_PRIVATE_KEY
@@ -305,17 +343,15 @@ export class GitHub {
public static authenticateAsUser = async (
code: string,
state?: string | null
) =>
GitHub.authenticateAsApp().auth({
): Promise<GitHubClient> => {
// Exchange the code once, the oauth-user strategy repeats it per request.
const { token } = (await GitHub.authenticateAsApp().auth({
type: "oauth-user",
code,
state,
factory: (options: OAuthWebFlowAuthOptions) =>
new CustomOctokit({
authStrategy: createOAuthUserAuth,
auth: options,
}),
}) as Promise<InstanceType<typeof CustomOctokit>>;
})) as GitHubAppUserAuthentication;
return new CustomOctokit({ auth: token });
};
/**
* [Authenticates as a GitHub app installation](https://github.com/octokit/auth-app.js/?tab=readme-ov-file#authenticate-as-installation)
@@ -332,7 +368,57 @@ export class GitHub {
authStrategy: createAppAuth,
auth: options,
}),
}) as Promise<InstanceType<typeof CustomOctokit>>;
}) as Promise<GitHubClient>;
/**
* Checks whether the user can manage an installation. The user must be the
* owner of a personal account, or an active admin of an organization.
*
* @param client user-authenticated octokit instance.
* @param installation installation from the user's installation list.
* @returns the access the user has to the installation.
*/
public static async canManageInstallation(
client: GitHubClient,
installation: UserInstallation
): Promise<InstallationAccess> {
const { account } = installation;
if (!account || !("login" in account)) {
return InstallationAccess.Denied;
}
if (installation.target_type === "User") {
const { data: user } = await client.requestAuthenticatedUser();
return user.id === account.id
? InstallationAccess.Allowed
: InstallationAccess.Denied;
}
if (installation.target_type !== "Organization") {
return InstallationAccess.Denied;
}
if (!installation.permissions.members) {
return InstallationAccess.MissingPermission;
}
try {
const { data: membership } = await client.requestOrgMembership(
account.login
);
return membership.state === "active" && membership.role === "admin"
? InstallationAccess.Allowed
: InstallationAccess.Denied;
} catch (err) {
if (
err instanceof RequestError &&
(err.status === 403 || err.status === 404)
) {
return InstallationAccess.Denied;
}
throw err;
}
}
/**
*
@@ -394,7 +480,7 @@ export class GitHub {
};
private static async unfurlProject(
client: InstanceType<typeof CustomOctokit>,
client: GitHubClient,
resource: ParsedProject
) {
let project: GitHubProject | undefined;