Skip to content

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

71.6 KB
Raw Blame
import { ForbiddenError, subject } from "@casl/ability";
import { Knex } from "knex";

import { ActionProjectType, OrganizationActionScope, ProjectType, TAppConnections } from "@app/db/schemas";
import { ValidateChefConnectionCredentialsSchema } from "@app/ee/services/app-connections/chef";
import { chefConnectionService } from "@app/ee/services/app-connections/chef/chef-connection-service";
import { ValidateOCIConnectionCredentialsSchema } from "@app/ee/services/app-connections/oci";
import { ociConnectionService } from "@app/ee/services/app-connections/oci/oci-connection-service";
import { ValidateOracleDBConnectionCredentialsSchema } from "@app/ee/services/app-connections/oracledb";
import { assertIndividualGatewayAllowed } from "@app/ee/services/gateway-pool/gateway-pool-policy-fns";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
  OrgPermissionAppConnectionActions,
  OrgPermissionGatewayActions,
  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 { 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";
import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { DiscriminativePick, OrgServiceActor } from "@app/lib/types";
import {
  addAppConnectionFederatedCredential,
  decryptAppConnection,
  decryptAppConnectionCredentials,
  encryptAppConnectionConfiguration,
  encryptAppConnectionCredentials,
  enterpriseAppCheck,
  getAppConnectionMethodName,
  isAppConnectionAllowedInProject,
  listAppConnectionOptions,
  PROJECT_TYPES_ENFORCING_APP_CONNECTION_TYPES,
  TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM,
  validateAppConnectionCredentials
} from "@app/services/app-connection/app-connection-fns";
import { TGitHubAppDALFactory } from "@app/services/github-app/github-app-dal";
import { TIdentityUaDALFactory } from "@app/services/identity-ua/identity-ua-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TOidcIssuerServiceFactory } from "@app/services/oidc-issuer/oidc-issuer-service";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";

import { ValidateOnePassConnectionCredentialsSchema } from "./1password";
import { onePassConnectionService } from "./1password/1password-connection-service";
import { ValidateADCSConnectionCredentialsSchema } from "./adcs/adcs-connection-schemas";
import { adcsConnectionService } from "./adcs/adcs-connection-service";
import { ValidateAnthropicConnectionCredentialsSchema } from "./anthropic";
import { TAppConnectionDALFactory } from "./app-connection-dal";
import { AppConnection } from "./app-connection-enums";
import { APP_CONNECTION_NAME_MAP } from "./app-connection-maps";
import {
  TAppConnection,
  TAppConnectionConfig,
  TAppConnectionRaw,
  TAppConnectionScope,
  TCreateAppConnectionDTO,
  TGetAppConnectionByNameDTO,
  TUpdateAppConnectionDTO,
  TValidateAppConnectionCredentialsSchema,
  TValidateAppConnectionUsageByIdDTO
} from "./app-connection-types";
import { ValidateAuth0ConnectionCredentialsSchema } from "./auth0";
import { auth0ConnectionService } from "./auth0/auth0-connection-service";
import { ValidateAwsConnectionCredentialsSchema } from "./aws";
import { awsConnectionService } from "./aws/aws-connection-service";
import { ValidateAzureADCSConnectionCredentialsSchema } from "./azure-adcs/azure-adcs-connection-schemas";
import { azureAdcsConnectionService } from "./azure-adcs/azure-adcs-connection-service";
import { ValidateAzureAppConfigurationConnectionCredentialsSchema } from "./azure-app-configuration";
import { ValidateAzureClientSecretsConnectionCredentialsSchema } from "./azure-client-secrets";
import { azureClientSecretsConnectionService } from "./azure-client-secrets/azure-client-secrets-service";
import { ValidateAzureDevOpsConnectionCredentialsSchema } from "./azure-devops/azure-devops-schemas";
import { azureDevOpsConnectionService } from "./azure-devops/azure-devops-service";
import { ValidateAzureDnsConnectionCredentialsSchema } from "./azure-dns/azure-dns-connection-schema";
import { azureDnsConnectionService } from "./azure-dns/azure-dns-connection-service";
import { ValidateAzureEntraIdConnectionCredentialsSchema } from "./azure-entra-id";
import { azureEntraIdConnectionService } from "./azure-entra-id/azure-entra-id-connection-service";
import { ValidateAzureKeyVaultConnectionCredentialsSchema } from "./azure-key-vault";
import { ValidateBitbucketConnectionCredentialsSchema } from "./bitbucket";
import { bitbucketConnectionService } from "./bitbucket/bitbucket-connection-service";
import { ValidateCamundaConnectionCredentialsSchema } from "./camunda";
import { camundaConnectionService } from "./camunda/camunda-connection-service";
import { ValidateChecklyConnectionCredentialsSchema } from "./checkly";
import { checklyConnectionService } from "./checkly/checkly-connection-service";
import { ValidateCircleCIConnectionCredentialsSchema } from "./circleci";
import { circleciConnectionService } from "./circleci/circleci-connection-service";
import { ValidateCloud66ConnectionCredentialsSchema } from "./cloud-66";
import { cloud66ConnectionService } from "./cloud-66/cloud-66-connection-service";
import { ValidateCloudflareConnectionCredentialsSchema } from "./cloudflare/cloudflare-connection-schema";
import { cloudflareConnectionService } from "./cloudflare/cloudflare-connection-service";
import { ValidateConvexConnectionCredentialsSchema } from "./convex";
import { TAppConnectionCredentialRotationServiceFactory } from "./credential-rotation";
import { ValidateDatabricksConnectionCredentialsSchema } from "./databricks";
import { databricksConnectionService } from "./databricks/databricks-connection-service";
import { ValidateDatadogConnectionCredentialsSchema } from "./datadog";
import { datadogConnectionService } from "./datadog/datadog-connection-service";
import { ValidateDaytonaConnectionCredentialsSchema } from "./daytona";
import { ValidateDbtConnectionCredentialsSchema } from "./dbt";
import { dbtConnectionService } from "./dbt/dbt-connection-service";
import { ValidateDevinConnectionCredentialsSchema } from "./devin";
import { ValidateDigiCertConnectionCredentialsSchema } from "./digicert/digicert-connection-schemas";
import { digicertConnectionService } from "./digicert/digicert-connection-service";
import { ValidateDigitalOceanConnectionCredentialsSchema } from "./digital-ocean";
import { digitalOceanAppPlatformConnectionService } from "./digital-ocean/digital-ocean-connection-service";
import { ValidateDNSMadeEasyConnectionCredentialsSchema } from "./dns-made-easy/dns-made-easy-connection-schema";
import { dnsMadeEasyConnectionService } from "./dns-made-easy/dns-made-easy-connection-service";
import { ValidateDopplerConnectionCredentialsSchema } from "./doppler/doppler-connection-schema";
import { dopplerConnectionService } from "./doppler/doppler-connection-service";
import { ValidateExternalInfisicalConnectionCredentialsSchema } from "./external-infisical";
import { externalInfisicalConnectionService } from "./external-infisical/external-infisical-connection-service";
import { ValidateF5BigIpConnectionCredentialsSchema } from "./f5-big-ip";
import { ValidateFireworksConnectionCredentialsSchema } from "./fireworks";
import { fireworksConnectionService } from "./fireworks/fireworks-connection-service";
import { ValidateFlyioConnectionCredentialsSchema } from "./flyio";
import { flyioConnectionService } from "./flyio/flyio-connection-service";
import { ValidateGcpConnectionCredentialsSchema } from "./gcp";
import { gcpConnectionService } from "./gcp/gcp-connection-service";
import { GitHubConnectionMethod, ValidateGitHubConnectionCredentialsSchema } from "./github";
import { ValidateGitHubRadarConnectionCredentialsSchema } from "./github-radar";
import { githubRadarConnectionService } from "./github-radar/github-radar-connection-service";
import { githubConnectionService } from "./github/github-connection-service";
import { ValidateGitLabConnectionCredentialsSchema } from "./gitlab";
import { gitlabConnectionService } from "./gitlab/gitlab-connection-service";
import { ValidateGoDaddyConnectionCredentialsSchema } from "./godaddy/godaddy-connection-schemas";
import { ValidateHasuraCloudConnectionCredentialsSchema } from "./hasura-cloud";
import { hasuraCloudConnectionService } from "./hasura-cloud/hasura-cloud-connection-service";
import { ValidateHCVaultConnectionCredentialsSchema } from "./hc-vault";
import { hcVaultConnectionService } from "./hc-vault/hc-vault-connection-service";
import { ValidateHerokuConnectionCredentialsSchema } from "./heroku";
import { herokuConnectionService } from "./heroku/heroku-connection-service";
import { ValidateHpeIloConnectionCredentialsSchema } from "./hpe-ilo";
import { ValidateHumanitecConnectionCredentialsSchema } from "./humanitec";
import { humanitecConnectionService } from "./humanitec/humanitec-connection-service";
import { ValidateImpervaConnectionCredentialsSchema } from "./imperva";
import { impervaConnectionService } from "./imperva/imperva-connection-service";
import { ValidateJiraConnectionCredentialsSchema } from "./jira";
import { ValidateKeeperConnectionCredentialsSchema } from "./keeper";
import { keeperConnectionService } from "./keeper/keeper-connection-service";
import { ValidateKempLoadMasterConnectionCredentialsSchema } from "./kemp-loadmaster";
import { kempLoadMasterConnectionService } from "./kemp-loadmaster/kemp-loadmaster-connection-service";
import { ValidateLaravelForgeConnectionCredentialsSchema } from "./laravel-forge";
import { laravelForgeConnectionService } from "./laravel-forge/laravel-forge-connection-service";
import { ValidateLdapConnectionCredentialsSchema } from "./ldap";
import { ldapConnectionService } from "./ldap/ldap-connection-service";
import { ValidateLiteLLMConnectionCredentialsSchema } from "./litellm";
import { liteLLMConnectionService } from "./litellm/litellm-connection-service";
import { ValidateMicrosoftIntuneConnectionCredentialsSchema } from "./microsoft-intune";
import { ValidateMongoDBConnectionCredentialsSchema } from "./mongodb";
import { ValidateMsSqlConnectionCredentialsSchema } from "./mssql";
import { ValidateMySqlConnectionCredentialsSchema } from "./mysql";
import { ValidateNetlifyConnectionCredentialsSchema } from "./netlify";
import { netlifyConnectionService } from "./netlify/netlify-connection-service";
import { ValidateNetScalerConnectionCredentialsSchema } from "./netscaler";
import { ValidateNorthflankConnectionCredentialsSchema } from "./northflank";
import { northflankConnectionService } from "./northflank/northflank-connection-service";
import {
  nutanixPrismCentralConnectionService,
  ValidateNutanixPrismCentralConnectionCredentialsSchema
} from "./nutanix-prism-central";
import { ValidateOctopusDeployConnectionCredentialsSchema } from "./octopus-deploy";
import { octopusDeployConnectionService } from "./octopus-deploy/octopus-deploy-connection-service";
import { ValidateOktaConnectionCredentialsSchema } from "./okta";
import { oktaConnectionService } from "./okta/okta-connection-service";
import { ValidateOnaConnectionCredentialsSchema } from "./ona";
import { onaConnectionService } from "./ona/ona-connection-service";
import { ValidateOpenRouterConnectionCredentialsSchema } from "./open-router";
import { openRouterConnectionService } from "./open-router/open-router-connection-service";
import { ValidateOpenAIConnectionCredentialsSchema } from "./openai";
import { openaiConnectionService } from "./openai/openai-connection-service";
import { ValidateOvhConnectionCredentialsSchema } from "./ovh";
import {
  paloAltoNetworksConnectionService,
  ValidatePaloAltoNetworksConnectionCredentialsSchema
} from "./palo-alto-networks";
import { ValidatePortainerConnectionCredentialsSchema } from "./portainer";
import { portainerConnectionService } from "./portainer/portainer-connection-service";
import { ValidatePostgresConnectionCredentialsSchema } from "./postgres";
import { powerDnsConnectionService, ValidatePowerDnsConnectionCredentialsSchema } from "./powerdns";
import { ValidateQoveryConnectionCredentialsSchema } from "./qovery";
import { qoveryConnectionService } from "./qovery/qovery-connection-service";
import { ValidateRailwayConnectionCredentialsSchema } from "./railway";
import { railwayConnectionService } from "./railway/railway-connection-service";
import { ValidateRedisConnectionCredentialsSchema } from "./redis";
import { ValidateRenderConnectionCredentialsSchema } from "./render/render-connection-schema";
import { renderConnectionService } from "./render/render-connection-service";
import { ValidateRundeckConnectionCredentialsSchema } from "./rundeck";
import { rundeckConnectionService } from "./rundeck/rundeck-connection-service";
import { ValidateS3CompatibleConnectionCredentialsSchema } from "./s3-compatible";
import { ValidateSalesforceConnectionCredentialsSchema } from "./salesforce";
import { salesforceConnectionService } from "./salesforce/salesforce-connection-service";
import { ValidateServiceNowConnectionCredentialsSchema } from "./servicenow";
import { ValidateSmbConnectionCredentialsSchema } from "./smb";
import { ValidateSnowflakeConnectionCredentialsSchema } from "./snowflake";
import { snowflakeConnectionService } from "./snowflake/snowflake-connection-service";
import { ValidateSpaceliftConnectionCredentialsSchema } from "./spacelift";
import { spaceliftConnectionService } from "./spacelift/spacelift-connection-service";
import { ValidateSshConnectionCredentialsSchema } from "./ssh";
import { ValidateStripeConnectionCredentialsSchema } from "./stripe";
import { ValidateSupabaseConnectionCredentialsSchema } from "./supabase";
import { supabaseConnectionService } from "./supabase/supabase-connection-service";
import { ValidateTeamCityConnectionCredentialsSchema } from "./teamcity";
import { teamcityConnectionService } from "./teamcity/teamcity-connection-service";
import { ValidateTerraformCloudConnectionCredentialsSchema } from "./terraform-cloud";
import { terraformCloudConnectionService } from "./terraform-cloud/terraform-cloud-connection-service";
import { ValidateTravisCIConnectionCredentialsSchema } from "./travis-ci";
import { travisCIConnectionService } from "./travis-ci/travis-ci-connection-service";
import { ValidateTriggerDevConnectionCredentialsSchema } from "./trigger-dev";
import { triggerDevConnectionService } from "./trigger-dev/trigger-dev-connection-service";
import { ValidateUltraDNSConnectionCredentialsSchema } from "./ultradns/ultradns-connection-schema";
import { ultraDNSConnectionService } from "./ultradns/ultradns-connection-service";
import { ValidateVenafiTppConnectionCredentialsSchema } from "./venafi-tpp/venafi-tpp-connection-schemas";
import { ValidateVenafiConnectionCredentialsSchema } from "./venafi/venafi-connection-schema";
import { venafiConnectionService } from "./venafi/venafi-connection-service";
import { ValidateVercelConnectionCredentialsSchema } from "./vercel";
import { vercelConnectionService } from "./vercel/vercel-connection-service";
import { ValidateWindmillConnectionCredentialsSchema } from "./windmill";
import { windmillConnectionService } from "./windmill/windmill-connection-service";
import { ValidateWinRMConnectionCredentialsSchema } from "./winrm/winrm-connection-schemas";
import { ValidateZabbixConnectionCredentialsSchema } from "./zabbix";
import { zabbixConnectionService } from "./zabbix/zabbix-connection-service";

export type TAppConnectionServiceFactoryDep = {
  appConnectionDAL: TAppConnectionDALFactory;
  permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
  gatewayPoolService: Pick<
    TGatewayPoolServiceFactory,
    "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId" | "runWithPoolFailover"
  >;
  gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
  orgDAL: Pick<TOrgDALFactory, "findById">;
  projectDAL: Pick<TProjectDALFactory, "findProjectById">;
  appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;
  identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;
  gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "upsertConnectionLink">;
  keyStore: Pick<
    TKeyStoreFactory,
    "setItemWithExpiryNX" | "deleteItem" | "getItem" | "setItemWithExpiry" | "acquireLock"
  >;
  oidcIssuerService: Pick<TOidcIssuerServiceFactory, "signToken">;
};

export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;

const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAppConnectionCredentialsSchema> = {
  [AppConnection.AWS]: ValidateAwsConnectionCredentialsSchema,
  [AppConnection.GitHub]: ValidateGitHubConnectionCredentialsSchema,
  [AppConnection.GitHubRadar]: ValidateGitHubRadarConnectionCredentialsSchema,
  [AppConnection.GCP]: ValidateGcpConnectionCredentialsSchema,
  [AppConnection.AzureKeyVault]: ValidateAzureKeyVaultConnectionCredentialsSchema,
  [AppConnection.AzureAppConfiguration]: ValidateAzureAppConfigurationConnectionCredentialsSchema,
  [AppConnection.AzureDevOps]: ValidateAzureDevOpsConnectionCredentialsSchema,
  [AppConnection.AzureADCS]: ValidateAzureADCSConnectionCredentialsSchema,
  [AppConnection.ADCS]: ValidateADCSConnectionCredentialsSchema,
  [AppConnection.WinRM]: ValidateWinRMConnectionCredentialsSchema,
  [AppConnection.Databricks]: ValidateDatabricksConnectionCredentialsSchema,
  [AppConnection.Humanitec]: ValidateHumanitecConnectionCredentialsSchema,
  [AppConnection.TerraformCloud]: ValidateTerraformCloudConnectionCredentialsSchema,
  [AppConnection.Vercel]: ValidateVercelConnectionCredentialsSchema,
  [AppConnection.Postgres]: ValidatePostgresConnectionCredentialsSchema,
  [AppConnection.MsSql]: ValidateMsSqlConnectionCredentialsSchema,
  [AppConnection.MySql]: ValidateMySqlConnectionCredentialsSchema,
  [AppConnection.Camunda]: ValidateCamundaConnectionCredentialsSchema,
  [AppConnection.AzureClientSecrets]: ValidateAzureClientSecretsConnectionCredentialsSchema,
  [AppConnection.Windmill]: ValidateWindmillConnectionCredentialsSchema,
  [AppConnection.Auth0]: ValidateAuth0ConnectionCredentialsSchema,
  [AppConnection.HCVault]: ValidateHCVaultConnectionCredentialsSchema,
  [AppConnection.LDAP]: ValidateLdapConnectionCredentialsSchema,
  [AppConnection.TeamCity]: ValidateTeamCityConnectionCredentialsSchema,
  [AppConnection.OCI]: ValidateOCIConnectionCredentialsSchema,
  [AppConnection.OracleDB]: ValidateOracleDBConnectionCredentialsSchema,
  [AppConnection.OnePass]: ValidateOnePassConnectionCredentialsSchema,
  [AppConnection.Heroku]: ValidateHerokuConnectionCredentialsSchema,
  [AppConnection.HasuraCloud]: ValidateHasuraCloudConnectionCredentialsSchema,
  [AppConnection.Render]: ValidateRenderConnectionCredentialsSchema,
  [AppConnection.LaravelForge]: ValidateLaravelForgeConnectionCredentialsSchema,
  [AppConnection.Flyio]: ValidateFlyioConnectionCredentialsSchema,
  [AppConnection.TriggerDev]: ValidateTriggerDevConnectionCredentialsSchema,
  [AppConnection.GitLab]: ValidateGitLabConnectionCredentialsSchema,
  [AppConnection.Cloudflare]: ValidateCloudflareConnectionCredentialsSchema,
  [AppConnection.DNSMadeEasy]: ValidateDNSMadeEasyConnectionCredentialsSchema,
  [AppConnection.UltraDNS]: ValidateUltraDNSConnectionCredentialsSchema,
  [AppConnection.AzureDNS]: ValidateAzureDnsConnectionCredentialsSchema,
  [AppConnection.Zabbix]: ValidateZabbixConnectionCredentialsSchema,
  [AppConnection.Railway]: ValidateRailwayConnectionCredentialsSchema,
  [AppConnection.Bitbucket]: ValidateBitbucketConnectionCredentialsSchema,
  [AppConnection.Checkly]: ValidateChecklyConnectionCredentialsSchema,
  [AppConnection.Supabase]: ValidateSupabaseConnectionCredentialsSchema,
  [AppConnection.DigitalOcean]: ValidateDigitalOceanConnectionCredentialsSchema,
  [AppConnection.Netlify]: ValidateNetlifyConnectionCredentialsSchema,
  [AppConnection.Northflank]: ValidateNorthflankConnectionCredentialsSchema,
  [AppConnection.Okta]: ValidateOktaConnectionCredentialsSchema,
  [AppConnection.OpenRouter]: ValidateOpenRouterConnectionCredentialsSchema,
  [AppConnection.OpenAI]: ValidateOpenAIConnectionCredentialsSchema,
  [AppConnection.Redis]: ValidateRedisConnectionCredentialsSchema,
  [AppConnection.MongoDB]: ValidateMongoDBConnectionCredentialsSchema,
  [AppConnection.Chef]: ValidateChefConnectionCredentialsSchema,
  [AppConnection.OctopusDeploy]: ValidateOctopusDeployConnectionCredentialsSchema,
  [AppConnection.SSH]: ValidateSshConnectionCredentialsSchema,
  [AppConnection.Dbt]: ValidateDbtConnectionCredentialsSchema,
  [AppConnection.SMB]: ValidateSmbConnectionCredentialsSchema,
  [AppConnection.CircleCI]: ValidateCircleCIConnectionCredentialsSchema,
  [AppConnection.Cloud66]: ValidateCloud66ConnectionCredentialsSchema,
  [AppConnection.AzureEntraId]: ValidateAzureEntraIdConnectionCredentialsSchema,
  [AppConnection.MicrosoftIntune]: ValidateMicrosoftIntuneConnectionCredentialsSchema,
  [AppConnection.Venafi]: ValidateVenafiConnectionCredentialsSchema,
  [AppConnection.VenafiTpp]: ValidateVenafiTppConnectionCredentialsSchema,
  [AppConnection.ExternalInfisical]: ValidateExternalInfisicalConnectionCredentialsSchema,
  [AppConnection.Doppler]: ValidateDopplerConnectionCredentialsSchema,
  [AppConnection.NetScaler]: ValidateNetScalerConnectionCredentialsSchema,
  [AppConnection.PaloAltoNetworks]: ValidatePaloAltoNetworksConnectionCredentialsSchema,
  [AppConnection.KempLoadMaster]: ValidateKempLoadMasterConnectionCredentialsSchema,
  [AppConnection.Imperva]: ValidateImpervaConnectionCredentialsSchema,
  [AppConnection.Anthropic]: ValidateAnthropicConnectionCredentialsSchema,
  [AppConnection.OVH]: ValidateOvhConnectionCredentialsSchema,
  [AppConnection.Devin]: ValidateDevinConnectionCredentialsSchema,
  [AppConnection.Ona]: ValidateOnaConnectionCredentialsSchema,
  [AppConnection.DigiCert]: ValidateDigiCertConnectionCredentialsSchema,
  [AppConnection.GoDaddy]: ValidateGoDaddyConnectionCredentialsSchema,
  [AppConnection.TravisCI]: ValidateTravisCIConnectionCredentialsSchema,
  [AppConnection.Salesforce]: ValidateSalesforceConnectionCredentialsSchema,
  [AppConnection.Snowflake]: ValidateSnowflakeConnectionCredentialsSchema,
  [AppConnection.Datadog]: ValidateDatadogConnectionCredentialsSchema,
  [AppConnection.F5BigIp]: ValidateF5BigIpConnectionCredentialsSchema,
  [AppConnection.Convex]: ValidateConvexConnectionCredentialsSchema,
  [AppConnection.Rundeck]: ValidateRundeckConnectionCredentialsSchema,
  [AppConnection.Portainer]: ValidatePortainerConnectionCredentialsSchema,
  [AppConnection.Qovery]: ValidateQoveryConnectionCredentialsSchema,
  [AppConnection.LiteLLM]: ValidateLiteLLMConnectionCredentialsSchema,
  [AppConnection.Fireworks]: ValidateFireworksConnectionCredentialsSchema,
  [AppConnection.NutanixPrismCentral]: ValidateNutanixPrismCentralConnectionCredentialsSchema,
  [AppConnection.PowerDns]: ValidatePowerDnsConnectionCredentialsSchema,
  [AppConnection.Spacelift]: ValidateSpaceliftConnectionCredentialsSchema,
  [AppConnection.Daytona]: ValidateDaytonaConnectionCredentialsSchema,
  [AppConnection.Stripe]: ValidateStripeConnectionCredentialsSchema,
  [AppConnection.Keeper]: ValidateKeeperConnectionCredentialsSchema,
  [AppConnection.HpeIloRedFish]: ValidateHpeIloConnectionCredentialsSchema,
  [AppConnection.ServiceNow]: ValidateServiceNowConnectionCredentialsSchema,
  [AppConnection.S3Compatible]: ValidateS3CompatibleConnectionCredentialsSchema,
  [AppConnection.Jira]: ValidateJiraConnectionCredentialsSchema
};

export const appConnectionServiceFactory = ({
  appConnectionDAL,
  permissionService,
  kmsService,
  licenseService,
  gatewayV2Service,
  gatewayPoolService,
  gatewayV2DAL,
  orgDAL,
  projectDAL,
  appConnectionCredentialRotationService,
  identityUaDAL,
  gitHubAppDAL,
  keyStore,
  oidcIssuerService
}: TAppConnectionServiceFactoryDep) => {
  const listAppConnections = async (actor: OrgServiceActor, app?: AppConnection, projectId?: string) => {
    let appConnections: TAppConnections[];

    if (projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Read,
        ProjectPermissionSub.AppConnections
      );

      appConnections = (
        await appConnectionDAL.findWithProjectDetails({
          projectId,
          ...(app ? { app } : {})
        })
      ).filter((appConnection) =>
        permission.can(
          ProjectPermissionAppConnectionActions.Read,
          subject(ProjectPermissionSub.AppConnections, { connectionId: appConnection.id })
        )
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        actorId: actor.id,
        actor: actor.type,
        orgId: actor.orgId,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Read,
        OrgPermissionSubjects.AppConnections
      );

      appConnections = (
        await appConnectionDAL.findWithProjectDetails({
          orgId: actor.orgId,
          ...(app ? { app } : {})
        })
      ).filter((appConnection) =>
        permission.can(
          OrgPermissionAppConnectionActions.Read,
          subject(OrgPermissionSubjects.AppConnections, { connectionId: appConnection.id })
        )
      );
    }

    const decryptedAppConnections = await Promise.all(
      appConnections
        .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()))
        .map((appConnection) => decryptAppConnection(appConnection, kmsService))
    );

    return decryptedAppConnections.map(addAppConnectionFederatedCredential);
  };

  const findAppConnectionById = async (
    app: AppConnection,
    connectionId: string,
    actor: OrgServiceActor,
    scope?: TAppConnectionScope
  ) => {
    const appConnection = await appConnectionDAL.findById(connectionId);

    // Checked before any permission or app check, so a connection outside the scope reads exactly like a missing one.
    if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
      throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });

    if (appConnection.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId: appConnection.projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Read,
        subject(ProjectPermissionSub.AppConnections, { connectionId })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        actorId: actor.id,
        actor: actor.type,
        orgId: appConnection.orgId,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Read,
        subject(OrgPermissionSubjects.AppConnections, { connectionId })
      );
    }

    if (appConnection.app !== app)
      throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });

    return addAppConnectionFederatedCredential(await decryptAppConnection(appConnection, kmsService));
  };

  const findAppConnectionByName = async (
    app: AppConnection,
    { connectionName, projectId }: TGetAppConnectionByNameDTO,
    actor: OrgServiceActor
  ) => {
    const appConnection = await appConnectionDAL.findOne({
      name: connectionName,
      ...(projectId ? { projectId } : { orgId: actor.orgId, projectId: null })
    });

    if (!appConnection)
      throw new NotFoundError({
        message: `Could not find App Connection with name ${connectionName} in ${projectId ? "project" : "organization"} scope.`
      });

    if (appConnection.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId: appConnection.projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Read,
        subject(ProjectPermissionSub.AppConnections, { connectionId: appConnection.id })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        actorId: actor.id,
        actor: actor.type,
        orgId: appConnection.orgId,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Read,
        subject(OrgPermissionSubjects.AppConnections, { connectionId: appConnection.id })
      );
    }

    if (appConnection.app !== app)
      throw new BadRequestError({ message: `App Connection with name ${connectionName} is not for App "${app}"` });

    return addAppConnectionFederatedCredential(await decryptAppConnection(appConnection, kmsService));
  };

  // In project scope, an org-managed GitHub App can only be referenced by actors who can also
  // connect org-level app connections — everyone else is limited to the project's own apps and
  // the shared instance app.
  const checkGitHubAppScopeAccess = async (
    gitHubAppId: string,
    orgId: string,
    orgPermission: Awaited<ReturnType<TPermissionServiceFactory["getOrgPermission"]>>["permission"]
  ) => {
    const gitHubApp = await gitHubAppDAL.findOne({ id: gitHubAppId, orgId });
    if (gitHubApp && !gitHubApp.projectId) {
      ForbiddenError.from(orgPermission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Connect,
        OrgPermissionSubjects.AppConnections
      );
    }
  };

  const createAppConnection = async (
    {
      method,
      app,
      credentials,
      configuration,
      gatewayId,
      gatewayPoolId,
      projectId,
      rotation,
      isAutoRotationEnabled,
      ...params
    }: TCreateAppConnectionDTO,
    actor: OrgServiceActor
  ) => {
    if (gatewayId && gatewayPoolId) {
      throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
    }

    const { permission: orgPermission } = await permissionService.getOrgPermission({
      actorId: actor.id,
      actor: actor.type,
      orgId: actor.orgId,
      actorOrgId: actor.orgId,
      actorAuthMethod: actor.authMethod,
      scope: OrganizationActionScope.Any
    });

    const project = projectId ? await projectDAL.findProjectById(projectId) : null;

    if (projectId) {
      if (!project) throw new BadRequestError({ message: `Could not find project with ID ${projectId}` });

      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Create,
        ProjectPermissionSub.AppConnections
      );

      if (
        PROJECT_TYPES_ENFORCING_APP_CONNECTION_TYPES.includes(project.type as ProjectType) &&
        !isAppConnectionAllowedInProject(app, project.type as ProjectType)
      ) {
        const supported = listAppConnectionOptions(project.type as ProjectType).map((option) => option.name);
        throw new BadRequestError({
          message: `${APP_CONNECTION_NAME_MAP[app]} Connections can't be used in this project. It supports: ${supported.join(", ")}.`
        });
      }
    } else {
      ForbiddenError.from(orgPermission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Create,
        OrgPermissionSubjects.AppConnections
      );
    }

    if (gatewayId) {
      const plan = await licenseService.getPlan(actor.orgId);
      if (!plan.gateway) {
        throw new BadRequestError({
          message:
            "Your current plan does not support gateway usage with app connections. Please upgrade your plan or contact Infisical Sales for assistance."
        });
      }

      ForbiddenError.from(orgPermission).throwUnlessCan(
        OrgPermissionGatewayActions.AttachGateways,
        OrgPermissionSubjects.Gateway
      );

      const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: actor.orgId });
      if (!gatewayV2) {
        throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
      }

      await assertIndividualGatewayAllowed({ orgDAL, orgId: actor.orgId, gatewayId });
    }

    if (gatewayPoolId) {
      await gatewayPoolService.resolveAttachableGatewayFromPool({
        poolId: gatewayPoolId,
        orgId: actor.orgId,
        actor
      });
    }

    await enterpriseAppCheck(
      licenseService,
      app,
      actor.orgId,
      "Failed to create app connection due to plan restriction. Upgrade plan to access enterprise app connections."
    );

    if (app === AppConnection.GitHub && method === GitHubConnectionMethod.App && projectId) {
      const { gitHubAppId } = credentials as { gitHubAppId?: string | null };
      if (gitHubAppId) {
        await checkGitHubAppScopeAccess(gitHubAppId, actor.orgId, orgPermission);
      }
    }

    const runValidation = (validationGatewayId: string | null | undefined) =>
      validateAppConnectionCredentials(
        {
          app,
          credentials,
          method,
          orgId: actor.orgId,
          projectId,
          version: 2,
          gatewayId: validationGatewayId,
          projectType: project?.type
        } as TAppConnectionConfig,
        gatewayV2Service,
        { identityUaDAL, gitHubAppDAL, kmsService, keyStore, oidcIssuerService, actorId: actor.id }
      );

    // Validation only dials the target and reads back, so retrying it on another member is safe.
    let validationGatewayId: string | null | undefined = gatewayId;
    let validatedCredentials: Awaited<ReturnType<typeof runValidation>>;
    if (gatewayPoolId) {
      const outcome = await gatewayPoolService.runWithPoolFailover({ poolId: gatewayPoolId }, runValidation);
      validatedCredentials = outcome.result;
      validationGatewayId = outcome.gatewayId;
    } else {
      validatedCredentials = await runValidation(gatewayId);
    }

    try {
      const createConnection = async (connectionCredentials: TAppConnection["credentials"]) => {
        return appConnectionDAL.transaction(async (tx) => {
          const encryptedCredentials = await encryptAppConnectionCredentials({
            credentials: connectionCredentials,
            orgId: actor.orgId,
            kmsService,
            projectId
          });

          const encryptedConfiguration = await encryptAppConnectionConfiguration({
            configuration,
            orgId: actor.orgId,
            kmsService,
            projectId
          });

          const appConnection = await appConnectionDAL.create(
            {
              orgId: actor.orgId,
              encryptedCredentials,
              encryptedConfiguration,
              method,
              app,
              gatewayId: gatewayPoolId ? null : gatewayId,
              gatewayPoolId: gatewayPoolId ?? null,
              projectId,
              isAutoRotationEnabled,
              version: 2, // v1 (legacy) always used orgId as AWS ExternalId; v2 uses scope-based ID
              ...params
            },
            tx
          );

          if (isAutoRotationEnabled && rotation) {
            await appConnectionCredentialRotationService.createRotation(
              {
                connectionId: appConnection.id,
                ...rotation
              },
              tx
            );
          }

          // 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;
        });
      };

      let connection: TAppConnectionRaw;

      if (params.isPlatformManagedCredentials) {
        connection = await TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM[app](
          {
            app,
            orgId: actor.orgId,
            credentials: validatedCredentials,
            method,
            gatewayId: validationGatewayId
          } as TAppConnectionConfig,
          (platformCredentials) => createConnection(platformCredentials),
          gatewayV2Service
        );
      } else {
        connection = await createConnection(validatedCredentials);
      }

      return addAppConnectionFederatedCredential({
        ...connection,
        credentialsHash: crypto.nativeCrypto.createHash("sha256").update(connection.encryptedCredentials).digest("hex"),
        credentials: validatedCredentials,
        configuration
      } as TAppConnection);
    } catch (err) {
      if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
        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;
    }
  };

  const updateAppConnection = async (
    app: AppConnection,
    {
      connectionId,
      credentials,
      configuration,
      gatewayId,
      gatewayPoolId,
      isAutoRotationEnabled,
      rotation,
      ...params
    }: TUpdateAppConnectionDTO,
    actor: OrgServiceActor,
    scope?: TAppConnectionScope
  ) => {
    if (gatewayId && gatewayPoolId) {
      throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
    }

    const appConnection = await appConnectionDAL.findById(connectionId);

    if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
      throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });

    await enterpriseAppCheck(
      licenseService,
      appConnection.app as AppConnection,
      actor.orgId,
      "Failed to update app connection due to plan restriction. Upgrade plan to access enterprise app connections."
    );

    const { permission: orgPermission } = await permissionService.getOrgPermission({
      actorId: actor.id,
      actor: actor.type,
      orgId: appConnection.orgId,
      actorOrgId: actor.orgId,
      actorAuthMethod: actor.authMethod,
      scope: OrganizationActionScope.Any
    });

    if (appConnection.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId: appConnection.projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Edit,
        subject(ProjectPermissionSub.AppConnections, { connectionId })
      );
    } else {
      ForbiddenError.from(orgPermission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Edit,
        subject(OrgPermissionSubjects.AppConnections, { connectionId })
      );
    }

    if (appConnection.app !== app)
      throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });

    if (gatewayId !== undefined && gatewayId !== appConnection.gatewayId) {
      ForbiddenError.from(orgPermission).throwUnlessCan(
        OrgPermissionGatewayActions.AttachGateways,
        OrgPermissionSubjects.Gateway
      );

      if (gatewayId) {
        const plan = await licenseService.getPlan(actor.orgId);
        if (!plan.gateway) {
          throw new BadRequestError({
            message:
              "Your current plan does not support gateway usage with app connections. Please upgrade your plan or contact Infisical Sales for assistance."
          });
        }

        const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: actor.orgId });
        if (!gatewayV2) {
          throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
        }

        await assertIndividualGatewayAllowed({ orgDAL, orgId: actor.orgId, gatewayId });
      }
    }

    // Mutual exclusion: setting one clears the other.
    let gatewayIdValue: string | null | undefined;
    let gatewayPoolIdValue: string | null | undefined;
    if (gatewayId !== undefined && gatewayPoolId !== undefined) {
      gatewayIdValue = gatewayId;
      gatewayPoolIdValue = gatewayPoolId;
    } else if (gatewayId !== undefined) {
      gatewayIdValue = gatewayId;
      gatewayPoolIdValue = gatewayId !== null ? null : undefined;
    } else if (gatewayPoolId !== undefined) {
      gatewayPoolIdValue = gatewayPoolId;
      gatewayIdValue = gatewayPoolId !== null ? null : undefined;
    }

    const effectiveGatewayIdForUpdate = gatewayIdValue !== undefined ? gatewayIdValue : appConnection.gatewayId;
    const effectiveGatewayPoolIdForUpdate =
      gatewayPoolIdValue !== undefined ? gatewayPoolIdValue : appConnection.gatewayPoolId;

    if (effectiveGatewayPoolIdForUpdate) {
      const isNewPoolAttachment =
        gatewayPoolId !== undefined && gatewayPoolId !== appConnection.gatewayPoolId && gatewayPoolId !== null;
      if (isNewPoolAttachment) {
        await gatewayPoolService.resolveAttachableGatewayFromPool({
          poolId: effectiveGatewayPoolIdForUpdate,
          orgId: actor.orgId,
          actor
        });
      }
    }

    // prevent updating credentials or management status if platform managed
    if (appConnection.isPlatformManagedCredentials && (params.isPlatformManagedCredentials === false || credentials)) {
      throw new BadRequestError({
        message: "Cannot update credentials or management status for platform managed connections"
      });
    }

    let updatedCredentials: undefined | TAppConnection["credentials"];

    const { method } = appConnection as DiscriminativePick<TAppConnectionConfig, "app" | "method">;
    let validationGatewayIdForUpdate: string | null | undefined = effectiveGatewayIdForUpdate;

    if (credentials) {
      // Only checked when the caller explicitly selects an app — merged-in existing credentials
      // (gitHubAppId undefined) keep already-configured connections editable.
      if (app === AppConnection.GitHub && method === GitHubConnectionMethod.App && appConnection.projectId) {
        const requestedGitHubAppId = (credentials as { gitHubAppId?: string | null }).gitHubAppId;
        if (requestedGitHubAppId) {
          await checkGitHubAppScopeAccess(requestedGitHubAppId, actor.orgId, orgPermission);
        }
      }

      let credentialsToValidate = credentials;

      if (
        app === AppConnection.GitHub &&
        method === GitHubConnectionMethod.App &&
        (credentials as { gitHubAppId?: string | null }).gitHubAppId === undefined
      ) {
        const existingCredentials = await decryptAppConnectionCredentials({
          orgId: appConnection.orgId,
          projectId: appConnection.projectId,
          encryptedCredentials: appConnection.encryptedCredentials,
          kmsService
        });
        const existingGitHubAppId = (existingCredentials as { gitHubAppId?: string | null }).gitHubAppId;
        if (existingGitHubAppId) {
          credentialsToValidate = { ...credentials, gitHubAppId: existingGitHubAppId } as typeof credentials;
        }
      }

      if (
        !VALIDATE_APP_CONNECTION_CREDENTIALS_MAP[app].safeParse({
          method,
          credentials: credentialsToValidate
        }).success
      )
        throw new BadRequestError({
          message: `Invalid credential format for ${
            APP_CONNECTION_NAME_MAP[app]
          } Connection with method ${getAppConnectionMethodName(method)}`
        });

      const updateProject = appConnection.projectId ? await projectDAL.findProjectById(appConnection.projectId) : null;

      const runUpdateValidation = (validationGatewayId: string | null | undefined) =>
        validateAppConnectionCredentials(
          {
            app,
            orgId: actor.orgId,
            projectId: appConnection.projectId,
            connection: { id: appConnection.id, name: appConnection.name },
            version: appConnection.version,
            credentials: credentialsToValidate,
            method,
            gatewayId: validationGatewayId,
            projectType: updateProject?.type
          } as TAppConnectionConfig,
          gatewayV2Service,
          { identityUaDAL, gitHubAppDAL, kmsService, keyStore, oidcIssuerService, actorId: actor.id }
        );

      // Validation only dials the target and reads back, so retrying it on another member is safe.
      if (effectiveGatewayPoolIdForUpdate) {
        const outcome = await gatewayPoolService.runWithPoolFailover(
          { poolId: effectiveGatewayPoolIdForUpdate },
          runUpdateValidation
        );
        updatedCredentials = outcome.result;
        validationGatewayIdForUpdate = outcome.gatewayId;
      } else {
        updatedCredentials = await runUpdateValidation(effectiveGatewayIdForUpdate);
      }

      if (!updatedCredentials)
        throw new BadRequestError({ message: "Unable to validate connection - check credentials" });

      // A Stripe connection is bound to the account its API keys live in. Letting a reconnect point
      // it at a different account would strand every key a rotation already generated: Stripe answers
      // a delete for an unknown key with a 404, which rotation reads as already retired, so the keys
      // in the original account stay live with no way to revoke them through Infisical.
      if (app === AppConnection.Stripe) {
        const existingCredentials = await decryptAppConnectionCredentials({
          orgId: appConnection.orgId,
          projectId: appConnection.projectId,
          encryptedCredentials: appConnection.encryptedCredentials,
          kmsService
        });

        const existingAccountId = (existingCredentials as { accountId?: string }).accountId;
        const updatedAccountId = (updatedCredentials as { accountId?: string }).accountId;

        if (existingAccountId && updatedAccountId !== existingAccountId) {
          throw new BadRequestError({
            message: `This connection is bound to Stripe account ${existingAccountId}, but the app was authorized on account ${updatedAccountId}. Reconnect using the same account, or create a new connection for ${updatedAccountId}.`
          });
        }
      }
    }

    try {
      const updateConnection = async (connectionCredentials: TAppConnection["credentials"] | undefined, tx?: Knex) => {
        const encryptedCredentials = connectionCredentials
          ? await encryptAppConnectionCredentials({
              credentials: connectionCredentials,
              orgId: actor.orgId,
              kmsService,
              projectId: appConnection.projectId
            })
          : undefined;

        const encryptedConfiguration =
          configuration !== undefined
            ? await encryptAppConnectionConfiguration({
                configuration,
                orgId: actor.orgId,
                kmsService,
                projectId: appConnection.projectId
              })
            : undefined;

        return appConnectionDAL.updateById(
          connectionId,
          {
            orgId: actor.orgId,
            encryptedCredentials,
            ...(encryptedConfiguration !== undefined && { encryptedConfiguration }),
            ...(gatewayIdValue !== undefined && { gatewayId: gatewayIdValue }),
            ...(gatewayPoolIdValue !== undefined && { gatewayPoolId: gatewayPoolIdValue }),
            ...params
          },
          tx
        );
      };

      // Check if the connection has an existing rotation
      const existingRotation = await appConnectionCredentialRotationService.getRotationByConnectionId(connectionId);

      if (params.isPlatformManagedCredentials) {
        if (!updatedCredentials)
          // prevent enabling platform managed credentials without re-confirming credentials
          throw new BadRequestError({ message: "Credentials required to transition to platform managed credentials" });
      }

      const updatedConnection = await appConnectionDAL.transaction(async (tx) => {
        if (credentials && existingRotation) {
          // Credential change with active rotation: tear down old rotation first
          await appConnectionCredentialRotationService.updateRotation(
            { connectionId, isAutoRotationEnabled: false },
            tx
          );
        }

        let connection: TAppConnectionRaw;
        if (params.isPlatformManagedCredentials) {
          connection = await TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM[app](
            {
              app,
              orgId: actor.orgId,
              credentials: updatedCredentials,
              method,
              gatewayId: validationGatewayIdForUpdate
            } as TAppConnectionConfig,
            (platformCredentials) => updateConnection(platformCredentials, tx),
            gatewayV2Service
          );
        } else {
          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 updates
        if (isAutoRotationEnabled !== undefined || rotation) {
          if (isAutoRotationEnabled === false) {
            // Disabling rotation — preserve config but stop scheduling
            if (!credentials && existingRotation) {
              await appConnectionCredentialRotationService.updateRotation(
                { connectionId, isAutoRotationEnabled: false },
                tx
              );
            }
          } else if (credentials && existingRotation) {
            // Credentials were changed and rotation was torn down above — re-enable with updated config
            await appConnectionCredentialRotationService.updateRotation(
              {
                connectionId,
                isAutoRotationEnabled: true,
                rotationInterval: rotation?.rotationInterval ?? existingRotation.rotationInterval,
                rotateAtUtc:
                  rotation?.rotateAtUtc ?? (existingRotation.rotateAtUtc as { hours: number; minutes: number })
              },
              tx
            );
          } else if (existingRotation && isAutoRotationEnabled === true) {
            // Re-enabling rotation on a connection that was previously disabled
            await appConnectionCredentialRotationService.updateRotation(
              { connectionId, isAutoRotationEnabled: true, ...rotation },
              tx
            );
          } else if (!existingRotation && isAutoRotationEnabled && rotation) {
            // Enabling rotation on a connection that never had it
            if (!rotation.rotationInterval || !rotation.rotateAtUtc) {
              throw new BadRequestError({
                message: "Rotation interval and schedule are required when enabling rotation"
              });
            }
            await appConnectionCredentialRotationService.createRotation(
              { connectionId, rotationInterval: rotation.rotationInterval, rotateAtUtc: rotation.rotateAtUtc },
              tx
            );
            await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true }, tx);
          } else if (existingRotation && rotation) {
            // Updating schedule/interval on existing rotation
            await appConnectionCredentialRotationService.updateRotation({ connectionId, ...rotation }, tx);
          }
        } else if (credentials && existingRotation) {
          // Credentials changed but no rotation fields provided — re-enable with previous config
          await appConnectionCredentialRotationService.updateRotation(
            {
              connectionId,
              isAutoRotationEnabled: true,
              rotationInterval: existingRotation.rotationInterval,
              rotateAtUtc: existingRotation.rotateAtUtc as { hours: number; minutes: number }
            },
            tx
          );
        }

        return connection;
      });

      return addAppConnectionFederatedCredential(await decryptAppConnection(updatedConnection, kmsService));
    } catch (err) {
      if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
        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;
    }
  };

  const deleteAppConnection = async (
    app: AppConnection,
    connectionId: string,
    actor: OrgServiceActor,
    scope?: TAppConnectionScope
  ) => {
    const appConnection = await appConnectionDAL.findById(connectionId);

    if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
      throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });

    if (appConnection.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId: appConnection.projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Delete,
        subject(ProjectPermissionSub.AppConnections, { connectionId })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        actorId: actor.id,
        actor: actor.type,
        orgId: appConnection.orgId,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Delete,
        subject(OrgPermissionSubjects.AppConnections, { connectionId })
      );
    }

    if (appConnection.app !== app)
      throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });

    // TODO (scott): add option to delete all dependencies

    // 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);

      return addAppConnectionFederatedCredential(await decryptAppConnection(deletedAppConnection, kmsService));
    } catch (err) {
      if (
        err instanceof DatabaseError &&
        (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation
      ) {
        const { constraint } = err.error as { constraint?: string };
        if (
          constraint === "approval_policy_auto_approval_inputs_connectionid_foreign" ||
          constraint === "approval_policy_auto_approval_conditions_connectionid_foreign"
        ) {
          throw new BadRequestError({
            message:
              "Cannot delete this App Connection because one or more approval policies use it in their auto-approval rules. Remove it from those rules first."
          });
        }
        if (constraint === "certificate_authority_secret_appconnectionid_foreign") {
          throw new BadRequestError({
            message:
              "Cannot delete this App Connection because a certificate authority signs with an AWS KMS key reached through it. Delete that certificate authority first."
          });
        }
        throw new BadRequestError({
          message:
            "Cannot delete App Connection with existing connections. Remove all existing connections and try again."
        });
      }

      throw err;
    }
  };

  const connectAppConnectionById = async <T extends TAppConnection>(
    app: AppConnection | AppConnection[],
    connectionId: string,
    actor: OrgServiceActor
  ) => {
    const allowedApps = Array.isArray(app) ? app : [app];
    const appConnection = await appConnectionDAL.findById(connectionId);

    if (!appConnection || appConnection.orgId !== actor.orgId)
      throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });

    const connectionApp = appConnection.app as AppConnection;

    if (appConnection.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId: appConnection.projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Connect,
        subject(ProjectPermissionSub.AppConnections, { connectionId })
      );
    } else {
      const { permission: orgPermission } = await permissionService.getOrgPermission({
        actorId: actor.id,
        actor: actor.type,
        orgId: appConnection.orgId,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(orgPermission).throwUnlessCan(
        OrgPermissionAppConnectionActions.Connect,
        subject(OrgPermissionSubjects.AppConnections, { connectionId })
      );
    }

    if (!allowedApps.includes(connectionApp))
      throw new BadRequestError({
        message: `${
          APP_CONNECTION_NAME_MAP[connectionApp]
        } Connection with ID ${connectionId} cannot be used to connect to ${allowedApps
          .map((allowedApp) => APP_CONNECTION_NAME_MAP[allowedApp])
          .join(" or ")}`
      });

    await enterpriseAppCheck(
      licenseService,
      connectionApp,
      actor.orgId,
      "Failed to connect app due to plan restriction. Upgrade plan to access enterprise app connections."
    );

    const connectionProject = appConnection.projectId
      ? await projectDAL.findProjectById(appConnection.projectId)
      : null;

    const connection = await decryptAppConnection(appConnection, kmsService);

    return { ...connection, projectType: connectionProject?.type } as unknown as T;
  };

  const validateAppConnectionUsageById = async (
    app: AppConnection | AppConnection[],
    { connectionId, projectId }: TValidateAppConnectionUsageByIdDTO,
    actor: OrgServiceActor
  ) => {
    const appConnection = await connectAppConnectionById(app, connectionId, actor);

    if (appConnection.projectId && appConnection.projectId !== projectId) {
      throw new BadRequestError({
        message: `You cannot connect project App Connection with ID "${appConnection.id}" from project with ID "${appConnection.projectId}" to project with ID "${projectId}"`
      });
    }

    return appConnection;
  };

  const listAvailableAppConnectionsForUser = async (app: AppConnection, actor: OrgServiceActor, projectId?: string) => {
    const { permission: orgPermission } = await permissionService.getOrgPermission({
      actorId: actor.id,
      actor: actor.type,
      orgId: actor.orgId,
      actorOrgId: actor.orgId,
      actorAuthMethod: actor.authMethod,
      scope: OrganizationActionScope.Any
    });

    let availableProjectConnections: TAppConnections[] = [];

    if (projectId) {
      const project = await projectDAL.findProjectById(projectId);

      if (!project) throw new BadRequestError({ message: `Could not find project with ID ${projectId}` });

      const { permission: projectPermission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(projectPermission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.Connect,
        ProjectPermissionSub.AppConnections
      );

      const projectAppConnections = await appConnectionDAL.find({ app, projectId });

      availableProjectConnections = projectAppConnections.filter((connection) =>
        projectPermission.can(
          ProjectPermissionAppConnectionActions.Connect,
          subject(ProjectPermissionSub.AppConnections, { connectionId: connection.id })
        )
      );
    }

    const orgAppConnections = await appConnectionDAL.find({ app, orgId: actor.orgId, projectId: null });

    const availableOrgConnections = orgAppConnections.filter((connection) =>
      orgPermission.can(
        OrgPermissionAppConnectionActions.Connect,
        subject(OrgPermissionSubjects.AppConnections, { connectionId: connection.id })
      )
    );

    return [...availableOrgConnections, ...availableProjectConnections].sort((a, b) =>
      a.name.toLowerCase().localeCompare(b.name.toLowerCase())
    ) as Omit<TAppConnection, "credentials">[];
  };

  const findAppConnectionUsageById = async (app: AppConnection, connectionId: string, actor: OrgServiceActor) => {
    const appConnection = await appConnectionDAL.findById(connectionId);

    if (!appConnection || appConnection.orgId !== actor.orgId)
      throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });

    const { permission } = await permissionService.getOrgPermission({
      actorId: actor.id,
      actor: actor.type,
      orgId: appConnection.orgId,
      actorOrgId: actor.orgId,
      actorAuthMethod: actor.authMethod,
      scope: OrganizationActionScope.Any
    });

    ForbiddenError.from(permission).throwUnlessCan(
      OrgPermissionAppConnectionActions.Read,
      OrgPermissionSubjects.AppConnections
    );

    if (appConnection.app !== app)
      throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });

    const projectUsage = await appConnectionDAL.findAppConnectionUsageById(connectionId);

    return projectUsage;
  };

  const triggerCredentialRotation = async (
    { app, connectionId }: { app: AppConnection; connectionId: string },
    actor: OrgServiceActor,
    scope?: TAppConnectionScope
  ) => {
    const appConnection = await appConnectionDAL.findById(connectionId);

    if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
      throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });

    if (appConnection.app !== app)
      throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });

    if (appConnection.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actor: actor.type,
        actorId: actor.id,
        projectId: appConnection.projectId,
        actorAuthMethod: actor.authMethod,
        actorOrgId: actor.orgId,
        actionProjectType: ActionProjectType.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionAppConnectionActions.RotateCredentials,
        subject(ProjectPermissionSub.AppConnections, { connectionId })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        actorId: actor.id,
        actor: actor.type,
        orgId: appConnection.orgId,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod,
        scope: OrganizationActionScope.Any
      });

      ForbiddenError.from(permission).throwUnlessCan(
        OrgPermissionAppConnectionActions.RotateCredentials,
        subject(OrgPermissionSubjects.AppConnections, { connectionId })
      );
    }

    return appConnectionCredentialRotationService.triggerRotation({ connectionId });
  };

  return {
    listAppConnectionOptions,
    listAppConnections,
    findAppConnectionById,
    findAppConnectionByName,
    createAppConnection,
    updateAppConnection,
    deleteAppConnection,
    connectAppConnectionById,
    validateAppConnectionUsageById,
    listAvailableAppConnectionsForUser,
    findAppConnectionUsageById,
    triggerCredentialRotation,
    github: githubConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService, {
      gitHubAppDAL,
      kmsService
    }),
    githubRadar: githubRadarConnectionService(connectAppConnectionById),
    gcp: gcpConnectionService(connectAppConnectionById),
    databricks: databricksConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    aws: awsConnectionService(connectAppConnectionById),
    kempLoadMaster: kempLoadMasterConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    imperva: impervaConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    humanitec: humanitecConnectionService(connectAppConnectionById),
    terraformCloud: terraformCloudConnectionService(connectAppConnectionById),
    camunda: camundaConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    vercel: vercelConnectionService(connectAppConnectionById),
    qovery: qoveryConnectionService(connectAppConnectionById),
    ona: onaConnectionService(connectAppConnectionById),
    azureClientSecrets: azureClientSecretsConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    azureDevOps: azureDevOpsConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    auth0: auth0ConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    salesforce: salesforceConnectionService(connectAppConnectionById),
    hcvault: hcVaultConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    windmill: windmillConnectionService(connectAppConnectionById),
    teamcity: teamcityConnectionService(connectAppConnectionById),
    oci: ociConnectionService(connectAppConnectionById, licenseService),
    onepass: onePassConnectionService(connectAppConnectionById),
    keeper: keeperConnectionService(connectAppConnectionById),
    cloud66: cloud66ConnectionService(connectAppConnectionById),
    heroku: herokuConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    render: renderConnectionService(connectAppConnectionById),
    flyio: flyioConnectionService(connectAppConnectionById),
    triggerDev: triggerDevConnectionService(connectAppConnectionById),
    gitlab: gitlabConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    cloudflare: cloudflareConnectionService(connectAppConnectionById),
    venafi: venafiConnectionService(connectAppConnectionById),
    azureAdcs: azureAdcsConnectionService(connectAppConnectionById),
    adcs: adcsConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    ldap: ldapConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService, keyStore),
    dnsMadeEasy: dnsMadeEasyConnectionService(connectAppConnectionById),
    ultraDNS: ultraDNSConnectionService(connectAppConnectionById),
    azureDns: azureDnsConnectionService(connectAppConnectionById),
    zabbix: zabbixConnectionService(connectAppConnectionById),
    railway: railwayConnectionService(connectAppConnectionById),
    hasuraCloud: hasuraCloudConnectionService(connectAppConnectionById),
    bitbucket: bitbucketConnectionService(connectAppConnectionById),
    checkly: checklyConnectionService(connectAppConnectionById),
    supabase: supabaseConnectionService(connectAppConnectionById),
    rundeck: rundeckConnectionService(connectAppConnectionById),
    portainer: portainerConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    digitalOcean: digitalOceanAppPlatformConnectionService(connectAppConnectionById),
    netlify: netlifyConnectionService(connectAppConnectionById),
    northflank: northflankConnectionService(connectAppConnectionById),
    externalInfisical: externalInfisicalConnectionService(connectAppConnectionById),
    okta: oktaConnectionService(connectAppConnectionById),
    datadog: datadogConnectionService(connectAppConnectionById),
    openai: openaiConnectionService(connectAppConnectionById),
    openRouter: openRouterConnectionService(connectAppConnectionById),
    laravelForge: laravelForgeConnectionService(connectAppConnectionById),
    chef: chefConnectionService(connectAppConnectionById, licenseService, gatewayV2Service, gatewayPoolService),
    octopusDeploy: octopusDeployConnectionService(connectAppConnectionById),
    dbt: dbtConnectionService(connectAppConnectionById),
    circleci: circleciConnectionService(connectAppConnectionById),
    azureEntraId: azureEntraIdConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
    doppler: dopplerConnectionService(connectAppConnectionById),
    digicert: digicertConnectionService(connectAppConnectionById),
    travisCI: travisCIConnectionService(connectAppConnectionById),
    snowflake: snowflakeConnectionService(connectAppConnectionById),
    litellm: liteLLMConnectionService(connectAppConnectionById),
    fireworks: fireworksConnectionService(connectAppConnectionById),
    nutanixPrismCentral: nutanixPrismCentralConnectionService(
      connectAppConnectionById,
      gatewayV2Service,
      gatewayPoolService
    ),
    powerDns: powerDnsConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    paloAltoNetworks: paloAltoNetworksConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
    spacelift: spaceliftConnectionService(connectAppConnectionById)
  };
};