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
addressed requested changes
Daniel Hougaardf5638a1b27d5
diff --git a/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.ts b/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.tsindex 13e78d7c84..90cc75bfe4 100644--- a/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.ts+++ b/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.ts@@ -2,6 +2,8 @@ import { Knex } from "knex";import { TableName } from "@app/db/schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";+export async function up(knex: Knex): Promise<void> {// Add isAutoRotationEnabled to app_connectionsif (!(await knex.schema.hasColumn(TableName.AppConnection, "isAutoRotationEnabled"))) {@@ -29,11 +31,14 @@ export async function up(knex: Knex): Promise<void> {t.binary("encryptedGeneratedCredentials").notNullable();t.timestamps(true, true, true);});++ await createOnUpdateTrigger(knex, TableName.AppConnectionCredentialRotation);}}export async function down(knex: Knex): Promise<void> {await knex.schema.dropTableIfExists(TableName.AppConnectionCredentialRotation);+ await dropOnUpdateTrigger(knex, TableName.AppConnectionCredentialRotation);if (await knex.schema.hasColumn(TableName.AppConnection, "isAutoRotationEnabled")) {await knex.schema.alterTable(TableName.AppConnection, (t) => {diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 22bd2248cc..26cefff54e 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2551,7 +2551,9 @@ export const AppConnections = {credentials: `The credentials used to connect with ${appName}.`,method: `The method used to authenticate with ${appName}.`,isPlatformManagedCredentials: `Whether or not the ${appName} Connection credentials should be managed by Infisical. Once enabled this cannot be reversed.`,- projectId: `The ID of the project to create the ${appName} Connection in.`+ projectId: `The ID of the project to create the ${appName} Connection in.`,+ isAutoRotationEnabled: `Whether or not automatic credential rotation is enabled for the ${appName} Connection.`,+ rotation: `The credential rotation configuration for the ${appName} Connection.`};},UPDATE: (app: AppConnection) => {@@ -2562,7 +2564,9 @@ export const AppConnections = {description: `The updated description of the ${appName} Connection.`,credentials: `The credentials used to connect with ${appName}.`,method: `The method used to authenticate with ${appName}.`,- isPlatformManagedCredentials: `Whether or not the ${appName} Connection credentials should be managed by Infisical. Once enabled this cannot be reversed.`+ isPlatformManagedCredentials: `Whether or not the ${appName} Connection credentials should be managed by Infisical. Once enabled this cannot be reversed.`,+ isAutoRotationEnabled: `Whether or not automatic credential rotation is enabled for the ${appName} Connection.`,+ rotation: `The updated credential rotation configuration for the ${appName} Connection.`};},DELETE: (app: AppConnection) => ({@@ -2630,7 +2634,9 @@ export const AppConnections = {clientSecret: "The Client Secret to use to connect with Azure Client Secrets.",certificateBody: "The certificate body in PEM format to use to connect with Azure Client Secrets.",privateKey:- "The private key to use to connect with Azure Client Secrets. This is never transmitted to Azure and is only used to sign the Azure client assertion with."+ "The private key to use to connect with Azure Client Secrets. This is never transmitted to Azure and is only used to sign the Azure client assertion with.",+ clientSecretKeyId:+ "The Key ID of the client secret in Azure AD. Required when enabling credential rotation so the original secret can be revoked."},AZURE_DEVOPS: {code: "The OAuth code to use to connect with Azure DevOps.",diff --git a/backend/src/services/app-connection/app-connection-dal.ts b/backend/src/services/app-connection/app-connection-dal.tsindex 9b6c38c6fd..4db0c2cdc7 100644--- a/backend/src/services/app-connection/app-connection-dal.ts+++ b/backend/src/services/app-connection/app-connection-dal.ts@@ -57,7 +57,7 @@ export const appConnectionDALFactory = (db: TDbClient) => {| undefined| null;- if (connection.isAutoRotationEnabled && connection.rotateAtUtc) {+ if (connection.rotateAtUtc) {const parsedRotationAtUtc = AppConnectionCredentialRotationRotateAtUtcSchema.safeParse(connection.rotateAtUtc);if (parsedRotationAtUtc.success) {diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex b2a8bfb8f0..472740cfb1 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -517,6 +517,7 @@ export const decryptAppConnection = async (lastRotationMessage: appConnection.rotation.encryptedLastRotationMessage? await decryptRotationMessage({orgId: appConnection.orgId,+ projectId: appConnection.projectId,encryptedLastRotationMessage: appConnection.rotation.encryptedLastRotationMessage,kmsService})diff --git a/backend/src/services/app-connection/app-connection-schemas.ts b/backend/src/services/app-connection/app-connection-schemas.tsindex 533975d0ee..3687b5a372 100644--- a/backend/src/services/app-connection/app-connection-schemas.ts+++ b/backend/src/services/app-connection/app-connection-schemas.ts@@ -20,16 +20,21 @@ export const BaseAppConnectionSchema = AppConnectionsSchema.omit({}).extend({rotation: z.object({- lastRotationMessage: z.string().optional().nullable(),- rotationInterval: z.number(),- nextRotationAt: z.date().nullable().optional(),- rotationStatus: z.nativeEnum(AppConnectionCredentialRotationStatus),- rotateAtUtc: z.object({- hours: z.number(),- minutes: z.number()- })+ lastRotationMessage: z.string().optional().nullable().describe("The message from the last rotation attempt."),+ rotationInterval: z.number().describe("The interval in days between credential rotations."),+ nextRotationAt: z.date().nullable().optional().describe("The next scheduled rotation time."),+ rotationStatus: z+ .nativeEnum(AppConnectionCredentialRotationStatus)+ .describe("The status of the last rotation attempt."),+ rotateAtUtc: z+ .object({+ hours: z.number().describe("The hour (0-23) at which to rotate."),+ minutes: z.number().describe("The minute (0-59) at which to rotate.")+ })+ .describe("The UTC time of day at which rotation should occur.")})- .optional(),+ .optional()+ .describe("The credential rotation configuration, if configured."),credentialsHash: z.string().optional(),project: z@@ -76,7 +81,7 @@ export const GenericCreateAppConnectionFieldsSchema = (.describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),isAutoRotationEnabled: supportsCredentialRotation- ? z.boolean().optional()+ ? z.boolean().optional().describe(AppConnections.CREATE(app).isAutoRotationEnabled): z.literal(false, {errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })@@ -85,7 +90,7 @@ export const GenericCreateAppConnectionFieldsSchema = (.describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),rotation: supportsCredentialRotation- ? CreateAppConnectionCredentialRotationSchema.optional()+ ? CreateAppConnectionCredentialRotationSchema.optional().describe(AppConnections.CREATE(app).rotation): z.undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }).or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))@@ -133,7 +138,7 @@ export const GenericUpdateAppConnectionFieldsSchema = (.describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),isAutoRotationEnabled: supportsCredentialRotation- ? z.boolean().optional()+ ? z.boolean().optional().describe(AppConnections.UPDATE(app).isAutoRotationEnabled): z.literal(false, {errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })@@ -142,7 +147,7 @@ export const GenericUpdateAppConnectionFieldsSchema = (.describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),rotation: supportsCredentialRotation- ? UpdateAppConnectionCredentialRotationSchema.omit({ isAutoRotationEnabled: true }).optional()+ ? UpdateAppConnectionCredentialRotationSchema.optional().describe(AppConnections.UPDATE(app).rotation): z.undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }).or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 363f2ba562..a3e73d883d 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -1,4 +1,5 @@import { ForbiddenError, subject } from "@casl/ability";+import { Knex } from "knex";import { ActionProjectType, OrganizationActionScope, TAppConnections } from "@app/db/schemas";import { ValidateChefConnectionCredentialsSchema } from "@app/ee/services/app-connections/chef";@@ -636,7 +637,7 @@ export const appConnectionServiceFactory = ({}try {- const updateConnection = async (connectionCredentials: TAppConnection["credentials"] | undefined) => {+ const updateConnection = async (connectionCredentials: TAppConnection["credentials"] | undefined, tx?: Knex) => {const encryptedCredentials = connectionCredentials? await encryptAppConnectionCredentials({credentials: connectionCredentials,@@ -646,98 +647,113 @@ export const appConnectionServiceFactory = ({}): undefined;- return appConnectionDAL.updateById(connectionId, {- orgId: actor.orgId,- encryptedCredentials,- gatewayId,- ...params- });+ return appConnectionDAL.updateById(+ connectionId,+ {+ orgId: actor.orgId,+ encryptedCredentials,+ gatewayId,+ ...params+ },+ tx+ );};- let updatedConnection: TAppConnectionRaw;-// Check if the connection has an existing rotationconst existingRotation = await appConnectionCredentialRotationService.getRotationByConnectionId(connectionId);- if (credentials && existingRotation) {- // Credential change with active rotation: tear down old rotation first- await appConnectionCredentialRotationService.updateRotation({- connectionId,- isAutoRotationEnabled: false- });- }-if (params.isPlatformManagedCredentials) {if (!updatedCredentials)// prevent enabling platform managed credentials without re-confirming credentialsthrow new BadRequestError({ message: "Credentials required to transition to platform managed credentials" });-- updatedConnection = await TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM[app](- {- app,- orgId: actor.orgId,- credentials: updatedCredentials,- method,- gatewayId- } as TAppConnectionConfig,- (platformCredentials) => updateConnection(platformCredentials),- gatewayService,- gatewayV2Service- );- } else {- updatedConnection = await updateConnection(updatedCredentials);}- // Handle rotation updates- if (isAutoRotationEnabled !== undefined || rotation) {- if (isAutoRotationEnabled === false) {- // Disabling rotation — tear down if it exists and wasn't already torn down above- if (!credentials && existingRotation) {- await appConnectionCredentialRotationService.updateRotation({- connectionId,- isAutoRotationEnabled: false- });+ 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+ } as TAppConnectionConfig,+ (platformCredentials) => updateConnection(platformCredentials, tx),+ gatewayService,+ gatewayV2Service+ );+ } else {+ connection = await updateConnection(updatedCredentials, 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-initialize+ const existingRotateAtUtc = existingRotation.rotateAtUtc as { hours: number; minutes: number };+ await appConnectionCredentialRotationService.createRotation(+ {+ connectionId,+ rotationInterval: rotation?.rotationInterval ?? existingRotation.rotationInterval,+ rotateAtUtc: rotation?.rotateAtUtc ?? existingRotateAtUtc+ },+ tx+ );+ await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true }, tx);+ } else if (existingRotation && isAutoRotationEnabled === true) {+ // Re-enabling rotation on a connection that was previously disabled (record preserved)+ 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 were changed and rotation was torn down above — re-initialize- const existingRotateAtUtc = existingRotation.rotateAtUtc as { hours: number; minutes: number };- await appConnectionCredentialRotationService.createRotation({- connectionId,- rotationInterval: rotation?.rotationInterval ?? existingRotation.rotationInterval,- rotateAtUtc: rotation?.rotateAtUtc ?? existingRotateAtUtc- });- // createRotation doesn't set isAutoRotationEnabled — restore it after re-initialization- await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true });- } else if (!existingRotation && isAutoRotationEnabled && rotation) {- // Enabling rotation on a connection that didn't have 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- });- await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true });- } else if (existingRotation && rotation) {- // Updating schedule/interval on existing rotation- await appConnectionCredentialRotationService.updateRotation({- connectionId,- ...rotation- });+ // Credentials changed but no rotation fields provided — re-initialize with previous config+ await appConnectionCredentialRotationService.createRotation(+ {+ connectionId,+ rotationInterval: existingRotation.rotationInterval,+ rotateAtUtc: existingRotation.rotateAtUtc as { hours: number; minutes: number }+ },+ tx+ );+ await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true }, tx);}- } else if (credentials && existingRotation) {- // Credentials changed but no rotation fields provided — re-initialize with previous config- await appConnectionCredentialRotationService.createRotation({- connectionId,- rotationInterval: existingRotation.rotationInterval,- rotateAtUtc: existingRotation.rotateAtUtc as { hours: number; minutes: number }- });- // createRotation doesn't set isAutoRotationEnabled — restore it after re-initialization- await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true });- }++ return connection;+ });return await decryptAppConnection(updatedConnection, kmsService);} catch (err) {diff --git a/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-schemas.ts b/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-schemas.tsindex 29ce16a756..880b48ce2d 100644--- a/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-schemas.ts+++ b/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-schemas.ts@@ -47,7 +47,12 @@ export const AzureClientSecretsConnectionClientSecretInputCredentialsSchema = z..trim().min(1, "Tenant ID required").describe(AppConnections.CREDENTIALS.AZURE_CLIENT_SECRETS.tenantId),- clientSecretKeyId: z.string().uuid().trim().optional()+ clientSecretKeyId: z+ .string()+ .uuid()+ .trim()+ .optional()+ .describe(AppConnections.CREDENTIALS.AZURE_CLIENT_SECRETS.clientSecretKeyId)});export const AzureClientSecretsConnectionCertificateInputCredentialsSchema = z.object({diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-fns.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-fns.tsindex 42dc4188f4..d6c08a8e26 100644--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-fns.ts+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-fns.ts@@ -102,17 +102,26 @@ export const calculateNextRotationAt = ({export const encryptCredentialRotationGeneratedCredentials = async ({orgId,+ projectId,generatedCredentials,kmsService}: {orgId: string;+ projectId: string | null | undefined;generatedCredentials: TAppConnectionCredentialRotationGeneratedCredentials;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;}) => {- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );const { cipherTextBlob } = encryptor({plainText: Buffer.from(JSON.stringify(generatedCredentials))@@ -123,17 +132,26 @@ export const encryptCredentialRotationGeneratedCredentials = async ({export const decryptCredentialRotationGeneratedCredentials = async ({orgId,+ projectId,encryptedGeneratedCredentials,kmsService}: {orgId: string;+ projectId: string | null | undefined;encryptedGeneratedCredentials: Buffer;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;}) => {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { decryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );const decryptedPlainTextBlob = decryptor({cipherTextBlob: encryptedGeneratedCredentials@@ -144,17 +162,26 @@ export const decryptCredentialRotationGeneratedCredentials = async ({export const encryptStrategyConfig = async ({orgId,+ projectId,config,kmsService}: {orgId: string;+ projectId: string | null | undefined;config: Record<string, unknown>;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;}) => {- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );const { cipherTextBlob } = encryptor({plainText: Buffer.from(JSON.stringify(config))@@ -165,17 +192,26 @@ export const encryptStrategyConfig = async ({export const decryptStrategyConfig = async <T>({orgId,+ projectId,encryptedStrategyConfig,kmsService}: {orgId: string;+ projectId: string | null | undefined;encryptedStrategyConfig: Buffer;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;}) => {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { decryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );const decryptedPlainTextBlob = decryptor({cipherTextBlob: encryptedStrategyConfig@@ -186,17 +222,26 @@ export const decryptStrategyConfig = async <T>({export const encryptRotationMessage = async ({orgId,+ projectId,message,kmsService}: {orgId: string;+ projectId: string | null | undefined;message: string;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;}) => {- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );const { cipherTextBlob } = encryptor({plainText: Buffer.from(message)@@ -207,17 +252,26 @@ export const encryptRotationMessage = async ({export const decryptRotationMessage = async ({orgId,+ projectId,encryptedLastRotationMessage,kmsService}: {orgId: string;+ projectId: string | null | undefined;encryptedLastRotationMessage: Buffer;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;}) => {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { decryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );const decryptedPlainTextBlob = decryptor({cipherTextBlob: encryptedLastRotationMessage@@ -229,15 +283,23 @@ export const decryptRotationMessage = async ({export const expandCredentialRotation = async ({ encryptedLastRotationMessage, ...rotation }: TAppConnectionCredentialRotationRaw,orgId: string,+ projectId: string | null | undefined,kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">): Promise<TAppConnectionCredentialRotation> => {let lastRotationMessage: string | null = null;if (encryptedLastRotationMessage) {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId- });+ const { decryptor } = await kmsService.createCipherPairWithDataKey(+ projectId+ ? {+ type: KmsDataKey.SecretManager,+ projectId+ }+ : {+ type: KmsDataKey.Organization,+ orgId+ }+ );lastRotationMessage = decryptor({cipherTextBlob: encryptedLastRotationMessagediff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-schemas.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-schemas.tsindex 8f0c6f2886..d36d8c7e5a 100644--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-schemas.ts+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-schemas.ts@@ -1,22 +1,22 @@import { z } from "zod";export const AppConnectionCredentialRotationRotateAtUtcSchema = z.object({- hours: z.number().int().min(0).max(23),- minutes: z.number().int().min(0).max(59)+ hours: z.number().int().min(0).max(23).describe("The hour (0-23) at which to rotate."),+ minutes: z.number().int().min(0).max(59).describe("The minute (0-59) at which to rotate.")});export const CreateAppConnectionCredentialRotationSchema = z.object({- rotationInterval: z.number().int().min(1).max(365),+ rotationInterval: z.number().int().min(1).max(365).describe("The interval in days between credential rotations."),rotateAtUtc: AppConnectionCredentialRotationRotateAtUtcSchema});export const UpdateAppConnectionCredentialRotationSchema = z.object({- rotationInterval: z.number().int().min(1).max(365).optional(),- rotateAtUtc: z- .object({- hours: z.number().int().min(0).max(23),- minutes: z.number().int().min(0).max(59)- })- .optional(),- isAutoRotationEnabled: z.boolean().optional()+ rotationInterval: z+ .number()+ .int()+ .min(1)+ .max(365)+ .optional()+ .describe("The interval in days between credential rotations."),+ rotateAtUtc: AppConnectionCredentialRotationRotateAtUtcSchema.optional()});diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.tsindex 682a60c79c..c39b61f4ab 100644--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts@@ -14,7 +14,7 @@ import {} from "@app/services/app-connection/app-connection-fns";import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { TAppConnection } from "../app-connection-types";+import { TAppConnection, TAppConnectionRaw } from "../app-connection-types";import { AzureClientSecretsConnectionMethod } from "../azure-client-secrets";import { AzureKeyVaultConnectionMethod } from "../azure-key-vault";import { TAppConnectionCredentialRotationDALFactory } from "./app-connection-credential-rotation-dal";@@ -50,8 +50,8 @@ const MAX_GENERATED_CREDENTIALS_LENGTH = 2;const STRATEGY_MAP: Record<AppConnectionCredentialRotationStrategy,{- app: TAppConnection["app"]; // azure-key-vault- method: TAppConnection["method"]; // client-secret+ app: TAppConnection["app"];+ method: TAppConnection["method"];}[]> = {[AppConnectionCredentialRotationStrategy.AzureClientSecret]: [@@ -168,24 +168,21 @@ export const appConnectionCredentialRotationServiceFactory = ({const credentials = await getConnectionClientCredentials(connection);- const { strategyConfig, generatedCredentials, updatedCredentials } = await provider.issueInitialCredentials(- credentials,- rotationInterval- );-- // Update the connection to use the new credential- await updateConnectionCredentials(connectionId, updatedCredentials as TAppConnection["credentials"], tx);+ const { strategyConfig, generatedCredentials, updatedCredentials, postCommitCallback } =+ await provider.issueInitialCredentials(credentials, rotationInterval);const now = new Date();const encryptedGeneratedCreds = await encryptCredentialRotationGeneratedCredentials({orgId: connection.orgId,+ projectId: connection.projectId,generatedCredentials,kmsService});const encryptedConfig = await encryptStrategyConfig({orgId: connection.orgId,+ projectId: connection.projectId,config: strategyConfig,kmsService});@@ -200,6 +197,8 @@ export const appConnectionCredentialRotationServiceFactory = ({});const create = async (trx: Knex) => {+ await updateConnectionCredentials(connectionId, updatedCredentials as TAppConnection["credentials"], trx);+return appConnectionCredentialRotationDAL.create({connectionId,@@ -220,7 +219,13 @@ export const appConnectionCredentialRotationServiceFactory = ({const rotation = tx ? await create(tx) : await appConnectionDAL.transaction(create);- return expandCredentialRotation(rotation, connection.orgId, kmsService);+ // Revoke old credentials only after the transaction has committed successfully,+ // so we don't end up with a dead connection if the DB write fails.+ if (postCommitCallback) {+ await postCommitCallback();+ }++ return expandCredentialRotation(rotation, connection.orgId, connection.projectId, kmsService);};/**@@ -238,24 +243,46 @@ export const appConnectionCredentialRotationServiceFactory = ({throw new NotFoundError({ message: "Credential rotation is not configured for this connection" });}- const update = async (trx: Knex) => {- await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: false }, trx);- await appConnectionCredentialRotationDAL.deleteById(existingRotation.id, trx);-- return null;- };-- // If disabling auto rotation, delete the rotation config+ // If disabling auto rotation, preserve the rotation record but null out nextRotationAt so cron won't pick it upif (isAutoRotationEnabled === false) {+ const disable = async (trx: Knex) => {+ await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: false }, trx);+ await appConnectionCredentialRotationDAL.updateById(existingRotation.id, { nextRotationAt: null }, trx);+ };+if (tx) {- await update(tx);+ await disable(tx);} else {- await appConnectionDAL.transaction(update);+ await appConnectionDAL.transaction(disable);}return null;}+ // If re-enabling auto rotation, recalculate nextRotationAt+ if (isAutoRotationEnabled === true && !existingRotation.nextRotationAt) {+ const resolvedRotateAtUtc = rotateAtUtc || (existingRotation.rotateAtUtc as { hours: number; minutes: number });+ const resolvedInterval = rotationInterval ?? existingRotation.rotationInterval;++ const nextRotationAt = calculateNextRotationAt({+ rotateAtUtc: resolvedRotateAtUtc,+ isAutoRotationEnabled: true,+ rotationInterval: resolvedInterval,+ rotationStatus: existingRotation.rotationStatus,+ isManualRotation: false,+ lastRotatedAt: existingRotation.lastRotatedAt ?? new Date()+ });++ await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled: true }, tx);++ const updateData: Record<string, unknown> = { nextRotationAt };+ if (rotationInterval !== undefined) updateData.rotationInterval = rotationInterval;+ if (rotateAtUtc !== undefined) updateData.rotateAtUtc = JSON.stringify(rotateAtUtc);++ const updated = await appConnectionCredentialRotationDAL.updateById(existingRotation.id, updateData, tx);+ return expandCredentialRotation(updated, connection.orgId, connection.projectId, kmsService);+ }+// Build update payloadconst updateData: Record<string, unknown> = {};@@ -289,7 +316,7 @@ export const appConnectionCredentialRotationServiceFactory = ({}const updated = await appConnectionCredentialRotationDAL.updateById(existingRotation.id, updateData, tx);- return expandCredentialRotation(updated, connection.orgId, kmsService);+ return expandCredentialRotation(updated, connection.orgId, connection.projectId, kmsService);};/**@@ -303,7 +330,7 @@ export const appConnectionCredentialRotationServiceFactory = ({const rotation = await appConnectionCredentialRotationDAL.findByConnectionId(connectionId, tx);if (!rotation) return null;- return expandCredentialRotation(rotation, connection.orgId, kmsService);+ return expandCredentialRotation(rotation, connection.orgId, connection.projectId, kmsService);};/**@@ -337,7 +364,7 @@ export const appConnectionCredentialRotationServiceFactory = ({});- return expandCredentialRotation(rotation, connection.orgId, kmsService);+ return expandCredentialRotation(rotation, connection.orgId, connection.projectId, kmsService);};/**@@ -371,6 +398,7 @@ export const appConnectionCredentialRotationServiceFactory = ({const now = new Date();const rotateAtUtc = rotationWithConnection.rotateAtUtc as { hours: number; minutes: number };+ let connection: TAppConnectionRaw | undefined;try {// Acquire lock to prevent concurrent rotationsconst lockKey = `credential-rotation-lock-${rotationId}`;@@ -378,7 +406,7 @@ export const appConnectionCredentialRotationServiceFactory = ({try {// Decrypt connection credentials (for Graph API self-rotation)- const connection = await appConnectionDAL.findById(connectionId);+ connection = await appConnectionDAL.findById(connectionId);if (!connection) throw new Error(`Connection ${connectionId} not found`);const credentials = await getConnectionClientCredentials(connection);@@ -386,12 +414,14 @@ export const appConnectionCredentialRotationServiceFactory = ({// Decrypt strategy config and generated credentialsconst config = await decryptStrategyConfig<TAppConnectionCredentialRotationStrategyConfig>({orgId,+ projectId: connection.projectId,encryptedStrategyConfig: encryptedConfig,kmsService});const generatedCredentials = await decryptCredentialRotationGeneratedCredentials({orgId,+ projectId: connection.projectId,encryptedGeneratedCredentials: encryptedGenCreds,kmsService});@@ -422,35 +452,18 @@ export const appConnectionCredentialRotationServiceFactory = ({inactiveIndex);- // Step 2: Update connection credentials with new secret+ // Step 2: Update connection credentials and rotation metadata atomicallyconst updatedCredentials = provider.mergeCredentials(credentials,newCredential) as TAppConnection["credentials"];- await updateConnectionCredentials(connectionId, updatedCredentials);- // Step 3: Revoke old credential at inactive index (best-effort, non-fatal)- // If this fails, we have 3 secrets temporarily — they'll be cleaned up on the next cycle.- if (inactiveCredential) {- try {- logger.info(- `credentialRotation: Revoking old credential keyId=${inactiveCredential.keyId} at index=${inactiveIndex} [rotationId=${rotationId}]`- );- await provider.revokeCredential(inactiveCredential, config, parsedCredentials.data);- } catch (revokeError) {- logger.warn(- revokeError,- `credentialRotation: Failed to revoke old credential keyId=${inactiveCredential.keyId} [rotationId=${rotationId}] — will retry on next cycle`- );- }- }-- // Step 4: Store new credential and swap active indexconst updatedGeneratedCredentials = [...generatedCredentials];updatedGeneratedCredentials[inactiveIndex] = newCredential;const encryptedUpdatedGenCreds = await encryptCredentialRotationGeneratedCredentials({orgId,+ projectId: connection.projectId,generatedCredentials: updatedGeneratedCredentials,kmsService});@@ -464,17 +477,39 @@ export const appConnectionCredentialRotationServiceFactory = ({lastRotatedAt: now});- await appConnectionCredentialRotationDAL.updateById(rotationId, {- activeIndex: inactiveIndex,- encryptedGeneratedCredentials: encryptedUpdatedGenCreds,- rotationStatus: AppConnectionCredentialRotationStatus.Success,- lastRotatedAt: now,- lastRotationAttemptedAt: now,- lastRotationJobId: options.jobId,- nextRotationAt,- encryptedLastRotationMessage: null+ await appConnectionDAL.transaction(async (tx) => {+ await updateConnectionCredentials(connectionId, updatedCredentials, tx);+ await appConnectionCredentialRotationDAL.updateById(+ rotationId,+ {+ activeIndex: inactiveIndex,+ encryptedGeneratedCredentials: encryptedUpdatedGenCreds,+ rotationStatus: AppConnectionCredentialRotationStatus.Success,+ lastRotatedAt: now,+ lastRotationAttemptedAt: now,+ lastRotationJobId: options.jobId,+ nextRotationAt,+ encryptedLastRotationMessage: null+ },+ tx+ );});+ // revoke old credential at inactive index after the transaction commits (best-effort)+ if (inactiveCredential) {+ try {+ logger.info(+ `credentialRotation: Revoking old credential keyId=${inactiveCredential.keyId} at index=${inactiveIndex} [rotationId=${rotationId}]`+ );+ await provider.revokeCredential(inactiveCredential, config, parsedCredentials.data);+ } catch (revokeError) {+ logger.warn(+ revokeError,+ `credentialRotation: Failed to revoke old credential keyId=${inactiveCredential.keyId} [rotationId=${rotationId}] — will retry on next cycle`+ );+ }+ }+logger.info(`credentialRotation: Successfully rotated [rotationId=${rotationId}] [connectionId=${connectionId}]`);@@ -485,11 +520,15 @@ export const appConnectionCredentialRotationServiceFactory = ({logger.error(error, `credentialRotation: Failed to rotate [rotationId=${rotationId}]`);const errorMessage = parseRotationErrorMessage(error);- const encryptedMessage = await encryptRotationMessage({- orgId,- message: errorMessage,- kmsService- });+ let encryptedMessage: Buffer | undefined;+ if (connection) {+ encryptedMessage = await encryptRotationMessage({+ orgId,+ projectId: connection.projectId,+ message: errorMessage,+ kmsService+ });+ }const nextRotationAt = calculateNextRotationAt({rotateAtUtc,@@ -504,7 +543,7 @@ export const appConnectionCredentialRotationServiceFactory = ({rotationStatus: AppConnectionCredentialRotationStatus.Failed,lastRotationAttemptedAt: now,lastRotationJobId: options.jobId,- encryptedLastRotationMessage: encryptedMessage,+ ...(encryptedMessage ? { encryptedLastRotationMessage: encryptedMessage } : {}),nextRotationAt});diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.tsindex 0951487e46..d4c6ef557c 100644--- a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts@@ -45,6 +45,7 @@ export type TCredentialRotationIssueInitialCredentials<strategyConfig: S;generatedCredentials: (C | null)[];updatedCredentials: Record<string, unknown>;+ postCommitCallback?: () => Promise<void>;}>;export type TCredentialRotationCreateCredential<diff --git a/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts b/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.tsindex adf3f6a9c5..07877d2f51 100644--- a/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts+++ b/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret/azure-client-secret-credential-rotation-fns.ts@@ -394,25 +394,29 @@ export const azureClientSecretRotationProviderFactory: TCredentialRotationProvid// getGraphApiToken has built-in retry logic for propagation delays (AADSTS7000215).const freshAccessToken = await getGraphApiToken(updatedCredentials);- // Revoke the original user-provided secret using its Key ID.- try {- await revokeAzureClientSecret(originalKeyId, strategyConfig, updatedCredentials, freshAccessToken);- logger.info(- `credentialRotation: Revoked original client secret keyId=${originalKeyId} [connection=${connection.name}]`- );- } catch (e) {- logger.warn(- e,- `credentialRotation: Failed to revoke original client secret keyId=${originalKeyId} [connection=${connection.name}] — it will need to be removed manually or will expire naturally`- );- }-const generatedCredentials: (TAzureClientSecretGeneratedCredential | null)[] = [newCredential, null];+ // Revoke the original user-provided secret AFTER the DB transaction commits,+ // so we don't end up with a dead connection if the transaction fails.+ const postCommitCallback = async () => {+ try {+ await revokeAzureClientSecret(originalKeyId, strategyConfig, updatedCredentials, freshAccessToken);+ logger.info(+ `credentialRotation: Revoked original client secret keyId=${originalKeyId} [connection=${connection.name}]`+ );+ } catch (e) {+ logger.warn(+ e,+ `credentialRotation: Failed to revoke original client secret keyId=${originalKeyId} [connection=${connection.name}] — it will need to be removed manually or will expire naturally`+ );+ }+ };+return {strategyConfig,generatedCredentials,- updatedCredentials+ updatedCredentials,+ postCommitCallback};};diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsxindex 737bcd845c..45ebd8c5a2 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx@@ -322,24 +322,22 @@ export const AzureClientSecretsConnectionForm = ({ appConnection, onSubmit, proj)}/>- <CredentialRotationForm- renderExtraFields={- <Controller- name="credentials.clientSecretKeyId"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- label="Client Secret Key ID"- errorText={error?.message}- tooltipText="The Key ID of the client secret provided above. Found in Azure Portal under App Registrations > Certificates & Secrets. Required so Infisical can revoke the original secret after rotation."- >- <Input {...field} placeholder="00000000-0000-0000-0000-000000000000" />- </FormControl>- )}- />- }- />+ <CredentialRotationForm>+ <Controller+ name="credentials.clientSecretKeyId"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error?.message)}+ label="Client Secret Key ID"+ errorText={error?.message}+ tooltipText="The Key ID of the client secret provided above. Found in Azure Portal under App Registrations > Certificates & Secrets. Required so Infisical can revoke the original secret after rotation."+ >+ <Input {...field} placeholder="00000000-0000-0000-0000-000000000000" />+ </FormControl>+ )}+ />+ </CredentialRotationForm></>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsxindex 0d36e4c4eb..ac5315b9e9 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx@@ -286,25 +286,22 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId</FormControl>)}/>-- <CredentialRotationForm- renderExtraFields={- <Controller- name="credentials.clientSecretKeyId"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- label="Client Secret Key ID"- errorText={error?.message}- tooltipText="The Key ID of the client secret provided above. Found in Azure Portal under App Registrations > Certificates & Secrets. Required so Infisical can revoke the original secret after rotation."- >- <Input {...field} placeholder="00000000-0000-0000-0000-000000000000" />- </FormControl>- )}- />- }- />+ <CredentialRotationForm>+ <Controller+ name="credentials.clientSecretKeyId"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error?.message)}+ label="Client Secret Key ID"+ errorText={error?.message}+ tooltipText="The Key ID of the client secret provided above. Found in Azure Portal under App Registrations > Certificates & Secrets. Required so Infisical can revoke the original secret after rotation."+ >+ <Input {...field} placeholder="00000000-0000-0000-0000-000000000000" />+ </FormControl>+ )}+ />+ </CredentialRotationForm></>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/CredentialRotationForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/CredentialRotationForm.tsxindex 361e8d2c76..6991579598 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/CredentialRotationForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/CredentialRotationForm.tsx@@ -7,10 +7,10 @@ import { FormControl, Input, Switch } from "@app/components/v2";import { getRotateAtLocal } from "@app/helpers/secretRotationsV2";type Props = {- renderExtraFields?: ReactNode;+ children?: ReactNode;};-export const CredentialRotationForm = ({ renderExtraFields }: Props) => {+export const CredentialRotationForm = ({ children }: Props) => {const { control, watch } = useFormContext();const isAutoRotationEnabled = watch("isAutoRotationEnabled");@@ -37,7 +37,7 @@ export const CredentialRotationForm = ({ renderExtraFields }: Props) => {isChecked={value}onCheckedChange={onChange}>- <p className="w-[13.6rem]">Automatic Credential Rotation</p>+ <p>Automatic Credential Rotation</p></Switch></FormControl>)}@@ -46,7 +46,7 @@ export const CredentialRotationForm = ({ renderExtraFields }: Props) => {{isAutoRotationEnabled && (<>- {renderExtraFields}+ {children}<div className="flex w-full items-center gap-2"><Controllerrender={({ field: { value, onChange }, fieldState: { error } }) => (