mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-05 05:26:25 +00:00
Merge pull request #2566 from Infisical/feat/github-integration-app-auth
feat: github integration with Github app auth
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
export { useDuplicateIntegrationAuth } from "./mutations";
|
||||
export {
|
||||
useAuthorizeIntegration,
|
||||
useDeleteIntegrationAuth,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
|
||||
import { apiRequest } from "@app/config/request";
|
||||
|
||||
import { IntegrationAuth, TDuplicateIntegrationAuthDTO } from "./types";
|
||||
|
||||
// For now, this should only be used in the Github app integration flow.
|
||||
export const useDuplicateIntegrationAuth = () => {
|
||||
return useMutation<IntegrationAuth, {}, TDuplicateIntegrationAuthDTO>({
|
||||
mutationFn: async (body) => {
|
||||
const { data } = await apiRequest.post<{ integrationAuth: IntegrationAuth }>(
|
||||
`/api/v1/integration-auth/${body.integrationAuthId}/duplicate`,
|
||||
body
|
||||
);
|
||||
|
||||
return data.integrationAuth;
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -777,11 +777,13 @@ export const useAuthorizeIntegration = () => {
|
||||
workspaceId,
|
||||
code,
|
||||
integration,
|
||||
installationId,
|
||||
url
|
||||
}: {
|
||||
workspaceId: string;
|
||||
code: string;
|
||||
integration: string;
|
||||
installationId?: string;
|
||||
url?: string;
|
||||
}) => {
|
||||
const {
|
||||
@@ -790,6 +792,7 @@ export const useAuthorizeIntegration = () => {
|
||||
workspaceId,
|
||||
code,
|
||||
integration,
|
||||
installationId,
|
||||
url
|
||||
});
|
||||
|
||||
|
||||
@@ -9,6 +9,10 @@ export type IntegrationAuth = {
|
||||
keyEncoding: string;
|
||||
url?: string;
|
||||
teamId?: string;
|
||||
metadata: {
|
||||
installationName?: string;
|
||||
installationId?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type App = {
|
||||
@@ -84,3 +88,8 @@ export type TeamCityBuildConfig = {
|
||||
name: string;
|
||||
buildConfigId: string;
|
||||
};
|
||||
|
||||
export type TDuplicateIntegrationAuthDTO = {
|
||||
integrationAuthId: string;
|
||||
projectId: string;
|
||||
};
|
||||
|
||||
@@ -8,8 +8,9 @@ export {
|
||||
useDeleteOrgTaxId,
|
||||
useGetIdentityMembershipOrgs,
|
||||
useGetOrganizationGroups,
|
||||
useGetOrganizations,
|
||||
useGetOrganizations,
|
||||
useGetOrgBillingDetails,
|
||||
useGetOrgIntegrationAuths,
|
||||
useGetOrgInvoices,
|
||||
useGetOrgLicenses,
|
||||
useGetOrgPlanBillingInfo,
|
||||
@@ -20,4 +21,4 @@ export {
|
||||
useGetOrgTrialUrl,
|
||||
useUpdateOrg,
|
||||
useUpdateOrgBillingDetails
|
||||
} from "./queries";
|
||||
} from "./queries";
|
||||
|
||||
@@ -4,6 +4,7 @@ import { apiRequest } from "@app/config/request";
|
||||
import { OrderByDirection } from "@app/hooks/api/generic/types";
|
||||
|
||||
import { TGroupOrgMembership } from "../groups/types";
|
||||
import { IntegrationAuth } from "../types";
|
||||
import {
|
||||
BillingDetails,
|
||||
Invoice,
|
||||
@@ -39,7 +40,8 @@ export const organizationKeys = {
|
||||
...params
|
||||
}: TListOrgIdentitiesDTO) =>
|
||||
[...organizationKeys.getOrgIdentityMemberships(orgId), params] as const,
|
||||
getOrgGroups: (orgId: string) => [{ orgId }, "organization-groups"] as const
|
||||
getOrgGroups: (orgId: string) => [{ orgId }, "organization-groups"] as const,
|
||||
getOrgIntegrationAuths: (orgId: string) => [{ orgId }, "integration-auths"] as const
|
||||
};
|
||||
|
||||
export const fetchOrganizations = async () => {
|
||||
@@ -464,3 +466,21 @@ export const useGetOrganizationGroups = (organizationId: string) => {
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useGetOrgIntegrationAuths = <TData = IntegrationAuth[],>(
|
||||
organizationId: string,
|
||||
select?: (data: IntegrationAuth[]) => TData
|
||||
) => {
|
||||
return useQuery({
|
||||
queryKey: organizationKeys.getOrgIntegrationAuths(organizationId),
|
||||
queryFn: async () => {
|
||||
const { data } = await apiRequest.get<{ authorizations: IntegrationAuth[] }>(
|
||||
`/api/v1/organization/${organizationId}/integration-authorizations`
|
||||
);
|
||||
|
||||
return data.authorizations;
|
||||
},
|
||||
enabled: Boolean(organizationId),
|
||||
select
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import crypto from "crypto";
|
||||
|
||||
import { useState } from "react";
|
||||
import Head from "next/head";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardBody,
|
||||
CardTitle,
|
||||
FormControl,
|
||||
Select,
|
||||
SelectItem
|
||||
} from "@app/components/v2";
|
||||
import { useGetCloudIntegrations } from "@app/hooks/api";
|
||||
|
||||
enum AuthMethod {
|
||||
APP = "APP",
|
||||
OAUTH = "OAUTH"
|
||||
}
|
||||
|
||||
export default function GithubIntegrationAuthModeSelectionPage() {
|
||||
const router = useRouter();
|
||||
const { data: cloudIntegrations } = useGetCloudIntegrations();
|
||||
const githubIntegration = cloudIntegrations?.find((integration) => integration.slug === "github");
|
||||
const [selectedAuthMethod, setSelectedAuthMethod] = useState<AuthMethod>(AuthMethod.APP);
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<Head>
|
||||
<title>Select GitHub Integration Auth</title>
|
||||
<link rel="icon" href="/infisical.ico" />
|
||||
</Head>
|
||||
<Card className="mb-12 max-w-lg rounded-md border border-mineshaft-600">
|
||||
<CardTitle
|
||||
className="px-6 text-left text-xl"
|
||||
subTitle="Select how you'd like to integrate with GitHub. We recommend using the GitHub App method for fine-grained access."
|
||||
>
|
||||
<div className="flex flex-row items-center">
|
||||
<div className="flex items-center pb-0.5">
|
||||
<Image
|
||||
src="/images/integrations/GitHub.png"
|
||||
height={30}
|
||||
width={30}
|
||||
alt="Github logo"
|
||||
/>
|
||||
</div>
|
||||
<span className="ml-2.5">GitHub Integration </span>
|
||||
<Link href="https://infisical.com/docs/integrations/cicd/githubactions" passHref>
|
||||
<a target="_blank" rel="noopener noreferrer">
|
||||
<div className="ml-2 mb-1 inline-block cursor-default rounded-md bg-yellow/20 px-1.5 pb-[0.03rem] pt-[0.04rem] text-sm text-yellow opacity-80 hover:opacity-100">
|
||||
<FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
|
||||
Docs
|
||||
<FontAwesomeIcon
|
||||
icon={faArrowUpRightFromSquare}
|
||||
className="ml-1.5 mb-[0.07rem] text-xxs"
|
||||
/>
|
||||
</div>
|
||||
</a>
|
||||
</Link>
|
||||
</div>
|
||||
</CardTitle>
|
||||
<CardBody>
|
||||
<FormControl label="Select authentication method">
|
||||
<Select
|
||||
value={selectedAuthMethod}
|
||||
onValueChange={(val) => {
|
||||
setSelectedAuthMethod(val as AuthMethod);
|
||||
}}
|
||||
className="w-full border border-mineshaft-500"
|
||||
>
|
||||
<SelectItem value={AuthMethod.APP}>GitHub App (Recommended)</SelectItem>
|
||||
<SelectItem value={AuthMethod.OAUTH}>OAuth</SelectItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<div className="flex items-end">
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (selectedAuthMethod === AuthMethod.APP) {
|
||||
router.push("/integrations/select-integration-auth?integrationSlug=github");
|
||||
} else {
|
||||
const state = crypto.randomBytes(16).toString("hex");
|
||||
localStorage.setItem("latestCSRFToken", state);
|
||||
|
||||
window.location.assign(
|
||||
`https://github.com/login/oauth/authorize?client_id=${githubIntegration?.clientId}&response_type=code&scope=repo,admin:org&redirect_uri=${window.location.origin}/integrations/github/oauth2/callback&state=${state}`
|
||||
);
|
||||
}
|
||||
}}
|
||||
colorSchema="primary"
|
||||
variant="outline_bg"
|
||||
className="mt-4 ml-auto w-min"
|
||||
>
|
||||
Connect to GitHub
|
||||
</Button>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
GithubIntegrationAuthModeSelectionPage.requireAuth = true;
|
||||
@@ -478,7 +478,7 @@ export default function GitHubCreateIntegrationPage() {
|
||||
errorText={
|
||||
integrationAuthOrgs?.length ? error?.message : "No organizations found"
|
||||
}
|
||||
isError={Boolean(integrationAuthOrgs?.length && error?.message)}
|
||||
isError={Boolean(integrationAuthOrgs?.length || error?.message)}
|
||||
>
|
||||
<Select
|
||||
value={field.value}
|
||||
|
||||
@@ -8,18 +8,23 @@ export default function GitHubOAuth2CallbackPage() {
|
||||
const router = useRouter();
|
||||
const { mutateAsync } = useAuthorizeIntegration();
|
||||
|
||||
const { code, state } = queryString.parse(router.asPath.split("?")[1]);
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
const { code, state, installation_id } = queryString.parse(router.asPath.split("?")[1]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
// validate state
|
||||
if (state !== localStorage.getItem("latestCSRFToken")) return;
|
||||
if (state !== localStorage.getItem("latestCSRFToken")) {
|
||||
return;
|
||||
}
|
||||
|
||||
localStorage.removeItem("latestCSRFToken");
|
||||
|
||||
const integrationAuth = await mutateAsync({
|
||||
workspaceId: localStorage.getItem("projectData.id") as string,
|
||||
code: code as string,
|
||||
installationId: installation_id as string,
|
||||
integration: "github"
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import crypto from "crypto";
|
||||
|
||||
import { useCallback, useEffect } from "react";
|
||||
import Head from "next/head";
|
||||
import Image from "next/image";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { Button, Card, CardTitle, ContentLoader } from "@app/components/v2";
|
||||
import { useOrganization, useWorkspace } from "@app/context";
|
||||
import {
|
||||
useDuplicateIntegrationAuth,
|
||||
useGetCloudIntegrations,
|
||||
useGetOrgIntegrationAuths
|
||||
} from "@app/hooks/api";
|
||||
import { IntegrationAuth } from "@app/hooks/api/types";
|
||||
|
||||
export default function SelectIntegrationAuthPage() {
|
||||
const router = useRouter();
|
||||
const { data: cloudIntegrations } = useGetCloudIntegrations();
|
||||
const { currentOrg } = useOrganization();
|
||||
const { currentWorkspace } = useWorkspace();
|
||||
const orgId = currentOrg?.id || "";
|
||||
|
||||
const integrationSlug = router.query.integrationSlug as string;
|
||||
|
||||
const currentIntegration = cloudIntegrations?.find(
|
||||
(integration) => integration.slug === integrationSlug
|
||||
);
|
||||
const { mutateAsync: duplicateIntegrationAuth, isLoading: isIntegrationAuthSelectLoading } =
|
||||
useDuplicateIntegrationAuth();
|
||||
|
||||
// for Github, we want to reuse the same connection across the Infisical organization
|
||||
// when we do need to reuse this page for other integrations, add handling to fetch workspace integration auths instead
|
||||
const {
|
||||
data: integrationAuths,
|
||||
isLoading: isLoadingIntegrationAuths,
|
||||
isSuccess: isLoadingIntegrationAuthsSuccess
|
||||
} = useGetOrgIntegrationAuths(
|
||||
orgId,
|
||||
useCallback(
|
||||
(data: IntegrationAuth[]) => {
|
||||
const filteredIntegrationAuths = data.filter(
|
||||
(integrationAuth) => integrationAuth.integration === integrationSlug
|
||||
);
|
||||
|
||||
if (integrationSlug === "github") {
|
||||
const sameProjectIntegrationAuths = filteredIntegrationAuths.filter(
|
||||
(auth) => auth.projectId === currentWorkspace?.id
|
||||
);
|
||||
const differentProjectIntegrationAuths = filteredIntegrationAuths.filter(
|
||||
(auth) => auth.projectId !== currentWorkspace?.id
|
||||
);
|
||||
|
||||
const installationIds = new Set<string>();
|
||||
|
||||
// for now, we only display the integration auths for Github apps
|
||||
return (
|
||||
// we concatenate it this way so that integration auths from the same project are prioritized for display
|
||||
sameProjectIntegrationAuths
|
||||
.concat(differentProjectIntegrationAuths)
|
||||
.filter((integrationAuth) => Boolean(integrationAuth.metadata?.installationId))
|
||||
// we filter it so that we only show unique installations because the same installation/connection
|
||||
// can be used in multiple integration auths
|
||||
.filter((integrationAuth) => {
|
||||
const isProcessedInstallationId = installationIds.has(
|
||||
integrationAuth.metadata.installationId as string
|
||||
);
|
||||
|
||||
if (!isProcessedInstallationId) {
|
||||
installationIds.add(integrationAuth.metadata.installationId as string);
|
||||
}
|
||||
|
||||
return !isProcessedInstallationId;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return [];
|
||||
},
|
||||
[integrationSlug]
|
||||
)
|
||||
);
|
||||
|
||||
const handleNewConnection = () => {
|
||||
const state = crypto.randomBytes(16).toString("hex");
|
||||
localStorage.setItem("latestCSRFToken", state);
|
||||
|
||||
if (integrationSlug === "github") {
|
||||
// for now we only handle Github apps
|
||||
window.location.assign(
|
||||
`https://github.com/apps/${currentIntegration?.clientSlug}/installations/new?state=${state}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!isLoadingIntegrationAuths &&
|
||||
integrationAuths?.length === 0 &&
|
||||
isLoadingIntegrationAuthsSuccess
|
||||
) {
|
||||
handleNewConnection();
|
||||
}
|
||||
}, [isLoadingIntegrationAuths, integrationAuths, isLoadingIntegrationAuthsSuccess]);
|
||||
|
||||
const logo = integrationSlug === "github" ? "/images/integrations/GitHub.png" : "";
|
||||
|
||||
const handleConnectionSelect = async (integrationAuth: IntegrationAuth) => {
|
||||
if (integrationSlug === "github") {
|
||||
if (integrationAuth.projectId === currentWorkspace?.id) {
|
||||
router.push(`/integrations/github/create?integrationAuthId=${integrationAuth.id}`);
|
||||
} else {
|
||||
// we create a copy of the existing integration auth from another project to the current project
|
||||
const newIntegrationAuth = await duplicateIntegrationAuth({
|
||||
projectId: currentWorkspace?.id || "",
|
||||
integrationAuthId: integrationAuth.id
|
||||
});
|
||||
|
||||
router.push(`/integrations/github/create?integrationAuthId=${newIntegrationAuth.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (
|
||||
isLoadingIntegrationAuths ||
|
||||
(integrationAuths?.length === 0 && isLoadingIntegrationAuthsSuccess)
|
||||
) {
|
||||
return <ContentLoader />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<Head>
|
||||
<title>Select Connection</title>
|
||||
<link rel="icon" href="/infisical.ico" />
|
||||
</Head>
|
||||
<Card className="mb-12 max-w-lg rounded-md border border-mineshaft-600">
|
||||
<CardTitle
|
||||
className="px-6 text-left text-xl"
|
||||
subTitle="Select an existing connection below or create a new one for your integration."
|
||||
>
|
||||
<div className="flex flex-row items-center">
|
||||
<div className="flex items-center pb-0.5">
|
||||
<Image src={logo} height={30} width={30} alt="Integration logo" />
|
||||
</div>
|
||||
<span className="ml-2.5">Select Connection</span>
|
||||
</div>
|
||||
</CardTitle>
|
||||
<div className="mb-7 flex flex-col items-center">
|
||||
{!isLoadingIntegrationAuths && integrationAuths?.length
|
||||
? integrationAuths.map((integrationAuth) => {
|
||||
let connectionName = "";
|
||||
|
||||
if (integrationAuth.integration === "github") {
|
||||
connectionName = integrationAuth.metadata?.installationName || "";
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
colorSchema="secondary"
|
||||
className="mt-3 w-3/4"
|
||||
isDisabled={isIntegrationAuthSelectLoading}
|
||||
key={integrationAuth.id}
|
||||
size="sm"
|
||||
type="submit"
|
||||
onClick={() => handleConnectionSelect(integrationAuth)}
|
||||
>
|
||||
{connectionName}
|
||||
</Button>
|
||||
);
|
||||
})
|
||||
: undefined}
|
||||
<div className="mt-6 flex w-full flex-row items-center justify-center">
|
||||
<div className="w-1/5 border-t border-mineshaft-400" />
|
||||
<p className="mx-4 text-xs text-gray-400">OR</p>
|
||||
<div className="w-1/5 border-t border-mineshaft-400" />
|
||||
</div>
|
||||
<Button
|
||||
colorSchema="primary"
|
||||
className="mt-6 w-3/4"
|
||||
size="sm"
|
||||
type="submit"
|
||||
onClick={handleNewConnection}
|
||||
>
|
||||
Create New Connection
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
SelectIntegrationAuthPage.requireAuth = true;
|
||||
@@ -60,7 +60,7 @@ export const redirectForProviderAuth = (integrationOption: TCloudIntegration) =>
|
||||
link = `https://app.netlify.com/authorize?client_id=${integrationOption.clientId}&response_type=code&state=${state}&redirect_uri=${window.location.origin}/integrations/netlify/oauth2/callback`;
|
||||
break;
|
||||
case "github":
|
||||
link = `https://github.com/login/oauth/authorize?client_id=${integrationOption.clientId}&response_type=code&scope=repo,admin:org&redirect_uri=${window.location.origin}/integrations/github/oauth2/callback&state=${state}`;
|
||||
link = `${window.location.origin}/integrations/github/auth-mode-selection`;
|
||||
break;
|
||||
case "gitlab":
|
||||
link = `${window.location.origin}/integrations/gitlab/authorize`;
|
||||
|
||||
Reference in New Issue
Block a user