Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
list instalations
Thiago Araujo da Silvad1170f8b2dce
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex c26587c7e5..9eaf0399dc 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -90,6 +90,7 @@ export const KeyStorePrefixes = {UsedAccountRecoveryToken: (userId: string, jti: string) => `used-account-recovery-token:${userId}:${jti}` as const,UsedGitHubManifestState: (jti: string) => `used-github-manifest-state:${jti}` as const,GitHubManifestNameLock: (orgId: string, name: string) => `github-manifest-name-lock:${orgId}:${name}` as const,+ UsedGitHubInstallationsToken: (jti: string) => `used-github-installations-token:${jti}` as const,AiMcpServerOAuth: (sessionId: string) => `ai-mcp-server-oauth:${sessionId}` as const,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 206503e4c6..ee0d9e4c57 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2512,7 +2512,8 @@ export const registerRoutes = async (projectDAL,appConnectionCredentialRotationService,identityUaDAL,- gitHubAppDAL+ gitHubAppDAL,+ keyStore});const honeyTokenConfigService = honeyTokenConfigServiceFactory({diff --git a/backend/src/server/routes/v1/github-app-router.ts b/backend/src/server/routes/v1/github-app-router.tsindex 29516ef421..317b0fe61d 100644--- a/backend/src/server/routes/v1/github-app-router.ts+++ b/backend/src/server/routes/v1/github-app-router.ts@@ -10,6 +10,7 @@ const SanitizedGitHubAppSchema = z.object({name: z.string(),appId: z.string(),slug: z.string(),+ clientId: z.string().nullable(),owner: z.string().nullable(),connectionCount: z.number(),createdAt: z.date().nullable(),@@ -100,27 +101,41 @@ export const registerGitHubAppRouter = async (server: FastifyZodProvider) => {});server.route({- method: "GET",- url: "/installation-status",+ method: "POST",+ url: "/resolve-installations",config: {- rateLimit: readLimit+ rateLimit: writeLimit},onRequest: verifyAuth([AuthMode.JWT]),schema: {- querystring: z.object({- gitHubAppId: z.string().uuid().optional()+ body: z.object({+ code: z.string().trim().min(1),+ gitHubAppId: z.string().uuid().optional(),+ host: z.string().trim().optional(),+ instanceType: z.enum(["cloud", "server"]).optional(),+ projectId: z.string().optional()}),response: {200: z.object({- installed: z.boolean(),- clientId: z.string()+ installations: z+ .object({+ id: z.string(),+ accountLogin: z.string(),+ accountType: z.string()+ })+ .array(),+ installationsToken: z.string()})}},handler: async (req) => {- const result = await server.services.gitHubApp.getInstallationStatus({+ const result = await server.services.gitHubApp.resolveUserInstallations({orgPermission: req.permission,- gitHubAppId: req.query.gitHubAppId+ code: req.body.code,+ gitHubAppId: req.body.gitHubAppId,+ host: req.body.host,+ instanceType: req.body.instanceType,+ projectId: req.body.projectId});return result;diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex d1526bb271..638f1f5032 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -15,6 +15,7 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { SECRET_ROTATION_CONNECTION_MAP } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-maps";import { SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-maps";+import { TKeyStoreFactory } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError } from "@app/lib/errors";import { APP_CONNECTION_NAME_MAP, APP_CONNECTION_PLAN_MAP } from "@app/services/app-connection/app-connection-maps";@@ -507,6 +508,8 @@ export const validateAppConnectionCredentials = async (identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;+ actorId?: string;}): Promise<TAppConnection["credentials"]> => {const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TAppConnectionCredentialsValidator> = {@@ -515,7 +518,9 @@ export const validateAppConnectionCredentials = async ([AppConnection.GitHub]: ((config: TAppConnectionConfig, gw, gw2) =>validateGitHubConnectionCredentials(config as TGitHubConnectionConfig, gw, gw2, {gitHubAppDAL: deps.gitHubAppDAL,- kmsService: deps.kmsService+ kmsService: deps.kmsService,+ keyStore: deps.keyStore,+ actorId: deps.actorId})) as TAppConnectionCredentialsValidator,[AppConnection.GitHubRadar]: validateGitHubRadarConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.GCP]: validateGcpConnectionCredentials as TAppConnectionCredentialsValidator,diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 120af6b268..2f19cb137a 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -23,6 +23,7 @@ import {ProjectPermissionAppConnectionActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import { TKeyStoreFactory } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto/cryptography";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";@@ -187,6 +188,7 @@ export type TAppConnectionServiceFactoryDep = {appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "upsertConnectionLink">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;};export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;@@ -275,7 +277,8 @@ export const appConnectionServiceFactory = ({projectDAL,appConnectionCredentialRotationService,identityUaDAL,- gitHubAppDAL+ gitHubAppDAL,+ keyStore}: TAppConnectionServiceFactoryDep) => {const listAppConnections = async (actor: OrgServiceActor, app?: AppConnection, projectId?: string) => {let appConnections: TAppConnections[];@@ -542,7 +545,7 @@ export const appConnectionServiceFactory = ({} as TAppConnectionConfig,gatewayService,gatewayV2Service,- { identityUaDAL, gitHubAppDAL, kmsService }+ { identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id });try {@@ -815,7 +818,7 @@ export const appConnectionServiceFactory = ({} as TAppConnectionConfig,gatewayService,gatewayV2Service,- { identityUaDAL, gitHubAppDAL, kmsService }+ { identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id });if (!updatedCredentials)diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.tsindex f8a64c1618..e598f4c9c0 100644--- a/backend/src/services/app-connection/github/github-connection-fns.ts+++ b/backend/src/services/app-connection/github/github-connection-fns.ts@@ -6,6 +6,7 @@ import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamicimport { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { request as httpRequest } from "@app/lib/config/request";import { crypto } from "@app/lib/crypto";@@ -103,6 +104,23 @@ export const resolveGitHubAppCredentials = async (};};+export type TGitHubAppInstallationsTokenPayload = {+ jti: string;+ orgId: string;+ actorId: string;+ gitHubAppId: string | null;+ host: string;+ instanceType: "cloud" | "server";+ installationIds: string[];+};++export const GITHUB_APP_INSTALLATIONS_TOKEN_TTL = "10m";++export const signGitHubAppInstallationsToken = (payload: TGitHubAppInstallationsTokenPayload) => {+ const { AUTH_SECRET } = getConfig();+ return crypto.jwt().sign(payload, AUTH_SECRET, { expiresIn: GITHUB_APP_INSTALLATIONS_TOKEN_TTL });+};+export const getGitHubConnectionListItem = () => {const { INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_ID, INF_APP_CONNECTION_GITHUB_APP_SLUG } = getConfig();@@ -641,14 +659,13 @@ export const validateGitHubConnectionCredentials = async (config: TGitHubConnectionConfig,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- deps: TGitHubAppCredentialResolverDeps+ deps: TGitHubAppCredentialResolverDeps & {+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;+ actorId?: string;+ }) => {const { credentials, method } = config;- // For org-managed GitHub App connections, bind the connection to the host/instance the app was- // registered against BEFORE any credential is used or any request host is derived. Without this,- // a user could create an app-method connection that references an existing app but supplies a- // custom host they control, causing the app's client secret / signed JWT to be sent there.let resolvedAppCredentials: TResolvedGitHubAppCredentials | undefined;if (method === GitHubConnectionMethod.App) {resolvedAppCredentials = await resolveGitHubAppCredentials(@@ -663,6 +680,77 @@ export const validateGitHubConnectionCredentials = async (}}+ if (method === GitHubConnectionMethod.App && credentials.installationsToken) {+ const { AUTH_SECRET } = getConfig();++ let tokenPayload: TGitHubAppInstallationsTokenPayload & { exp: number };+ try {+ tokenPayload = crypto+ .jwt()+ .verify(credentials.installationsToken, AUTH_SECRET) as TGitHubAppInstallationsTokenPayload & { exp: number };+ } catch {+ throw new BadRequestError({+ message: "Invalid or expired GitHub installation token. Please reconnect and try again."+ });+ }++ if (!tokenPayload.jti || !Array.isArray(tokenPayload.installationIds)) {+ throw new BadRequestError({+ message: "Invalid or expired GitHub installation token. Please reconnect and try again."+ });+ }++ const ttlSeconds = Math.max(1, tokenPayload.exp - Math.floor(Date.now() / 1000));+ const claimed = await deps.keyStore.setItemWithExpiryNX(+ KeyStorePrefixes.UsedGitHubInstallationsToken(tokenPayload.jti),+ ttlSeconds,+ "1"+ );+ if (!claimed) {+ throw new BadRequestError({+ message: "This GitHub installation token has already been used. Please reconnect and try again."+ });+ }++ if (tokenPayload.orgId !== config.orgId || (deps.actorId && tokenPayload.actorId !== deps.actorId)) {+ throw new ForbiddenRequestError({+ message: "GitHub installation token does not belong to this actor or organization."+ });+ }++ if ((tokenPayload.gitHubAppId ?? null) !== (credentials.gitHubAppId ?? null)) {+ throw new BadRequestError({+ message: "GitHub installation token was issued for a different GitHub App."+ });+ }++ if (!tokenPayload.installationIds.includes(credentials.installationId)) {+ throw new ForbiddenRequestError({+ message: "User does not have access to the provided installation"+ });+ }++ const boundHost = credentials.gitHubAppId+ ? (resolvedAppCredentials!.host ?? undefined)+ : tokenPayload.host || undefined;+ const boundInstanceType = credentials.gitHubAppId+ ? (resolvedAppCredentials!.instanceType ?? "cloud")+ : tokenPayload.instanceType;++ assertPlatformGitHubHostAllowed(boundHost);++ return {+ installationId: credentials.installationId,+ gitHubAppId: credentials.gitHubAppId ?? null,+ instanceType: boundInstanceType,+ host: boundHost+ };+ }++ if (method === GitHubConnectionMethod.App && !credentials.code) {+ throw new BadRequestError({ message: "GitHub App code required" });+ }+const apiBaseUrl = await getGitHubInstanceApiUrl(config);const gatewayConnectionDetails = config.gatewayId? await getGitHubGatewayConnectionDetails(config.gatewayId, apiBaseUrl, gatewayV2Service)diff --git a/backend/src/services/app-connection/github/github-connection-schemas.ts b/backend/src/services/app-connection/github/github-connection-schemas.tsindex de1150a72b..e5b356e498 100644--- a/backend/src/services/app-connection/github/github-connection-schemas.ts+++ b/backend/src/services/app-connection/github/github-connection-schemas.ts@@ -24,22 +24,33 @@ 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"),- 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"),- gitHubAppId: z.string().uuid().nullish(),- instanceType: z.literal("cloud").optional(),- host: z.string().trim().optional()- })-]);+export const GitHubConnectionAppInputCredentialsSchema = z+ .union([+ z.object({+ code: z.string().trim().min(1, "GitHub App code required").optional(),+ installationsToken: z.string().trim().min(1).optional(),+ installationId: z.string().min(1, "GitHub App Installation ID required"),+ 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").optional(),+ installationsToken: z.string().trim().min(1).optional(),+ installationId: z.string().min(1, "GitHub App Installation ID required"),+ gitHubAppId: z.string().uuid().nullish(),+ instanceType: z.literal("cloud").optional(),+ host: z.string().trim().optional()+ })+ ])+ .superRefine((credentials, ctx) => {+ if (Boolean(credentials.code) === Boolean(credentials.installationsToken)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Exactly one of code or installationsToken must be provided"+ });+ }+ });export const GitHubConnectionPatInputCredentialsSchema = z.union([z.object({diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.tsindex ce55d6d25c..a14d9bb523 100644--- a/backend/src/services/github-app/github-app-service.ts+++ b/backend/src/services/github-app/github-app-service.ts@@ -2,9 +2,17 @@ import { ForbiddenError } from "@casl/ability";import { AxiosError } from "axios";import jwt from "jsonwebtoken";-import { OrganizationActionScope } from "@app/db/schemas";-import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";+import {+ OrgPermissionActions,+ OrgPermissionAppConnectionActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAppConnectionActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";@@ -16,7 +24,10 @@ import {assertPlatformGitHubHostAllowed,buildGitHubAppJwtHeaders,getGitHubInstanceApiUrl,+ GithubTokenRespData,+ isGithubErrorResponse,resolveGitHubAppCredentials,+ signGitHubAppInstallationsToken,signGitHubAppJwt} from "@app/services/app-connection/github/github-connection-fns";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";@@ -26,17 +37,18 @@ import { KmsDataKey } from "@app/services/kms/kms-types";import { TGitHubAppDALFactory } from "./github-app-dal";import {TDeleteGitHubAppDTO,- TGetGitHubAppInstallationStatusDTO,+ TGitHubAppInstallation,TGitHubAppManifestResponse,TGitHubManifestStatePayload,TInitiateGitHubManifestDTO,TListGitHubAppsDTO,+ TResolveGitHubAppInstallationsDTO,TSanitizedGitHubApp} from "./github-app-types";type TGitHubAppServiceFactoryDep = {gitHubAppDAL: TGitHubAppDALFactory;- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem">;};@@ -71,13 +83,18 @@ export const gitHubAppServiceFactory = ({name: app.name,appId: app.appId,slug: app.slug,+ clientId: app.clientId,owner: app.owner ?? null,connectionCount: countByAppId.get(app.id) ?? 0,createdAt: app.createdAt,updatedAt: app.updatedAt}));- const { INF_APP_CONNECTION_GITHUB_APP_ID, INF_APP_CONNECTION_GITHUB_APP_SLUG } = getConfig();+ const {+ INF_APP_CONNECTION_GITHUB_APP_ID,+ INF_APP_CONNECTION_GITHUB_APP_SLUG,+ INF_APP_CONNECTION_GITHUB_APP_CLIENT_ID+ } = getConfig();const sharedApp: TSanitizedGitHubApp | null =INF_APP_CONNECTION_GITHUB_APP_ID && INF_APP_CONNECTION_GITHUB_APP_SLUG@@ -87,8 +104,8 @@ export const gitHubAppServiceFactory = ({name: INF_APP_CONNECTION_GITHUB_APP_SLUG,appId: INF_APP_CONNECTION_GITHUB_APP_ID,slug: INF_APP_CONNECTION_GITHUB_APP_SLUG,+ clientId: INF_APP_CONNECTION_GITHUB_APP_CLIENT_ID ?? null,owner: null,- // connections referencing the instance-default app store a null gitHubAppIdconnectionCount: countByAppId.get(null) ?? 0,createdAt: null,updatedAt: null@@ -202,6 +219,7 @@ export const gitHubAppServiceFactory = ({name: existing.name,appId: existing.appId,slug: existing.slug,+ clientId: existing.clientId,owner: existing.owner ?? null,connectionCount: 0,createdAt: existing.createdAt,@@ -448,68 +466,160 @@ 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 ({+ const resolveUserInstallations = async ({+ code,gitHubAppId,+ host,+ instanceType,+ projectId,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- });+ }: TResolveGitHubAppInstallationsDTO): Promise<{+ installations: TGitHubAppInstallation[];+ installationsToken: string;+ }> => {+ // mirror the permission required to create the connection this flow feeds into+ if (projectId) {+ const { permission } = await permissionService.getProjectPermission({+ actor: orgPermission.type,+ actorId: orgPermission.id,+ projectId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId,+ actionProjectType: ActionProjectType.Any+ });- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAppConnectionActions.Create,+ ProjectPermissionSub.AppConnections+ );+ } else {+ 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(+ OrgPermissionAppConnectionActions.Create,+ OrgPermissionSubjects.AppConnections+ );+ }++ const { SITE_URL } = getConfig();+ if (!SITE_URL) {+ throw new BadRequestError({ message: "SITE_URL is not configured." });+ }const {appId,clientId,- privateKey,+ clientSecret,host: appHost,instanceType: appInstanceType} = await resolveGitHubAppCredentials({ gitHubAppId: gitHubAppId ?? null, orgId: orgPermission.orgId },- { gitHubAppDAL, kmsService }+ {+ gitHubAppDAL,+ kmsService+ });- // The host/instance is never taken from the caller. For an org-managed app it is bound to the- // stored app record; for the instance-default (shared) app there is no host env var to bind it- // elsewhere, so it is only ever registered against the platform default host (github.com). This- // is what prevents a settings reader from pointing the app's signed JWT at a host they control- // to exfiltrate it.- const effectiveHost = gitHubAppId ? (appHost ?? undefined) : undefined;- const effectiveInstanceType = gitHubAppId ? (appInstanceType ?? "cloud") : "cloud";+ const effectiveHost = gitHubAppId ? (appHost ?? undefined) : host || undefined;+ const effectiveInstanceType: "cloud" | "server" = gitHubAppId+ ? (appInstanceType ?? "cloud")+ : (instanceType ?? "cloud");assertPlatformGitHubHostAllowed(effectiveHost);- // validates the host against local/private addresses internally- const apiBaseUrl = await getGitHubInstanceApiUrl({- credentials: { host: effectiveHost, instanceType: effectiveInstanceType }- });-- const appJwt = signGitHubAppJwt(appId, privateKey);+ const oauthHost = effectiveHost ?? "github.com";+ let tokenData: GithubTokenRespData;try {- // safeRequest validates + DNS-pins the target and disables redirects, so a public host- // cannot redirect this request to an internal service (SSRF).- const { data } = await safeRequest.get<{ id: number }[]>(`https://${apiBaseUrl}/app/installations`, {- params: { per_page: 1 },- headers: buildGitHubAppJwtHeaders(appJwt)+ const { data } = await safeRequest.post<GithubTokenRespData>(+ `https://${oauthHost}/login/oauth/access_token`,+ {+ client_id: clientId,+ client_secret: clientSecret,+ code,+ redirect_uri: `${SITE_URL}/organization/app-connections/github/oauth/callback`+ },+ {+ headers: {+ Accept: "application/json",+ "Content-Type": "application/json"+ }+ }+ );+ tokenData = data;+ } catch (err) {+ logger.error(err, `Failed to exchange GitHub OAuth code [gitHubAppId=${gitHubAppId ?? "shared"}]`);+ throw new BadRequestError({+ message: "Unable to authorize with GitHub. The code may be expired or invalid. Please try again."});+ }- return { installed: data.length > 0, clientId };- } catch (err) {- logger.error(err, `Failed to check GitHub App installation status [gitHubAppId=${gitHubAppId ?? "shared"}]`);+ if (isGithubErrorResponse(tokenData) || !tokenData.access_token) {throw new BadRequestError({- message: "Unable to check GitHub App installation status. Verify the app still exists on GitHub."+ message: "Unable to authorize with GitHub. The code may be expired or invalid. Please try again."});}++ const apiBaseUrl = await getGitHubInstanceApiUrl({+ credentials: { host: effectiveHost, instanceType: effectiveInstanceType }+ });++ type TUserInstallation = {+ id: number;+ app_id: number;+ account: { login: string; type: string };+ };++ const installations: TUserInstallation[] = [];+ const MAX_PAGES = 100;+ for (let page = 1; page <= MAX_PAGES; page++) {+ const { data } = await safeRequest.get<{ installations: TUserInstallation[] }>(+ `https://${apiBaseUrl}/user/installations`,+ {+ params: { per_page: 100, page },+ headers: {+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${tokenData.access_token}`,+ "X-GitHub-Api-Version": "2022-11-28"+ }+ }+ );++ const pageInstallations = data.installations ?? [];+ installations.push(...pageInstallations);++ if (pageInstallations.length < 100) {+ break;+ }+ }++ const appInstallations = installations.filter((installation) => String(installation.app_id) === appId);++ const installationsToken = signGitHubAppInstallationsToken({+ jti: crypto.nativeCrypto.randomUUID(),+ orgId: orgPermission.orgId,+ actorId: orgPermission.id,+ gitHubAppId: gitHubAppId ?? null,+ host: effectiveHost ?? "",+ instanceType: effectiveInstanceType,+ installationIds: appInstallations.map((installation) => String(installation.id))+ });++ return {+ installations: appInstallations.map((installation) => ({+ id: String(installation.id),+ accountLogin: installation.account.login,+ accountType: installation.account.type+ })),+ installationsToken+ };};return {@@ -517,6 +627,6 @@ export const gitHubAppServiceFactory = ({handleManifestCallback,listGitHubApps,deleteGitHubApp,- getInstallationStatus+ resolveUserInstallations};};diff --git a/backend/src/services/github-app/github-app-types.ts b/backend/src/services/github-app/github-app-types.tsindex 3ed5e362fd..dff11443ce 100644--- a/backend/src/services/github-app/github-app-types.ts+++ b/backend/src/services/github-app/github-app-types.ts@@ -10,8 +10,6 @@ export type TInitiateGitHubManifestDTO = {};export type TGitHubManifestStatePayload = {- // Unique, single-use identifier. Consumed (claimed in the key store) on the first callback so a- // captured state token cannot be replayed within its validity window.jti: string;orgId: string;actorId: string;@@ -33,11 +31,21 @@ export type TDeleteGitHubAppDTO = {orgPermission: OrgServiceActor;};-export type TGetGitHubAppInstallationStatusDTO = {+export type TResolveGitHubAppInstallationsDTO = {+ code: string;gitHubAppId?: string;+ host?: string;+ instanceType?: "cloud" | "server";+ projectId?: string;orgPermission: OrgServiceActor;};+export type TGitHubAppInstallation = {+ id: string;+ accountLogin: string;+ accountType: string;+};+export type TGitHubAppManifestResponse = {id: number;slug: string;@@ -56,6 +64,7 @@ export type TSanitizedGitHubApp = {name: string;appId: string;slug: string;+ clientId: string | null;owner: string | null;connectionCount: number;createdAt: Date | null;diff --git a/frontend/src/hooks/api/appConnections/types/github-connection.ts b/frontend/src/hooks/api/appConnections/types/github-connection.tsindex 1fb2b56975..a435eba556 100644--- a/frontend/src/hooks/api/appConnections/types/github-connection.ts+++ b/frontend/src/hooks/api/appConnections/types/github-connection.ts@@ -19,10 +19,9 @@ export type TGitHubConnection = TRootAppConnection & { app: AppConnection.GitHub| {method: GitHubConnectionMethod.App;credentials: {- code: string;- // omitted in the already-installed app flow — the backend resolves the installation- // from the authorizing user's access- installationId?: string;+ code?: string;+ installationsToken?: string;+ 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.tsindex 2d2c26eacc..afd5240cb2 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 { fetchGitHubAppInstallationStatus, gitHubAppKeys, useListGitHubApps } from "./queries";-export type { TGitHubApp } from "./types";+export { gitHubAppKeys, resolveGitHubAppInstallations, useListGitHubApps } from "./queries";+export type { TGitHubApp, TGitHubAppInstallation } from "./types";diff --git a/frontend/src/hooks/api/gitHubApps/queries.tsx b/frontend/src/hooks/api/gitHubApps/queries.tsxindex 69d2ae798f..929de61fba 100644--- a/frontend/src/hooks/api/gitHubApps/queries.tsx+++ b/frontend/src/hooks/api/gitHubApps/queries.tsx@@ -2,7 +2,7 @@ import { useQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { TGitHubApp } from "./types";+import { TGitHubApp, TGitHubAppInstallation } from "./types";export const gitHubAppKeys = {all: ["github-apps"] as const,@@ -14,13 +14,17 @@ 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 }) => {- const { data } = await apiRequest.get<{ installed: boolean; clientId: string }>(- "/api/v1/github-apps/installation-status",- { params }- );+export const resolveGitHubAppInstallations = async (params: {+ code: string;+ gitHubAppId?: string;+ host?: string;+ instanceType?: "cloud" | "server";+ projectId?: string;+}) => {+ const { data } = await apiRequest.post<{+ installations: TGitHubAppInstallation[];+ installationsToken: string;+ }>("/api/v1/github-apps/resolve-installations", params);return data;};diff --git a/frontend/src/hooks/api/gitHubApps/types.ts b/frontend/src/hooks/api/gitHubApps/types.tsindex 54a4f3b218..6f70e2d171 100644--- a/frontend/src/hooks/api/gitHubApps/types.ts+++ b/frontend/src/hooks/api/gitHubApps/types.ts@@ -4,8 +4,15 @@ export type TGitHubApp = {name: string;appId: string;slug: string;+ clientId: string | null;owner: string | null;connectionCount: number;createdAt: string | null;updatedAt: string | null;};++export type TGitHubAppInstallation = {+ id: string;+ accountLogin: string;+ accountType: string;+};diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsxindex b1699ac45b..45b8ecb31a 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx@@ -230,7 +230,8 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Proconst storeConnectionFormData = (formData: FormData,installState: string,- gitHubAppId?: string | null+ gitHubAppId?: string | null,+ appSlug?: string) => {localStorage.setItem(CSRF_TOKEN_STORAGE_KEY, installState);localStorage.setItem(@@ -241,6 +242,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro...(formData.credentials as TGitHubConnection["credentials"]),...(gitHubAppId ? { gitHubAppId } : {})},+ ...(appSlug ? { appSlug } : {}),connectionId: appConnection?.id,projectId,returnUrl@@ -248,10 +250,6 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro);};- // Kicks off GitHub App manifest creation, then redirects to GitHub to create + install the app.- // This only creates the GitHub App — when the user returns they land back on this form with the- // new app selected and complete the connection separately, so the connection fields aren't- // required here (only the GitHub App name, which the selector validates).const handleCreateApp = async ({ name, githubOrg }: { name: string; githubOrg: string }) => {const formData = form.getValues();setIsRedirecting(true);@@ -308,13 +306,16 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Procase GitHubConnectionMethod.App: {const targetApp = isUpdate ? reconnectApp : selectedGitHubApp;const slug = targetApp?.slug ?? appClientSlug;- // 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);- // Always route through GitHub's install flow so the user explicitly selects the target- // account; GitHub redirects back with the chosen installation_id, which the backend binds- // directly (no server-side guessing of which installation to use).+ storeConnectionFormData(formData, installState, targetApp?.id ?? undefined, slug);++ if (targetApp?.clientId) {+ window.location.assign(+ `${githubHost}/login/oauth/authorize?client_id=${targetApp.clientId}&state=${installState}&redirect_uri=${window.location.origin}/organization/app-connections/github/oauth/callback`+ );+ break;+ }+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.tsxindex 54c13d3e6e..f4da0ff0d2 100644--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx@@ -2,11 +2,13 @@ import { useCallback, useEffect, useState } from "react";import { useNavigate, useParams, useSearch } from "@tanstack/react-router";import { createNotification } from "@app/components/notifications";-import { ContentLoader } from "@app/components/v2";+import { Button, ContentLoader } from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";import {APP_CONNECTION_MAP,consumeCsrfToken,+ CSRF_TOKEN_STORAGE_KEY,+ generateCsrfToken,GITHUB_CONNECTION_FORM_STORAGE_KEY} from "@app/helpers/appConnections";import {@@ -22,6 +24,7 @@ import {useUpdateAppConnection} from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";+import { resolveGitHubAppInstallations, TGitHubAppInstallation } from "@app/hooks/api/gitHubApps";import { IntegrationsListPageTabs } from "@app/types/integrations";import { FormDataMap } from "./OauthCallbackPage.types";@@ -37,10 +40,19 @@ const formDataStorageFieldMap: Partial<Record<AppConnection, string>> = {[AppConnection.Heroku]: "herokuConnectionFormData"};+type TGitHubInstallationPicker = {+ installations: TGitHubAppInstallation[];+ installationsToken: string;+ formData: FormDataMap[AppConnection.GitHub];+};+export const OAuthCallbackPage = () => {const navigate = useNavigate();const [isReady, setIsReady] = useState(false);+ const [gitHubPicker, setGitHubPicker] = useState<TGitHubInstallationPicker | null>(null);+ const [pickedInstallationId, setPickedInstallationId] = useState<string | null>(null);+const search = useSearch({from: ROUTE_PATHS.Organization.AppConnections.OauthCallbackPage.id});@@ -68,6 +80,40 @@ export const OAuthCallbackPage = () => {localStorage.removeItem(dataFieldName!);};+ // Shared post-success step: notify and navigate back to where the connection flow started.+ const finalizeConnection = async (data: {+ returnUrl: string;+ appConnectionName: string;+ connectionId?: string;+ projectId?: string;+ connection: TAppConnection;+ }) => {+ createNotification({+ text: `Successfully ${data.connectionId ? "updated" : "added"} ${data.appConnectionName ? APP_CONNECTION_MAP[data.appConnectionName as AppConnection].name : ""} Connection`,+ type: "success"+ });++ await navigate({+ to: data.returnUrl,+ params: {+ projectId: data.projectId ?? undefined+ },+ search: data.returnUrl.includes("app-connections")+ ? undefined+ : {+ connectionId: data.connection.id,+ connectionName: data.connection.name,+ ...(data.returnUrl.includes("integrations")+ ? {+ selectedTab: localStorage.getItem("pkiSyncFormData")+ ? IntegrationsListPageTabs.PkiSyncs+ : IntegrationsListPageTabs.SecretSyncs+ }+ : {})+ }+ });+ };+const getFormData = <T extends keyof FormDataMap>(app: T): FormDataMap[T] | null => {const dataFieldName = formDataStorageFieldMap[app];@@ -364,12 +410,40 @@ export const OAuthCallbackPage = () => {const { connectionId, name, description, returnUrl, gatewayId, credentials, projectId } =formData;+ const storedGitHubAppId = (credentials as { gitHubAppId?: string | null } | undefined)+ ?.gitHubAppId;++ if (!installationId && formData.method === GitHubConnectionMethod.App) {+ try {+ const result = await resolveGitHubAppInstallations({+ code: code as string,+ gitHubAppId: storedGitHubAppId ?? undefined,+ ...(credentials?.instanceType && { instanceType: credentials.instanceType }),+ ...(credentials?.host && { host: credentials.host }),+ ...(projectId && { projectId })+ });+ setGitHubPicker({ ...result, formData });+ } catch (err) {+ createNotification({+ type: "error",+ text:+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??+ "Failed to resolve GitHub App installations"+ });+ navigate({+ to: returnUrl,+ params: {+ projectId+ }+ });+ }+ return null;+ }+let connection: TAppConnection;try {- const gitHubAppId = (credentials as { gitHubAppId?: string | null } | undefined)?.gitHubAppId;- // App connections always route through GitHub's install flow, which returns an installation_id;- // its presence is what distinguishes an App callback from an OAuth callback.+ const gitHubAppId = storedGitHubAppId;const isAppMethod = Boolean(installationId);const appCredentials = {@@ -413,8 +487,6 @@ export const OAuthCallbackPage = () => {});}} catch (err) {- // surface the failure reason — e.g. the backend couldn't resolve which installation of an- // already-installed app to usecreateNotification({type: "error",text:@@ -439,6 +511,101 @@ export const OAuthCallbackPage = () => {};}, []);+ const completeGitHubAppConnection = async (selectedInstallationId: string) => {+ if (!gitHubPicker) return;++ const { installationsToken, formData } = gitHubPicker;+ const { connectionId, name, description, returnUrl, gatewayId, credentials, projectId } =+ formData;+ const gitHubAppId = (credentials as { gitHubAppId?: string | null } | undefined)?.gitHubAppId;++ setPickedInstallationId(selectedInstallationId);++ try {+ const appCredentials = {+ installationsToken,+ installationId: selectedInstallationId,+ ...(gitHubAppId !== undefined && { gitHubAppId }),+ ...(credentials?.instanceType && { instanceType: credentials.instanceType }),+ ...(credentials?.host && { host: credentials.host })+ };++ let connection: TAppConnection;++ if (connectionId) {+ connection = await updateAppConnection.mutateAsync({+ app: AppConnection.GitHub,+ connectionId,+ credentials: appCredentials,+ gatewayId+ });+ } else {+ connection = await createAppConnection.mutateAsync({+ app: AppConnection.GitHub,+ name,+ description,+ projectId,+ method: GitHubConnectionMethod.App,+ credentials: appCredentials,+ gatewayId+ });+ }++ await finalizeConnection({+ connectionId,+ returnUrl,+ appConnectionName: formData.app,+ projectId,+ connection+ });+ } catch (err) {+ createNotification({+ type: "error",+ text:+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??+ `Failed to ${connectionId ? "update" : "create"} GitHub Connection`+ });+ navigate({+ to: returnUrl,+ params: {+ projectId+ }+ });+ }+ };++ const redirectToGitHubInstall = () => {+ if (!gitHubPicker) return;++ const { formData } = gitHubPicker;++ if (!formData.appSlug) {+ createNotification({+ type: "error",+ text: "Unable to determine the GitHub App to install. Please restart the connection flow."+ });+ navigate({+ to: formData.returnUrl,+ params: {+ projectId: formData.projectId+ }+ });+ return;+ }++ const newState = generateCsrfToken();+ localStorage.setItem(CSRF_TOKEN_STORAGE_KEY, newState);+ localStorage.setItem(GITHUB_CONNECTION_FORM_STORAGE_KEY, JSON.stringify(formData));++ const githubHost = formData.credentials?.host+ ? `https://${formData.credentials.host}`+ : "https://github.com";++ window.location.assign(+ `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${formData.appSlug}/installations/new?state=${newState}`+ );+ };+const handleGitHubRadar = useCallback(async () => {const formData = getFormData(AppConnection.GitHubRadar);if (formData === null) return null;@@ -579,35 +746,57 @@ export const OAuthCallbackPage = () => {}if (data) {- createNotification({- text: `Successfully ${data.connectionId ? "updated" : "added"} ${data.appConnectionName ? APP_CONNECTION_MAP[data.appConnectionName as AppConnection].name : ""} Connection`,- type: "success"- });-- await navigate({- to: data.returnUrl,- params: {- projectId: data.projectId ?? undefined- },- // scott: if it's not an app connection page we need to pass connection details as it's an inline creation- search: data.returnUrl.includes("app-connections")- ? undefined- : {- connectionId: data.connection.id,- connectionName: data.connection.name,- ...(data.returnUrl.includes("integrations")- ? {- selectedTab: localStorage.getItem("pkiSyncFormData")- ? IntegrationsListPageTabs.PkiSyncs- : IntegrationsListPageTabs.SecretSyncs- }- : {})- }- });+ await finalizeConnection(data);}})();}, [isReady]);+ if (gitHubPicker) {+ const hasInstallations = gitHubPicker.installations.length > 0;++ return (+ <div className="flex h-full w-full items-center justify-center">+ <div className="w-full max-w-md rounded-md border border-mineshaft-600 bg-mineshaft-800 p-6">+ <div className="mb-1 text-lg font-medium text-mineshaft-100">+ {hasInstallations ? "Select a GitHub account" : "Install the GitHub App"}+ </div>+ <p className="mb-4 text-sm text-mineshaft-300">+ {hasInstallations+ ? "The GitHub App is already installed on the following accounts. Select the installation to connect, or install the app on another account."+ : "The GitHub App is not installed on any account you have access to. Install it to continue."}+ </p>+ {hasInstallations && (+ <div className="mb-4 flex flex-col gap-2">+ {gitHubPicker.installations.map((installation) => (+ <Button+ key={installation.id}+ variant="outline_bg"+ isFullWidth+ isDisabled={Boolean(pickedInstallationId)}+ isLoading={pickedInstallationId === installation.id}+ onClick={() => completeGitHubAppConnection(installation.id)}+ >+ <div className="flex w-full items-center justify-between">+ <span>{installation.accountLogin}</span>+ <span className="text-xs text-mineshaft-400">{installation.accountType}</span>+ </div>+ </Button>+ ))}+ </div>+ )}+ <Button+ variant={hasInstallations ? "plain" : "outline_bg"}+ isFullWidth+ isDisabled={Boolean(pickedInstallationId)}+ onClick={redirectToGitHubInstall}+ >+ {hasInstallations ? "Install on another account" : "Install GitHub App"}+ </Button>+ </div>+ </div>+ );+ }+return (<div className="flex h-full w-full items-center justify-center"><ContentLoader text="Please wait! Authentication in process." />diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.ts b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.tsindex e2e5e3d681..d5b1a66ac6 100644--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.ts+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.ts@@ -19,7 +19,9 @@ type BaseFormData = {};export type GitHubFormData = BaseFormData &- Pick<TGitHubConnection, "name" | "method" | "description" | "gatewayId" | "credentials">;+ Pick<TGitHubConnection, "name" | "method" | "description" | "gatewayId" | "credentials"> & {+ appSlug?: string;+ };export type GitHubRadarFormData = BaseFormData &Pick<TGitHubRadarConnection, "name" | "method" | "description">;