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
fix unninstall
Thiago Araujo da Silvab000cd71980d
diff --git a/backend/src/db/migrations/20260529204743_create-github-apps.ts b/backend/src/db/migrations/20260529204743_create-github-apps.tsindex ce018c8b70..e8c96285dc 100644--- a/backend/src/db/migrations/20260529204743_create-github-apps.ts+++ b/backend/src/db/migrations/20260529204743_create-github-apps.ts@@ -16,9 +16,6 @@ export async function up(knex: Knex): Promise<void> {t.binary("encryptedPrivateKey").notNullable();t.string("slug").notNullable();t.string("owner").nullable();- // Host + instance type the app was registered against. These are bound to the app so that- // credential operations (signing app JWTs, using the client secret) always target the host- // the app belongs to, never a host supplied by the caller at request time.t.string("host").nullable();t.string("instanceType").notNullable().defaultTo("cloud");t.timestamps(true, true, true);diff --git a/backend/src/server/routes/v1/github-app-router.ts b/backend/src/server/routes/v1/github-app-router.tsindex 19c8ed0ce2..29516ef421 100644--- a/backend/src/server/routes/v1/github-app-router.ts+++ b/backend/src/server/routes/v1/github-app-router.ts@@ -108,9 +108,7 @@ export const registerGitHubAppRouter = async (server: FastifyZodProvider) => {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")+ gitHubAppId: z.string().uuid().optional()}),response: {200: z.object({@@ -122,9 +120,7 @@ export const registerGitHubAppRouter = async (server: FastifyZodProvider) => {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+ gitHubAppId: req.query.gitHubAppId});return result;diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 3400ddc4bd..0a49aed44a 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -26,7 +26,6 @@ import {import { crypto } from "@app/lib/crypto/cryptography";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { DiscriminativePick, OrgServiceActor } from "@app/lib/types";import {decryptAppConnection,@@ -108,11 +107,7 @@ import { ValidateFlyioConnectionCredentialsSchema } from "./flyio";import { flyioConnectionService } from "./flyio/flyio-connection-service";import { ValidateGcpConnectionCredentialsSchema } from "./gcp";import { gcpConnectionService } from "./gcp/gcp-connection-service";-import {- GitHubConnectionMethod,- uninstallGitHubAppInstallation,- ValidateGitHubConnectionCredentialsSchema-} from "./github";+import { GitHubConnectionMethod, ValidateGitHubConnectionCredentialsSchema } from "./github";import { githubConnectionService } from "./github/github-connection-service";import { ValidateGitHubRadarConnectionCredentialsSchema } from "./github-radar";import { githubRadarConnectionService } from "./github-radar/github-radar-connection-service";@@ -190,7 +185,7 @@ export type TAppConnectionServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findProjectById">;appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;- gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "deleteById">;+ gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne">;};export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;@@ -988,25 +983,9 @@ export const appConnectionServiceFactory = ({// TODO (scott): add option to delete all dependencies- if (app === AppConnection.GitHub) {- const decrypted = await decryptAppConnection(appConnection, kmsService);- if (decrypted.method === GitHubConnectionMethod.App) {- // Best-effort uninstall of THIS connection's installation on GitHub. Failures don't block- // local deletion — the user can always remove the installation manually. The underlying- // GitHub App is reusable and intentionally left intact; it's managed separately.- try {- await uninstallGitHubAppInstallation(decrypted, gatewayService, gatewayV2Service, gatewayPoolService, {- gitHubAppDAL,- kmsService- });- } catch (err) {- logger.warn(- { err, connectionId },- `Failed to uninstall GitHub App for connection [connectionId=${connectionId}]`- );- }- }- }+ // Note: for GitHub App connections we intentionally do NOT uninstall the app installation on+ // GitHub or delete the underlying GitHub App — both are reusable across connections and are+ // managed separately (the app via the GitHub Apps settings page, the installation on GitHub).try {const deletedAppConnection = await appConnectionDAL.deleteById(connectionId);diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.tsindex b367a980ef..ba52424ac1 100644--- a/backend/src/services/app-connection/github/github-connection-fns.ts+++ b/backend/src/services/app-connection/github/github-connection-fns.ts@@ -34,9 +34,6 @@ type TResolvedGitHubAppCredentials = {clientId: string;clientSecret: string;privateKey: string;- // Host/instance the app is bound to. Populated for org-managed apps (resolved by id) so callers- // can target the app's own host instead of a caller-supplied one. Null for the instance-default- // app configured via env vars, where callers fall back to their own host handling.host: string | null;instanceType: "cloud" | "server" | null;};@@ -101,7 +98,6 @@ export const resolveGitHubAppCredentials = async (clientId: INF_APP_CONNECTION_GITHUB_APP_CLIENT_ID,clientSecret: INF_APP_CONNECTION_GITHUB_APP_CLIENT_SECRET,privateKey: INF_APP_CONNECTION_GITHUB_APP_PRIVATE_KEY,- // The instance-default app isn't host-bound here; callers keep their existing host handling.host: null,instanceType: null};@@ -275,86 +271,6 @@ export const requestWithGitHubGateway = async <T>();};-export const uninstallGitHubAppInstallation = async (- appConnection: TGitHubConnection,- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,- deps: TGitHubAppCredentialResolverDeps-) => {- if (appConnection.method !== GitHubConnectionMethod.App) {- throw new InternalServerError({ message: "Cannot uninstall a non-app GitHub connection" });- }-- const {- appId,- privateKey,- host: appHost,- instanceType: appInstanceType- } = await resolveGitHubAppCredentials(- { gitHubAppId: appConnection.credentials.gitHubAppId, orgId: appConnection.orgId },- deps- );-- // Bind the signed app JWT to the app's own host, never the host recorded on the connection.- const effectiveCredentials = appConnection.credentials.gitHubAppId- ? { host: appHost ?? undefined, instanceType: appInstanceType ?? "cloud" }- : { host: appConnection.credentials.host, instanceType: appConnection.credentials.instanceType };-- assertPlatformGitHubHostAllowed(effectiveCredentials.host);-- 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"- });-- const apiBaseUrl = await getGitHubInstanceApiUrl({ credentials: effectiveCredentials });- const { installationId } = appConnection.credentials;-- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({- gatewayId: appConnection.gatewayId,- gatewayPoolId: appConnection.gatewayPoolId- });-- const gatewayConnectionDetails = effectiveGatewayId- ? await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service)- : undefined;-- try {- await requestWithGitHubGateway(- { gatewayId: effectiveGatewayId },- gatewayService,- gatewayV2Service,- {- url: `https://${apiBaseUrl}/app/installations/${installationId}`,- method: "DELETE",- headers: {- Accept: "application/vnd.github+json",- Authorization: `Bearer ${appJwt}`,- "X-GitHub-Api-Version": "2022-11-28"- }- },- gatewayConnectionDetails- );- } catch (err) {- // 404 means the installation is already gone (e.g. the user removed it on GitHub before- // deleting the connection in Infisical). That's a no-op success — anything else is logged- // but doesn't block local cleanup.- const status = (err as AxiosError)?.response?.status;- if (status !== 404) {- logger.warn(- { err, installationId, gitHubAppId: appConnection.credentials.gitHubAppId },- `Failed to uninstall GitHub App installation [installationId=${installationId}]`- );- }- }-};-export const getGitHubAppAuthToken = async (appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.tsindex 190f27c4e2..b930a462ad 100644--- a/backend/src/services/github-app/github-app-service.ts+++ b/backend/src/services/github-app/github-app-service.ts@@ -1,4 +1,5 @@import { ForbiddenError } from "@casl/ability";+import { AxiosError } from "axios";import jwt from "jsonwebtoken";import { OrganizationActionScope } from "@app/db/schemas";@@ -96,6 +97,75 @@ export const gitHubAppServiceFactory = ({return sharedApp ? [sharedApp, ...dbApps] : dbApps;};+ // Best-effort removal of every installation of the app on GitHub. Called after the local record+ // is deleted — at that point the app's private key is gone from Infisical, so any installation+ // left behind on GitHub could never be used again anyway. Failures are logged, never surfaced:+ // the user can always uninstall manually from GitHub.+ const uninstallAllGitHubAppInstallations = async (+ credentials: Awaited<ReturnType<typeof resolveGitHubAppCredentials>>,+ gitHubAppId: string+ ) => {+ const { appId, privateKey, host, instanceType } = credentials;++ // The host comes from the stored app record, never the caller — same binding as every other+ // credential operation on the app.+ assertPlatformGitHubHostAllowed(host ?? undefined);++ const apiBaseUrl = await getGitHubInstanceApiUrl({+ credentials: { host: host ?? undefined, instanceType: instanceType ?? "cloud" }+ });++ 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"+ });++ const headers = {+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${appJwt}`,+ "X-GitHub-Api-Version": "2022-11-28"+ };++ const installationIds: number[] = [];+ let page = 1;+ for (;;) {+ // safeRequest validates + DNS-pins the target and disables redirects (SSRF). Pages must be+ // fetched sequentially — we don't know the total count up front.+ // eslint-disable-next-line no-await-in-loop+ const { data } = await safeRequest.get<{ id: number }[]>(`https://${apiBaseUrl}/app/installations`, {+ params: { per_page: 100, page },+ headers+ });+ installationIds.push(...data.map((installation) => installation.id));+ if (data.length < 100) break;+ page += 1;+ }++ const results = await Promise.allSettled(+ installationIds.map((installationId) =>+ safeRequest.delete(`https://${apiBaseUrl}/app/installations/${installationId}`, { headers })+ )+ );++ results.forEach((result, idx) => {+ if (result.status === "rejected") {+ // 404 means the installation is already gone — that's the desired end state.+ const reason = result.reason as AxiosError;+ if (reason?.response?.status !== 404) {+ logger.warn(+ { err: reason, installationId: installationIds[idx], gitHubAppId },+ `Failed to uninstall GitHub App installation [installationId=${installationIds[idx]}] [gitHubAppId=${gitHubAppId}]`+ );+ }+ }+ });+ };+const deleteGitHubApp = async ({ id, orgPermission }: TDeleteGitHubAppDTO): Promise<TSanitizedGitHubApp> => {const { permission } = await permissionService.getOrgPermission({actor: orgPermission.type,@@ -108,7 +178,20 @@ export const gitHubAppServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Settings);- return gitHubAppDAL.transaction(async (tx) => {+ // Resolve credentials up front — once the row is deleted the private key is gone and we can no+ // longer sign the app JWT needed to uninstall the app's installations on GitHub.+ let credentials: Awaited<ReturnType<typeof resolveGitHubAppCredentials>> | null = null;+ try {+ credentials = await resolveGitHubAppCredentials(+ { gitHubAppId: id, orgId: orgPermission.orgId },+ { gitHubAppDAL, kmsService }+ );+ } catch {+ // App missing or credentials unreadable — the transaction below still performs (or rejects)+ // the local deletion; only the GitHub-side uninstall is skipped.+ }++ const sanitized = await gitHubAppDAL.transaction(async (tx) => {const existing = await gitHubAppDAL.findByIdWithLock(id, orgPermission.orgId, tx);if (!existing) {throw new NotFoundError({ message: `GitHub App with id ${id} not found in this organization.` });@@ -125,7 +208,7 @@ export const gitHubAppServiceFactory = ({});}- const sanitized: TSanitizedGitHubApp = {+ const result: TSanitizedGitHubApp = {id: existing.id,orgId: existing.orgId,name: existing.name,@@ -139,8 +222,18 @@ export const gitHubAppServiceFactory = ({await gitHubAppDAL.deleteById(existing.id, tx);- return sanitized;+ return result;});++ if (credentials) {+ try {+ await uninstallAllGitHubAppInstallations(credentials, id);+ } catch (err) {+ logger.warn(err, `Failed to uninstall GitHub App installations [gitHubAppId=${id}]`);+ }+ }++ return sanitized;};const initiateManifestCreation = async ({@@ -336,8 +429,6 @@ export const gitHubAppServiceFactory = ({// 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({@@ -362,11 +453,13 @@ export const gitHubAppServiceFactory = ({{ gitHubAppDAL, kmsService });- // For an org-managed app, the request only identifies which app to use — its host/instance are- // bound to the stored app record. Ignoring the caller-supplied host here 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) : host;- const effectiveInstanceType = gitHubAppId ? (appInstanceType ?? "cloud") : instanceType;+ // 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";assertPlatformGitHubHostAllowed(effectiveHost);diff --git a/backend/src/services/github-app/github-app-types.ts b/backend/src/services/github-app/github-app-types.tsindex 27fd2994e4..45a85041a4 100644--- a/backend/src/services/github-app/github-app-types.ts+++ b/backend/src/services/github-app/github-app-types.ts@@ -32,8 +32,6 @@ export type TDeleteGitHubAppDTO = {export type TGetGitHubAppInstallationStatusDTO = {gitHubAppId?: string;- host?: string;- instanceType?: "cloud" | "server";orgPermission: OrgServiceActor;};diff --git a/frontend/src/hooks/api/gitHubApps/queries.tsx b/frontend/src/hooks/api/gitHubApps/queries.tsxindex 1c53eee36e..69d2ae798f 100644--- a/frontend/src/hooks/api/gitHubApps/queries.tsx+++ b/frontend/src/hooks/api/gitHubApps/queries.tsx@@ -16,11 +16,7 @@ const fetchGitHubApps = async () => {// 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";-}) => {+export const fetchGitHubAppInstallationStatus = async (params: { gitHubAppId?: string }) => {const { data } = await apiRequest.get<{ installed: boolean; clientId: string }>("/api/v1/github-apps/installation-status",{ params }diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsxindex 097157cf34..306e4fa866 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx@@ -135,7 +135,8 @@ export const GitHubAppSelector = ({</span></div><p className="mt-1 text-xs leading-relaxed text-mineshaft-300">- Removes it from Infisical. The app still exists on GitHub until you uninstall it there.+ Removes it from Infisical and uninstalls it from GitHub. The app registration itself+ remains on GitHub until you delete it there.</p><div className="mt-3 flex items-center justify-end gap-2"><Buttondiff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsxindex dd204a6b4c..71dee468ba 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx@@ -328,9 +328,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Proif (targetApp?.id || !isInfisicalCloud()) {try {const { installed, clientId } = await fetchGitHubAppInstallationStatus({- gitHubAppId: targetApp?.id ?? undefined,- host: formData.credentials?.host || undefined,- instanceType: formData.credentials?.instanceType ?? "cloud"+ gitHubAppId: targetApp?.id ?? undefined});if (installed) {