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
create mid table
Thiago Araujo da Silva11d57335391c
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex ed9f5c7187..1503624f66 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -182,6 +182,9 @@ import {TGitAppOrg,TGitAppOrgInsert,TGitAppOrgUpdate,+ TGithubAppConnections,+ TGithubAppConnectionsInsert,+ TGithubAppConnectionsUpdate,TGithubApps,TGithubAppsInsert,TGithubAppsUpdate,@@ -1565,6 +1568,11 @@ declare module "knex/types/tables" {TSecretReminderRecipientsUpdate>;[TableName.GitHubApp]: KnexOriginal.CompositeTableType<TGithubApps, TGithubAppsInsert, TGithubAppsUpdate>;+ [TableName.GitHubAppConnection]: KnexOriginal.CompositeTableType<+ TGithubAppConnections,+ TGithubAppConnectionsInsert,+ TGithubAppConnectionsUpdate+ >;[TableName.GithubOrgSyncConfig]: KnexOriginal.CompositeTableType<TGithubOrgSyncConfigs,TGithubOrgSyncConfigsInsert,diff --git a/backend/src/db/migrations/20260604120000_create-github-app-connections.ts b/backend/src/db/migrations/20260604120000_create-github-app-connections.tsnew file mode 100644index 0000000000..a9d98d41df--- /dev/null+++ b/backend/src/db/migrations/20260604120000_create-github-app-connections.ts@@ -0,0 +1,25 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "@app/db/utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.GitHubAppConnection))) {+ await knex.schema.createTable(TableName.GitHubAppConnection, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("appConnectionId").notNullable().unique();+ t.foreign("appConnectionId").references("id").inTable(TableName.AppConnection).onDelete("CASCADE");+ t.uuid("githubAppId").notNullable();+ t.foreign("githubAppId").references("id").inTable(TableName.GitHubApp);+ t.index("githubAppId");+ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.GitHubAppConnection);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.schema.dropTableIfExists(TableName.GitHubAppConnection);+ await dropOnUpdateTrigger(knex, TableName.GitHubAppConnection);+}diff --git a/backend/src/db/schemas/github-app-connections.ts b/backend/src/db/schemas/github-app-connections.tsnew file mode 100644index 0000000000..a5182f2fd4--- /dev/null+++ b/backend/src/db/schemas/github-app-connections.ts@@ -0,0 +1,20 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const GithubAppConnectionsSchema = z.object({+ id: z.string().uuid(),+ appConnectionId: z.string().uuid(),+ githubAppId: z.string().uuid(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TGithubAppConnections = z.infer<typeof GithubAppConnectionsSchema>;+export type TGithubAppConnectionsInsert = Omit<z.input<typeof GithubAppConnectionsSchema>, TImmutableDBKeys>;+export type TGithubAppConnectionsUpdate = Partial<Omit<z.input<typeof GithubAppConnectionsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 3e372ba919..d43d2a6454 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -60,6 +60,7 @@ export * from "./gateways";export * from "./gateways-v2";export * from "./git-app-install-sessions";export * from "./git-app-org";+export * from "./github-app-connections";export * from "./github-apps";export * from "./github-org-sync-configs";export * from "./group-project-membership-roles";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 2db0b1f6a5..fe1f074ab6 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -193,6 +193,7 @@ export enum TableName {SecretReminderRecipients = "secret_reminder_recipients", // TODO(Carlos): Remove this in the future after migrating to the new reminder recipients tableGithubOrgSyncConfig = "github_org_sync_configs",GitHubApp = "github_apps",+ GitHubAppConnection = "github_app_connections",FolderCommit = "folder_commits",FolderCommitChanges = "folder_commit_changes",FolderCheckpoint = "folder_checkpoints",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 293f3620ed..206503e4c6 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1032,7 +1032,6 @@ export const registerRoutes = async (const gitHubAppService = gitHubAppServiceFactory({gitHubAppDAL,- appConnectionDAL,permissionService,kmsService,keyStorediff --git a/backend/src/services/app-connection/app-connection-dal.ts b/backend/src/services/app-connection/app-connection-dal.tsindex 275fa1ffb8..0135ad7fa0 100644--- a/backend/src/services/app-connection/app-connection-dal.ts+++ b/backend/src/services/app-connection/app-connection-dal.ts@@ -203,23 +203,6 @@ export const appConnectionDALFactory = (db: TDbClient) => {return parseInt(String(result?.count || "0"), 10);};- // Returns the org's GitHub App method connections. Which GitHub App each connection references- // lives inside the encrypted credentials, so callers decrypt to group/count per app.- const findGitHubAppMethodConnections = async (orgId: string, tx?: Knex) => {- const rows = await (tx || db.replicaNode())(TableName.AppConnection)- .where(`${TableName.AppConnection}.orgId`, orgId)- .andWhere(`${TableName.AppConnection}.app`, "github")- .andWhere(`${TableName.AppConnection}.method`, "github-app")- .select(- db.ref("id").withSchema(TableName.AppConnection),- db.ref("orgId").withSchema(TableName.AppConnection),- db.ref("projectId").withSchema(TableName.AppConnection),- db.ref("encryptedCredentials").withSchema(TableName.AppConnection)- );-- return rows;- };-return {...appConnectionOrm,findAppConnectionUsageById,@@ -227,7 +210,6 @@ export const appConnectionDALFactory = (db: TDbClient) => {findByGatewayId,countByGatewayId,findByGatewayPoolId,- countByGatewayPoolId,- findGitHubAppMethodConnections+ countByGatewayPoolId};};diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex f518504686..120af6b268 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -186,7 +186,7 @@ export type TAppConnectionServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findProjectById">;appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;- gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne">;+ gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "upsertConnectionLink">;};export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;@@ -589,6 +589,19 @@ export const appConnectionServiceFactory = ({);}+ // Which GitHub App the connection references is mirrored from the encrypted credentials+ // into github_app_connections so usage can be counted (and deletes blocked) without+ // decrypting, and so the FK rejects creates racing an app deletion.+ if (app === AppConnection.GitHub && method === GitHubConnectionMethod.App) {+ await gitHubAppDAL.upsertConnectionLink(+ {+ appConnectionId: appConnection.id,+ githubAppId: (connectionCredentials as { gitHubAppId?: string | null }).gitHubAppId ?? null+ },+ tx+ );+ }+return appConnection;});};@@ -623,6 +636,14 @@ export const appConnectionServiceFactory = ({throw new BadRequestError({ message: `An App Connection with the name "${params.name}" already exists` });}+ if (+ err instanceof DatabaseError &&+ (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation+ ) {+ // the github_app_connections link FK — the referenced GitHub App was deleted concurrently+ throw new BadRequestError({ message: "The selected GitHub App no longer exists. Please try again." });+ }+throw err;}};@@ -872,6 +893,18 @@ export const appConnectionServiceFactory = ({connection = await updateConnection(updatedCredentials, tx);}+ // Keep the github_app_connections link in sync with the (re-validated) credentials — see+ // the matching block in createAppConnection.+ if (updatedCredentials && app === AppConnection.GitHub && method === GitHubConnectionMethod.App) {+ await gitHubAppDAL.upsertConnectionLink(+ {+ appConnectionId: connectionId,+ githubAppId: (updatedCredentials as { gitHubAppId?: string | null }).gitHubAppId ?? null+ },+ tx+ );+ }+// Handle rotation updatesif (isAutoRotationEnabled !== undefined || rotation) {if (isAutoRotationEnabled === false) {@@ -938,6 +971,14 @@ export const appConnectionServiceFactory = ({throw new BadRequestError({ message: `An App Connection with the name "${params.name}" already exists` });}+ if (+ err instanceof DatabaseError &&+ (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation+ ) {+ // the github_app_connections link FK — the referenced GitHub App was deleted concurrently+ throw new BadRequestError({ message: "The selected GitHub App no longer exists. Please try again." });+ }+throw err;}};diff --git a/backend/src/services/github-app/github-app-dal.ts b/backend/src/services/github-app/github-app-dal.tsindex f49c94c02a..280473f44b 100644--- a/backend/src/services/github-app/github-app-dal.ts+++ b/backend/src/services/github-app/github-app-dal.ts@@ -14,8 +14,63 @@ export const gitHubAppDALFactory = (db: TDbClient) => {return app;};+ // Keeps the github_app_connections link row in sync with the connection's credentials. A null+ // githubAppId means the connection uses the instance-default (shared) app — no link row.+ const upsertConnectionLink = async (+ { appConnectionId, githubAppId }: { appConnectionId: string; githubAppId: string | null },+ tx: Knex+ ) => {+ if (!githubAppId) {+ await tx(TableName.GitHubAppConnection).where({ appConnectionId }).delete();+ return;+ }++ await tx(TableName.GitHubAppConnection)+ .insert({ appConnectionId, githubAppId })+ .onConflict("appConnectionId")+ .merge();+ };++ // Returns connection counts per GitHub App for the org, keyed by app id. The null key counts+ // GitHub App method connections with no link row, i.e. those using the instance-default app.+ const countConnectionsPerApp = async (orgId: string, tx?: Knex) => {+ const linkedRows = (await (tx || db.replicaNode())(TableName.GitHubAppConnection)+ .join(+ TableName.AppConnection,+ `${TableName.GitHubAppConnection}.appConnectionId`,+ `${TableName.AppConnection}.id`+ )+ .where(`${TableName.AppConnection}.orgId`, orgId)+ .groupBy(`${TableName.GitHubAppConnection}.githubAppId`)+ .select(`${TableName.GitHubAppConnection}.githubAppId`)+ .count(`${TableName.GitHubAppConnection}.id`)) as { githubAppId: string; count: string | number }[];++ const sharedRow = await (tx || db.replicaNode())(TableName.AppConnection)+ .where(`${TableName.AppConnection}.orgId`, orgId)+ .andWhere(`${TableName.AppConnection}.app`, "github")+ .andWhere(`${TableName.AppConnection}.method`, "github-app")+ .whereNotExists((qb) => {+ void qb+ .select("id")+ .from(TableName.GitHubAppConnection)+ .whereRaw(`"${TableName.GitHubAppConnection}"."appConnectionId" = "${TableName.AppConnection}"."id"`);+ })+ .count("id")+ .first();++ const counts = new Map<string | null, number>();+ linkedRows.forEach((row) => {+ counts.set(row.githubAppId, parseInt(String(row.count || "0"), 10));+ });+ counts.set(null, parseInt(String(sharedRow?.count || "0"), 10));++ return counts;+ };+return {...orm,- findByIdWithLock+ findByIdWithLock,+ upsertConnectionLink,+ countConnectionsPerApp};};diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.tsindex ca1f778544..ce55d6d25c 100644--- a/backend/src/services/github-app/github-app-service.ts+++ b/backend/src/services/github-app/github-app-service.ts@@ -1,7 +1,6 @@import { ForbiddenError } from "@casl/ability";import { AxiosError } from "axios";import jwt from "jsonwebtoken";-import { Knex } from "knex";import { OrganizationActionScope } from "@app/db/schemas";import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";@@ -13,8 +12,6 @@ import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { safeRequest } from "@app/lib/validator/safe-request";-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";-import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import {assertPlatformGitHubHostAllowed,buildGitHubAppJwtHeaders,@@ -39,7 +36,6 @@ import {type TGitHubAppServiceFactoryDep = {gitHubAppDAL: TGitHubAppDALFactory;- appConnectionDAL: Pick<TAppConnectionDALFactory, "findGitHubAppMethodConnections">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem">;@@ -49,32 +45,10 @@ export type TGitHubAppServiceFactory = ReturnType<typeof gitHubAppServiceFactoryexport const gitHubAppServiceFactory = ({gitHubAppDAL,- appConnectionDAL,permissionService,kmsService,keyStore}: TGitHubAppServiceFactoryDep) => {- const countConnectionsByGitHubApp = async (orgId: string, tx?: Knex) => {- const connections = await appConnectionDAL.findGitHubAppMethodConnections(orgId, tx);-- const counts = new Map<string | null, number>();- await Promise.all(- connections.map(async (connection) => {- const credentials = await decryptAppConnectionCredentials({- orgId: connection.orgId,- projectId: connection.projectId,- encryptedCredentials: connection.encryptedCredentials,- kmsService- });-- const gitHubAppId = (credentials as { gitHubAppId?: string | null }).gitHubAppId ?? null;- counts.set(gitHubAppId, (counts.get(gitHubAppId) ?? 0) + 1);- })- );-- return counts;- };-const listGitHubApps = async ({ orgPermission }: TListGitHubAppsDTO): Promise<TSanitizedGitHubApp[]> => {const { permission } = await permissionService.getOrgPermission({actor: orgPermission.type,@@ -89,7 +63,7 @@ export const gitHubAppServiceFactory = ({const apps = await gitHubAppDAL.find({ orgId: orgPermission.orgId });- const countByAppId = await countConnectionsByGitHubApp(orgPermission.orgId);+ const countByAppId = await gitHubAppDAL.countConnectionsPerApp(orgPermission.orgId);const dbApps: TSanitizedGitHubApp[] = apps.map((app) => ({id: app.id,@@ -211,7 +185,7 @@ export const gitHubAppServiceFactory = ({throw new NotFoundError({ message: `GitHub App with id ${id} not found in this organization.` });}- const connectionCounts = await countConnectionsByGitHubApp(orgPermission.orgId, tx);+ const connectionCounts = await gitHubAppDAL.countConnectionsPerApp(orgPermission.orgId, tx);const connectionCount = connectionCounts.get(existing.id) ?? 0;if (connectionCount > 0) {@@ -234,7 +208,19 @@ export const gitHubAppServiceFactory = ({updatedAt: existing.updatedAt};- await gitHubAppDAL.deleteById(existing.id, tx);+ try {+ await gitHubAppDAL.deleteById(existing.id, tx);+ } catch (err) {+ if (+ err instanceof DatabaseError &&+ (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation+ ) {+ throw new BadRequestError({+ message: `Cannot delete GitHub App "${existing.name}" while it is in use by a connection. Remove those connections first.`+ });+ }+ throw err;+ }return result;});