Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix redirect

Thiago Araujo da Silvad4d2a1cbd693
diff --git a/backend/src/server/routes/v1/github-app-router.ts b/backend/src/server/routes/v1/github-app-router.ts
index f78aa99ec7..19c8ed0ce2 100644
--- a/backend/src/server/routes/v1/github-app-router.ts
+++ b/backend/src/server/routes/v1/github-app-router.ts
@@ -99,6 +99,38 @@ export const registerGitHubAppRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/installation-status",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ querystring: z.object({
+ gitHubAppId: z.string().uuid().optional(),
+ host: z.string().trim().optional(),
+ instanceType: z.enum(["cloud", "server"]).default("cloud")
+ }),
+ response: {
+ 200: z.object({
+ installed: z.boolean(),
+ clientId: z.string()
+ })
+ }
+ },
+ handler: async (req) => {
+ const result = await server.services.gitHubApp.getInstallationStatus({
+ orgPermission: req.permission,
+ gitHubAppId: req.query.gitHubAppId,
+ host: req.query.host,
+ instanceType: req.query.instanceType
+ });
+
+ return result;
+ }
+ });
+
server.route({
method: "DELETE",
url: "/:id",
diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.ts
index 7babcc74ca..6d4f986b14 100644
--- a/backend/src/services/app-connection/github/github-connection-fns.ts
+++ b/backend/src/services/app-connection/github/github-connection-fns.ts
@@ -818,6 +818,8 @@ export const validateGitHubConnectionCredentials = async (
});
}
+ let resolvedInstallationId: string | undefined;
+
if (method === GitHubConnectionMethod.App) {
if (!tokenResp.data.access_token) {
throw new InternalServerError({ message: `Missing access token: ${tokenResp.data.error}` });
@@ -847,21 +849,46 @@ export const validateGitHubConnectionCredentials = async (
gatewayConnectionDetails
);
- const matchingInstallation = installationsResp.data.installations.find(
- (installation) => installation.id === +credentials.installationId
- );
+ // installations are scoped to this GitHub App since the token is a user-to-server token
+ const { installations } = installationsResp.data;
- if (!matchingInstallation) {
- throw new ForbiddenRequestError({
- message: "User does not have access to the provided installation"
- });
+ if (credentials.installationId) {
+ const { installationId } = credentials;
+ const matchingInstallation = installations.find((installation) => installation.id === +installationId);
+
+ if (!matchingInstallation) {
+ throw new ForbiddenRequestError({
+ message: "User does not have access to the provided installation"
+ });
+ }
+
+ resolvedInstallationId = credentials.installationId;
+ } else {
+ // already-installed app flow: GitHub doesn't redirect back through the install page, so the
+ // user only re-authorized via OAuth and the installation must be resolved from their access
+ if (installations.length === 0) {
+ throw new BadRequestError({
+ message:
+ "The GitHub App has no installations accessible to your GitHub account. Install the app on a GitHub account or organization you have access to, then try again."
+ });
+ }
+
+ if (installations.length > 1) {
+ throw new BadRequestError({
+ message: `The GitHub App is installed on multiple GitHub accounts accessible to you (${installations
+ .map((installation) => installation.account.login)
+ .join(", ")}). Unable to determine which installation to use.`
+ });
+ }
+
+ resolvedInstallationId = String(installations[0].id);
}
}
switch (method) {
case GitHubConnectionMethod.App:
return {
- installationId: credentials.installationId,
+ installationId: resolvedInstallationId as string,
gitHubAppId: credentials.gitHubAppId ?? null,
instanceType: credentials.instanceType,
host: credentials.host
diff --git a/backend/src/services/app-connection/github/github-connection-schemas.ts b/backend/src/services/app-connection/github/github-connection-schemas.ts
index de1150a72b..1528845af3 100644
--- a/backend/src/services/app-connection/github/github-connection-schemas.ts
+++ b/backend/src/services/app-connection/github/github-connection-schemas.ts
@@ -27,14 +27,16 @@ export const GitHubConnectionOAuthInputCredentialsSchema = z.union([
export const GitHubConnectionAppInputCredentialsSchema = z.union([
z.object({
code: z.string().trim().min(1, "GitHub App code required"),
- installationId: z.string().min(1, "GitHub App Installation ID required"),
+ // optional: when omitted (already-installed app flow) the installation is resolved from the
+ // installations accessible to the authorizing user
+ installationId: z.string().min(1, "GitHub App Installation ID required").optional(),
gitHubAppId: z.string().uuid().nullish(),
instanceType: z.literal("server"),
host: z.string().trim().min(1, "Host is required for server instance type")
}),
z.object({
code: z.string().trim().min(1, "GitHub App code required"),
- installationId: z.string().min(1, "GitHub App Installation ID required"),
+ installationId: z.string().min(1, "GitHub App Installation ID required").optional(),
gitHubAppId: z.string().uuid().nullish(),
instanceType: z.literal("cloud").optional(),
host: z.string().trim().optional()
diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.ts
index 20489f2a46..8c79e3a151 100644
--- a/backend/src/services/github-app/github-app-service.ts
+++ b/backend/src/services/github-app/github-app-service.ts
@@ -6,10 +6,16 @@ import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/pe
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
+import { crypto } from "@app/lib/crypto";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import {
+ getGitHubInstanceApiUrl,
+ resolveGitHubAppCredentials
+} from "@app/services/app-connection/github/github-connection-fns";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
@@ -17,6 +23,7 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
import { TGitHubAppDALFactory } from "./github-app-dal";
import {
TDeleteGitHubAppDTO,
+ TGetGitHubAppInstallationStatusDTO,
TGitHubAppManifestResponse,
TGitHubManifestStatePayload,
TInitiateGitHubManifestDTO,
@@ -313,10 +320,69 @@ export const gitHubAppServiceFactory = ({
return { redirectUrl: callbackUrl.toString() };
};
+ // Checks whether a GitHub App already has installations. GitHub never redirects back from the
+ // install page when the app is already installed, so the frontend uses this to route those
+ // connections through the OAuth authorize flow instead. Also returns the app's (public) OAuth
+ // client id needed to build the authorize URL.
+ const getInstallationStatus = async ({
+ gitHubAppId,
+ host,
+ instanceType,
+ orgPermission
+ }: TGetGitHubAppInstallationStatusDTO): Promise<{ installed: boolean; clientId: string }> => {
+ const { permission } = await permissionService.getOrgPermission({
+ actor: orgPermission.type,
+ actorId: orgPermission.id,
+ orgId: orgPermission.orgId,
+ actorAuthMethod: orgPermission.authMethod,
+ actorOrgId: orgPermission.orgId,
+ scope: OrganizationActionScope.Any
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
+
+ const { appId, clientId, privateKey } = await resolveGitHubAppCredentials(
+ { gitHubAppId: gitHubAppId ?? null, orgId: orgPermission.orgId },
+ { gitHubAppDAL, kmsService }
+ );
+
+ // validates the host against local/private addresses internally
+ const apiBaseUrl = await getGitHubInstanceApiUrl({ credentials: { host, instanceType } });
+
+ const appPrivateKey = privateKey
+ .split("\n")
+ .map((line) => line.trim())
+ .join("\n");
+
+ const now = Math.floor(Date.now() / 1000);
+ const appJwt = crypto.jwt().sign({ iat: now, exp: now + 5 * 60, iss: appId }, appPrivateKey, {
+ algorithm: "RS256"
+ });
+
+ try {
+ const { data } = await request.get<{ id: number }[]>(`https://${apiBaseUrl}/app/installations`, {
+ params: { per_page: 1 },
+ headers: {
+ Accept: "application/vnd.github+json",
+ Authorization: `Bearer ${appJwt}`,
+ "X-GitHub-Api-Version": "2022-11-28"
+ }
+ });
+
+ return { installed: data.length > 0, clientId };
+ } catch (err) {
+ logger.error(err, `Failed to check GitHub App installation status [gitHubAppId=${gitHubAppId ?? "shared"}]`);
+ throw new BadRequestError({
+ message: "Unable to check GitHub App installation status. Verify the app still exists on GitHub."
+ });
+ }
+ };
+
return {
initiateManifestCreation,
handleManifestCallback,
listGitHubApps,
- deleteGitHubApp
+ deleteGitHubApp,
+ getInstallationStatus
};
};
diff --git a/backend/src/services/github-app/github-app-types.ts b/backend/src/services/github-app/github-app-types.ts
index 18ba0d780e..27fd2994e4 100644
--- a/backend/src/services/github-app/github-app-types.ts
+++ b/backend/src/services/github-app/github-app-types.ts
@@ -30,6 +30,13 @@ export type TDeleteGitHubAppDTO = {
orgPermission: OrgServiceActor;
};
+export type TGetGitHubAppInstallationStatusDTO = {
+ gitHubAppId?: string;
+ host?: string;
+ instanceType?: "cloud" | "server";
+ orgPermission: OrgServiceActor;
+};
+
export type TGitHubAppManifestResponse = {
id: number;
slug: string;
diff --git a/frontend/src/hooks/api/appConnections/types/github-connection.ts b/frontend/src/hooks/api/appConnections/types/github-connection.ts
index d6c3a29261..1fb2b56975 100644
--- a/frontend/src/hooks/api/appConnections/types/github-connection.ts
+++ b/frontend/src/hooks/api/appConnections/types/github-connection.ts
@@ -20,7 +20,9 @@ export type TGitHubConnection = TRootAppConnection & { app: AppConnection.GitHub
method: GitHubConnectionMethod.App;
credentials: {
code: string;
- installationId: string;
+ // omitted in the already-installed app flow — the backend resolves the installation
+ // from the authorizing user's access
+ installationId?: string;
gitHubAppId?: string | null;
instanceType?: "cloud" | "server";
host?: string;
diff --git a/frontend/src/hooks/api/gitHubApps/index.ts b/frontend/src/hooks/api/gitHubApps/index.ts
index 043f44f5fc..2d2c26eacc 100644
--- a/frontend/src/hooks/api/gitHubApps/index.ts
+++ b/frontend/src/hooks/api/gitHubApps/index.ts
@@ -1,3 +1,3 @@
export { useDeleteGitHubApp } from "./mutations";
-export { gitHubAppKeys, useListGitHubApps } from "./queries";
+export { fetchGitHubAppInstallationStatus, gitHubAppKeys, useListGitHubApps } from "./queries";
export type { TGitHubApp } from "./types";
diff --git a/frontend/src/hooks/api/gitHubApps/queries.tsx b/frontend/src/hooks/api/gitHubApps/queries.tsx
index 3caf84e3a7..1c53eee36e 100644
--- a/frontend/src/hooks/api/gitHubApps/queries.tsx
+++ b/frontend/src/hooks/api/gitHubApps/queries.tsx
@@ -14,6 +14,20 @@ const fetchGitHubApps = async () => {
return data.gitHubApps;
};
+// Imperative check used when connecting: already-installed apps must skip GitHub's install page
+// (it never redirects back to Infisical) and go through the OAuth authorize flow instead.
+export const fetchGitHubAppInstallationStatus = async (params: {
+ gitHubAppId?: string;
+ host?: string;
+ instanceType?: "cloud" | "server";
+}) => {
+ const { data } = await apiRequest.get<{ installed: boolean; clientId: string }>(
+ "/api/v1/github-apps/installation-status",
+ { params }
+ );
+ return data;
+};
+
export const useListGitHubApps = (orgId?: string) =>
useQuery({
queryKey: gitHubAppKeys.list(orgId),
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx
index 4b3d1ec472..cf0cac2fbb 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx
@@ -4,10 +4,8 @@ import {
faArrowUpRightFromSquare,
faChevronLeft,
faCircleInfo,
- faLock,
faPlus,
- faTrash,
- faTriangleExclamation
+ faTrash
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import slugify from "@sindresorhus/slugify";
@@ -21,6 +19,7 @@ import {
CommandItem,
CommandList
} from "@app/components/v3/generic/Command";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3/generic/Tooltip";
import { TGitHubApp, useDeleteGitHubApp } from "@app/hooks/api/gitHubApps";
const SHARED_KEY = "__shared__";
@@ -127,36 +126,6 @@ export const GitHubAppSelector = ({
const isInUse = app.connectionCount > 0;
if (deleteTargetId === app.id) {
- if (isInUse) {
- return (
- <div
- key={app.id}
- className="m-1 rounded-md border border-yellow-500/40 bg-yellow-500/5 p-3"
- >
- <div className="flex items-center gap-2 text-sm font-medium text-mineshaft-100">
- <FontAwesomeIcon icon={faTriangleExclamation} className="text-yellow-500" />
- <span>
- Can&apos;t delete <span className="font-mono">{app.name}</span>
- </span>
- </div>
- <p className="mt-1 text-xs leading-relaxed text-mineshaft-300">
- In use by {app.connectionCount} connection{app.connectionCount === 1 ? "" : "s"}.
- Remove the connection{app.connectionCount === 1 ? "" : "s"} before deleting this app.
- </p>
- <div className="mt-3 flex items-center justify-end gap-2">
- <Button
- variant="plain"
- colorSchema="secondary"
- size="xs"
- onClick={() => setDeleteTargetId(null)}
- >
- Cancel
- </Button>
- </div>
- </div>
- );
- }
-
return (
<div key={app.id} className="m-1 rounded-md border border-red-500/40 bg-red-500/5 p-3">
<div className="flex items-center gap-2 text-sm font-medium text-mineshaft-100">
@@ -223,17 +192,39 @@ export const GitHubAppSelector = ({
>
<FontAwesomeIcon icon={faArrowUpRightFromSquare} className="text-xs" />
</button>
- <button
- type="button"
- title="Delete"
- className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-red-400"
- onClick={(e) => {
- e.stopPropagation();
- setDeleteTargetId(app.id);
- }}
- >
- <FontAwesomeIcon icon={faTrash} className="text-xs" />
- </button>
+ {isInUse ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* Native disabled buttons don't fire pointer events, so the tooltip
+ needs a focusable wrapper to open on hover/focus. */}
+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
+ <span tabIndex={0}>
+ <button
+ type="button"
+ disabled
+ className="cursor-not-allowed rounded p-1 text-mineshaft-500"
+ >
+ <FontAwesomeIcon icon={faTrash} className="text-xs" />
+ </button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ Remove the connection{app.connectionCount === 1 ? "" : "s"} before deleting this app.
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <button
+ type="button"
+ title="Delete"
+ className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-red-400"
+ onClick={(e) => {
+ e.stopPropagation();
+ setDeleteTargetId(app.id);
+ }}
+ >
+ <FontAwesomeIcon icon={faTrash} className="text-xs" />
+ </button>
+ )}
</div>
</CommandItem>
);
@@ -321,15 +312,16 @@ export const GitHubAppSelector = ({
"bg-primary/5 ring-1 ring-primary/40 ring-inset data-[selected=true]:bg-primary/10"
)}
>
- <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-sm bg-blue-500/15 text-blue-400">
- <FontAwesomeIcon icon={faLock} />
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-sm bg-mineshaft-600 text-mineshaft-100">
+ <FontAwesomeIcon icon={faGithub} />
</div>
<div className="min-w-0 flex-1">
- <p className="truncate text-sm font-medium text-mineshaft-100">
- Instance default
+ <p className="truncate font-mono text-sm text-mineshaft-100">
+ {sharedApp.name}
</p>
<p className="truncate text-xs text-mineshaft-400">
- Configured by instance admin
+ Instance default · {sharedApp.connectionCount} connection
+ {sharedApp.connectionCount === 1 ? "" : "s"}
</p>
</div>
<div className="flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 data-[selected=true]:opacity-100">
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
index ff89a70c52..dd204a6b4c 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
@@ -38,7 +38,11 @@ import {
useGetAppConnectionOption
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import { TGitHubApp, useListGitHubApps } from "@app/hooks/api/gitHubApps";
+import {
+ fetchGitHubAppInstallationStatus,
+ TGitHubApp,
+ useListGitHubApps
+} from "@app/hooks/api/gitHubApps";
import { GitHubFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
@@ -315,6 +319,32 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
// Custom apps carry an id we persist into credentials; the shared app (id null) resolves
// to the instance-default app on the backend.
storeConnectionFormData(formData, installState, targetApp?.id ?? undefined);
+
+ // GitHub never redirects back from the install page when the app is already installed, so
+ // installed apps go through the OAuth authorize flow instead — the user re-authorizes
+ // (auto-approved if previously authorized) and the backend resolves the installation.
+ // Skipped for the shared app on Infisical Cloud, where installations from unrelated orgs
+ // make the check meaningless.
+ if (targetApp?.id || !isInfisicalCloud()) {
+ try {
+ const { installed, clientId } = await fetchGitHubAppInstallationStatus({
+ gitHubAppId: targetApp?.id ?? undefined,
+ host: formData.credentials?.host || undefined,
+ instanceType: formData.credentials?.instanceType ?? "cloud"
+ });
+
+ if (installed) {
+ window.location.assign(
+ `${githubHost}/login/oauth/authorize?client_id=${clientId}&state=${installState}&redirect_uri=${window.location.origin}/organization/app-connections/github/oauth/callback`
+ );
+ break;
+ }
+ } catch {
+ // fall through to the install flow — first-time installs must keep working even if
+ // the status check is unavailable
+ }
+ }
+
window.location.assign(
`${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${slug}/installations/new?state=${installState}`
);
diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
index 5f4c26dea9..b97de1342a 100644
--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
@@ -365,30 +365,31 @@ export const OAuthCallbackPage = () => {
try {
const gitHubAppId = (credentials as { gitHubAppId?: string | null } | undefined)?.gitHubAppId;
+ // Fresh installs return from GitHub with an installation_id. Already-installed apps come
+ // back through the OAuth authorize flow without one — the stored method tells us it's still
+ // an App connection (the backend resolves the installation from the user's access).
+ const isAppMethod = formData.method === GitHubConnectionMethod.App || Boolean(installationId);
+
+ const appCredentials = {
+ code: code as string,
+ ...(installationId && { installationId: installationId as string }),
+ ...(gitHubAppId !== undefined && { gitHubAppId }),
+ ...(credentials?.instanceType && { instanceType: credentials.instanceType }),
+ ...(credentials?.host && { host: credentials.host })
+ };
+
+ const oauthCredentials = {
+ code: code as string,
+ ...(credentials?.instanceType && { instanceType: credentials.instanceType }),
+ ...(credentials?.host && { host: credentials.host })
+ };
+
if (connectionId) {
connection = await updateAppConnection.mutateAsync({
app: AppConnection.GitHub,
- ...(installationId
- ? {
- connectionId,
- credentials: {
- code: code as string,
- installationId: installationId as string,
- ...(gitHubAppId !== undefined && { gitHubAppId }),
- ...(credentials?.instanceType && { instanceType: credentials.instanceType }),
- ...(credentials?.host && { host: credentials.host })
- },
- gatewayId
- }
- : {
- connectionId,
- credentials: {
- code: code as string,
- ...(credentials?.instanceType && { instanceType: credentials.instanceType }),
- ...(credentials?.host && { host: credentials.host })
- },
- gatewayId
- })
+ connectionId,
+ credentials: isAppMethod ? appCredentials : oauthCredentials,
+ gatewayId
});
} else {
connection = await createAppConnection.mutateAsync({
@@ -396,30 +397,28 @@ export const OAuthCallbackPage = () => {
name,
description,
projectId,
- ...(installationId
+ ...(isAppMethod
? {
method: GitHubConnectionMethod.App,
- credentials: {
- code: code as string,
- ...(credentials?.instanceType && { instanceType: credentials.instanceType }),
- installationId: installationId as string,
- ...(gitHubAppId !== undefined && { gitHubAppId }),
- ...(credentials?.host && { host: credentials.host })
- },
+ credentials: appCredentials,
gatewayId
}
: {
method: GitHubConnectionMethod.OAuth,
- credentials: {
- code: code as string,
- ...(credentials?.instanceType && { instanceType: credentials.instanceType }),
- ...(credentials?.host && { host: credentials.host })
- },
+ credentials: oauthCredentials,
gatewayId
})
});
}
- } catch {
+ } catch (err) {
+ // surface the failure reason — e.g. the backend couldn't resolve which installation of an
+ // already-installed app to use
+ createNotification({
+ type: "error",
+ text:
+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
+ `Failed to ${connectionId ? "update" : "create"} GitHub Connection`
+ });
navigate({
to: returnUrl,
params: {