diff --git a/plugins/github/client/Settings.tsx b/plugins/github/client/Settings.tsx index f0bb541746..599a5b58fd 100644 --- a/plugins/github/client/Settings.tsx +++ b/plugins/github/client/Settings.tsx @@ -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() { )} + {error === "denied" && ( + + + Only an owner of the GitHub account or organization can connect it + to {{ appName }}. + + + )} + {error === "missing_permission" && ( + + {isCloudHosted ? ( + + The GitHub app needs new permissions for the organization. Ask an + owner of the organization to accept them in GitHub, then try + again. + + ) : ( + + 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. + + )} + + )} {isTruthyQueryValue(installRequest) && ( diff --git a/plugins/github/server/api/github.test.ts b/plugins/github/server/api/github.test.ts index 9c66856709..8dfe626a79 100644 --- a/plugins/github/server/api/github.test.ts +++ b/plugins/github/server/api/github.test.ts @@ -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>; + 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({ diff --git a/plugins/github/server/api/github.ts b/plugins/github/server/api/github.ts index 5903e82e3e..34402faa53 100644 --- a/plugins/github/server/api/github.ts +++ b/plugins/github/server/api/github.ts @@ -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)}` ); diff --git a/plugins/github/server/github.test.ts b/plugins/github/server/github.test.ts new file mode 100644 index 0000000000..8a1f67c1f1 --- /dev/null +++ b/plugins/github/server/github.test.ts @@ -0,0 +1,125 @@ +import { RequestError } from "octokit"; +import { GitHub, InstallationAccess } from "./github"; + +type Client = Parameters[0]; +type UserInstallation = Parameters[1]; + +function buildInstallation( + targetType: string, + permissions: Record = {} +) { + 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); + }); +}); diff --git a/plugins/github/server/github.ts b/plugins/github/server/github.ts index fcb067675c..22c9b3ad9c 100644 --- a/plugins/github/server/github.ts +++ b/plugins/github/server/github.ts @@ -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; + 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 => { + // 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>; + })) 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>; + }) as Promise; + + /** + * 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 { + 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, + client: GitHubClient, resource: ParsedProject ) { let project: GitHubProject | undefined; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 974d67a95d..3dc0456431 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -1668,6 +1668,9 @@ "Disconnecting will prevent previewing Figma design files from this account in documents. Are you sure?": "Disconnecting will prevent previewing Figma design files from this account in documents. Are you sure?", "The Figma integration is currently disabled. Please set the associated environment variables and restart the server to enable the integration.": "The Figma integration is currently disabled. Please set the associated environment variables and restart the server to enable the integration.", "Whoops, you need to accept the permissions in GitHub to connect {{appName}} to your workspace. Try again?": "Whoops, you need to accept the permissions in GitHub to connect {{appName}} to your workspace. Try again?", + "Only an owner of the GitHub account or organization can connect it to {{appName}}.": "Only an owner of the GitHub account or organization can connect it to {{appName}}.", + "The GitHub app needs new permissions for the organization. Ask an owner of the organization to accept them in GitHub, then try again.": "The GitHub app needs new permissions for the organization. Ask an owner of the organization to accept them in GitHub, then try again.", + "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.": "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.", "The owner of the GitHub account has been requested to install the {{githubAppName}} GitHub app. Once approved, previews will be shown for respective links.": "The owner of the GitHub account has been requested to install the {{githubAppName}} GitHub app. Once approved, previews will be shown for respective links.", "Enable previews of GitHub issues and pull requests in documents by connecting a GitHub organization or specific repositories to {{appName}}.": "Enable previews of GitHub issues and pull requests in documents by connecting a GitHub organization or specific repositories to {{appName}}.", "Enabled by {{integrationCreatedBy}}": "Enabled by {{integrationCreatedBy}}",