Skip to content

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

checkpoint

Daniel Hougaard24aafe239256
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 917caa95a0..fe6fdd1b87 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -63,6 +63,7 @@ import { TAccountRecoveryServiceFactory } from "@app/services/account-recovery/a
import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";
import { TApiKeyServiceFactory } from "@app/services/api-key/api-key-service";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
+import { TAppConnectionCredentialRotationServiceFactory } from "@app/services/app-connection/credential-rotation";
import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { TAuthPasswordFactory } from "@app/services/auth/auth-password-service";
@@ -383,6 +384,7 @@ declare module "fastify" {
aiMcpEndpoint: TAiMcpEndpointServiceFactory;
aiMcpActivityLog: TAiMcpActivityLogServiceFactory;
approvalPolicy: TApprovalPolicyServiceFactory;
+ appConnectionCredentialRotation: TAppConnectionCredentialRotationServiceFactory;
};
// this is exclusive use for middlewares in which we need to inject data
// everywhere else access using service layer
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 09136cd3fa..7a44978fed 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -44,6 +44,9 @@ import {
TApiKeys,
TApiKeysInsert,
TApiKeysUpdate,
+ TAppConnectionCredentialRotations,
+ TAppConnectionCredentialRotationsInsert,
+ TAppConnectionCredentialRotationsUpdate,
TAppConnections,
TAppConnectionsInsert,
TAppConnectionsUpdate,
@@ -1608,5 +1611,10 @@ declare module "knex/types/tables" {
>;
[TableName.QueueJobs]: KnexOriginal.CompositeTableType<TQueueJobs, TQueueJobsInsert, TQueueJobsUpdate>;
+ [TableName.AppConnectionCredentialRotation]: KnexOriginal.CompositeTableType<
+ TAppConnectionCredentialRotations,
+ TAppConnectionCredentialRotationsInsert,
+ TAppConnectionCredentialRotationsUpdate
+ >;
}
}
diff --git a/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.ts b/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.ts
new file mode 100644
index 0000000000..13e78d7c84
--- /dev/null
+++ b/backend/src/db/migrations/20260220000000_app-connection-credential-rotation.ts
@@ -0,0 +1,43 @@
+import { Knex } from "knex";
+
+import { TableName } from "@app/db/schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ // Add isAutoRotationEnabled to app_connections
+ if (!(await knex.schema.hasColumn(TableName.AppConnection, "isAutoRotationEnabled"))) {
+ await knex.schema.alterTable(TableName.AppConnection, (t) => {
+ t.boolean("isAutoRotationEnabled").defaultTo(false).notNullable();
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AppConnectionCredentialRotation))) {
+ await knex.schema.createTable(TableName.AppConnectionCredentialRotation, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("connectionId").notNullable().unique();
+ t.foreign("connectionId").references("id").inTable(TableName.AppConnection).onDelete("CASCADE");
+ t.string("strategy").notNullable();
+ t.binary("encryptedStrategyConfig").notNullable();
+ t.integer("rotationInterval").notNullable();
+ t.jsonb("rotateAtUtc").notNullable();
+ t.string("rotationStatus").notNullable();
+ t.timestamp("lastRotationAttemptedAt").nullable();
+ t.timestamp("lastRotatedAt").nullable();
+ t.binary("encryptedLastRotationMessage").nullable();
+ t.string("lastRotationJobId").nullable();
+ t.timestamp("nextRotationAt").nullable();
+ t.integer("activeIndex").notNullable().defaultTo(0);
+ t.binary("encryptedGeneratedCredentials").notNullable();
+ t.timestamps(true, true, true);
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.AppConnectionCredentialRotation);
+
+ if (await knex.schema.hasColumn(TableName.AppConnection, "isAutoRotationEnabled")) {
+ await knex.schema.alterTable(TableName.AppConnection, (t) => {
+ t.dropColumn("isAutoRotationEnabled");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/app-connection-credential-rotations.ts b/backend/src/db/schemas/app-connection-credential-rotations.ts
new file mode 100644
index 0000000000..57c28acbd5
--- /dev/null
+++ b/backend/src/db/schemas/app-connection-credential-rotations.ts
@@ -0,0 +1,38 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AppConnectionCredentialRotationsSchema = z.object({
+ id: z.string().uuid(),
+ connectionId: z.string().uuid(),
+ strategy: z.string(),
+ encryptedStrategyConfig: zodBuffer,
+ rotationInterval: z.number(),
+ rotateAtUtc: z.unknown(),
+ rotationStatus: z.string(),
+ lastRotationAttemptedAt: z.date().nullable().optional(),
+ lastRotatedAt: z.date().nullable().optional(),
+ encryptedLastRotationMessage: zodBuffer.nullable().optional(),
+ lastRotationJobId: z.string().nullable().optional(),
+ nextRotationAt: z.date().nullable().optional(),
+ activeIndex: z.number().default(0),
+ encryptedGeneratedCredentials: zodBuffer,
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAppConnectionCredentialRotations = z.infer<typeof AppConnectionCredentialRotationsSchema>;
+export type TAppConnectionCredentialRotationsInsert = Omit<
+ z.input<typeof AppConnectionCredentialRotationsSchema>,
+ TImmutableDBKeys
+>;
+export type TAppConnectionCredentialRotationsUpdate = Partial<
+ Omit<z.input<typeof AppConnectionCredentialRotationsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/app-connections.ts b/backend/src/db/schemas/app-connections.ts
index 41d1df17fa..a747c58b64 100644
--- a/backend/src/db/schemas/app-connections.ts
+++ b/backend/src/db/schemas/app-connections.ts
@@ -21,6 +21,7 @@ export const AppConnectionsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
isPlatformManagedCredentials: z.boolean().default(false).nullable().optional(),
+ isAutoRotationEnabled: z.boolean().default(false),
gatewayId: z.string().uuid().nullable().optional(),
projectId: z.string().nullable().optional()
});
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 9e017b7a62..4c962cb109 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -12,6 +12,7 @@ export * from "./ai-mcp-server-tools";
export * from "./ai-mcp-server-user-credentials";
export * from "./ai-mcp-servers";
export * from "./api-keys";
+export * from "./app-connection-credential-rotations";
export * from "./app-connections";
export * from "./approval-policies";
export * from "./approval-policy-step-approvers";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 61e0e88a31..631dedd80e 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -173,6 +173,7 @@ export enum TableName {
SlackIntegrations = "slack_integrations",
ProjectSlackConfigs = "project_slack_configs",
AppConnection = "app_connections",
+ AppConnectionCredentialRotation = "app_connection_credential_rotations",
SecretSync = "secret_syncs",
PkiSync = "pki_syncs",
CertificateSync = "certificate_syncs",
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts
index 3a25b37260..4ef50038cc 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts
@@ -49,6 +49,7 @@ const baseSecretRotationV2Query = ({
db.ref("app").withSchema(TableName.AppConnection).as("connectionApp"),
db.ref("orgId").withSchema(TableName.AppConnection).as("connectionOrgId"),
db.ref("encryptedCredentials").withSchema(TableName.AppConnection).as("connectionEncryptedCredentials"),
+ db.ref("isAutoRotationEnabled").withSchema(TableName.AppConnection).as("connectionIsAutoRotationEnabled"),
db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),
db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),
db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),
@@ -109,6 +110,7 @@ const expandSecretRotation = <T extends Awaited<ReturnType<typeof baseSecretRota
connectionGatewayId,
connectionProjectId,
connectionIsPlatformManagedCredentials,
+ connectionIsAutoRotationEnabled,
...el
} = secretRotation;
@@ -129,7 +131,8 @@ const expandSecretRotation = <T extends Awaited<ReturnType<typeof baseSecretRota
version: connectionVersion,
gatewayId: connectionGatewayId,
projectId: connectionProjectId,
- isPlatformManagedCredentials: connectionIsPlatformManagedCredentials
+ isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,
+ isAutoRotationEnabled: connectionIsAutoRotationEnabled
},
folder: {
id: folder!.id,
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 0fa2884eec..e122cdd4f0 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -20,6 +20,10 @@ import { buildRedisFromConfig, TRedisConfigKeys } from "@app/lib/config/redis";
import { crypto } from "@app/lib/crypto";
import { logger } from "@app/lib/logger";
import { QueueWorkerProfile } from "@app/lib/types";
+import {
+ TAppConnectionCredentialRotationRotateJobPayload,
+ TAppConnectionCredentialRotationSendNotificationJobPayload
+} from "@app/services/app-connection/credential-rotation/app-connection-credential-rotation-types";
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { ExternalPlatforms } from "@app/services/external-migration/external-migration-types";
import { TCreateUserNotificationDTO } from "@app/services/notification/notification-types";
@@ -95,7 +99,9 @@ export enum QueueName {
PamAccountRotation = "pam-account-rotation",
PamSessionExpiration = "pam-session-expiration",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
- PkiDiscoveryScan = "pki-discovery-scan"
+ PkiDiscoveryScan = "pki-discovery-scan",
+ AppConnectionCredentialRotation = "app-connection-credential-rotation",
+ AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate"
}
export enum QueueJobs {
@@ -158,7 +164,10 @@ export enum QueueJobs {
PamSessionExpiration = "pam-session-expiration",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
PkiDiscoveryRunScan = "pki-discovery-run-scan",
- PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan"
+ PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",
+ AppConnectionCredentialRotationQueueRotations = "app-connection-credential-rotation-queue-rotations",
+ AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
+ AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification"
}
export type TQueueOptions = {
@@ -480,6 +489,19 @@ export type TQueueJobTypes = {
name: QueueJobs.PkiDiscoveryScheduledScan;
payload: undefined;
};
+ [QueueName.AppConnectionCredentialRotation]:
+ | {
+ name: QueueJobs.AppConnectionCredentialRotationQueueRotations;
+ payload: undefined;
+ }
+ | {
+ name: QueueJobs.AppConnectionCredentialRotationSendNotification;
+ payload: TAppConnectionCredentialRotationSendNotificationJobPayload;
+ };
+ [QueueName.AppConnectionCredentialRotationRotate]: {
+ name: QueueJobs.AppConnectionCredentialRotationRotate;
+ payload: TAppConnectionCredentialRotationRotateJobPayload;
+ };
};
const SECRET_SCANNING_QUEUES = [
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 777067d05f..c7e5bd84e6 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -193,6 +193,11 @@ import { apiKeyDALFactory } from "@app/services/api-key/api-key-dal";
import { apiKeyServiceFactory } from "@app/services/api-key/api-key-service";
import { appConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { appConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
+import {
+ appConnectionCredentialRotationDALFactory,
+ appConnectionCredentialRotationQueueFactory,
+ appConnectionCredentialRotationServiceFactory
+} from "@app/services/app-connection/credential-rotation";
import {
approvalPolicyDALFactory,
approvalPolicyStepApproversDALFactory,
@@ -635,6 +640,8 @@ export const registerRoutes = async (
const pkiAlertChannelDAL = pkiAlertChannelDALFactory(db);
const pkiAlertV2DAL = pkiAlertV2DALFactory(db);
+ const appConnectionCredentialRotationDAL = appConnectionCredentialRotationDALFactory(db);
+
const vaultExternalMigrationConfigDAL = vaultExternalMigrationConfigDALFactory(db);
// New event bus for inter-container communication
@@ -2150,6 +2157,14 @@ export const registerRoutes = async (
roleDAL
});
+ const appConnectionCredentialRotationService = appConnectionCredentialRotationServiceFactory({
+ appConnectionCredentialRotationDAL,
+ appConnectionDAL,
+ keyStore,
+ kmsService,
+ queueService
+ });
+
const appConnectionService = appConnectionServiceFactory({
appConnectionDAL,
permissionService,
@@ -2159,7 +2174,8 @@ export const registerRoutes = async (
gatewayV2Service,
gatewayDAL,
gatewayV2DAL,
- projectDAL
+ projectDAL,
+ appConnectionCredentialRotationService
});
const secretSyncService = secretSyncServiceFactory({
@@ -2571,6 +2587,12 @@ export const registerRoutes = async (
notificationService
});
+ await appConnectionCredentialRotationQueueFactory({
+ queueService,
+ appConnectionCredentialRotationDAL,
+ appConnectionCredentialRotationService
+ });
+
const secretScanningV2Queue = secretScanningV2QueueServiceFactory({
auditLogService,
secretScanningV2DAL,
@@ -2916,7 +2938,8 @@ export const registerRoutes = async (
aiMcpServer: aiMcpServerService,
aiMcpEndpoint: aiMcpEndpointService,
aiMcpActivityLog: aiMcpActivityLogService,
- approvalPolicy: approvalPolicyService
+ approvalPolicy: approvalPolicyService,
+ appConnectionCredentialRotation: appConnectionCredentialRotationService
});
const cronJobs: CronJob[] = [];
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
index 7cd3f30127..258b73ff55 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
@@ -8,6 +8,7 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";
import { TAppConnection, TAppConnectionInput } from "@app/services/app-connection/app-connection-types";
+import { TCreateAppConnectionCredentialRotationSchema } from "@app/services/app-connection/credential-rotation/app-connection-credential-rotation-types";
import { AuthMode } from "@app/services/auth/auth-type";
export const registerAppConnectionEndpoints = <T extends TAppConnection, I extends TAppConnectionInput>({
@@ -25,8 +26,10 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
credentials: I["credentials"];
description?: string | null;
isPlatformManagedCredentials?: boolean;
+ isAutoRotationEnabled?: boolean;
gatewayId?: string | null;
projectId?: string;
+ rotation?: TCreateAppConnectionCredentialRotationSchema;
}>;
updateSchema: z.ZodType<{
name?: string;
@@ -272,10 +275,31 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const { name, method, credentials, description, isPlatformManagedCredentials, gatewayId, projectId } = req.body;
+ const {
+ name,
+ method,
+ credentials,
+ description,
+ isPlatformManagedCredentials,
+ gatewayId,
+ projectId,
+ isAutoRotationEnabled,
+ rotation
+ } = req.body;
const appConnection = (await server.services.appConnection.createAppConnection(
- { name, method, app, credentials, description, isPlatformManagedCredentials, gatewayId, projectId },
+ {
+ name,
+ method,
+ app,
+ credentials,
+ description,
+ isPlatformManagedCredentials,
+ gatewayId,
+ projectId,
+ rotation,
+ isAutoRotationEnabled
+ },
req.permission
)) as T;
diff --git a/backend/src/services/app-connection/app-connection-schemas.ts b/backend/src/services/app-connection/app-connection-schemas.ts
index 3f6e3914a7..3053ae9d34 100644
--- a/backend/src/services/app-connection/app-connection-schemas.ts
+++ b/backend/src/services/app-connection/app-connection-schemas.ts
@@ -7,6 +7,7 @@ import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connec
import { TAppConnectionBaseConfig } from "@app/services/app-connection/app-connection-types";
import { AppConnection } from "./app-connection-enums";
+import { CreateAppConnectionCredentialRotationSchema } from "./credential-rotation/app-connection-credential-rotation-schemas";
export const BaseAppConnectionSchema = AppConnectionsSchema.omit({
encryptedCredentials: true,
@@ -26,32 +27,62 @@ export const BaseAppConnectionSchema = AppConnectionsSchema.omit({
export const GenericCreateAppConnectionFieldsSchema = (
app: AppConnection,
- { supportsPlatformManagedCredentials = false, supportsGateways = false }: TAppConnectionBaseConfig = {}
+ {
+ supportsPlatformManagedCredentials = false,
+ supportsGateways = false,
+ supportsCredentialRotation = false
+ }: TAppConnectionBaseConfig = {}
) =>
- z.object({
- name: slugSchema({ field: "name" }).describe(AppConnections.CREATE(app).name),
- description: z
- .string()
- .trim()
- .max(256, "Description cannot exceed 256 characters")
- .nullish()
- .describe(AppConnections.CREATE(app).description),
- projectId: z.string().optional().describe(AppConnections.CREATE(app).projectId),
- isPlatformManagedCredentials: supportsPlatformManagedCredentials
- ? z.boolean().optional().default(false).describe(AppConnections.CREATE(app).isPlatformManagedCredentials)
- : z
- .literal(false, {
- errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })
- })
- .optional()
- .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),
- gatewayId: supportsGateways
- ? z.string().uuid().nullish().describe("The Gateway ID to use for this connection.")
- : 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` }))
- .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`)
- });
+ z
+ .object({
+ name: slugSchema({ field: "name" }).describe(AppConnections.CREATE(app).name),
+ description: z
+ .string()
+ .trim()
+ .max(256, "Description cannot exceed 256 characters")
+ .nullish()
+ .describe(AppConnections.CREATE(app).description),
+ projectId: z.string().optional().describe(AppConnections.CREATE(app).projectId),
+ isPlatformManagedCredentials: supportsPlatformManagedCredentials
+ ? z.boolean().optional().default(false).describe(AppConnections.CREATE(app).isPlatformManagedCredentials)
+ : z
+ .literal(false, {
+ errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })
+ })
+ .optional()
+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),
+ gatewayId: supportsGateways
+ ? z.string().uuid().nullish().describe("The Gateway ID to use for this connection.")
+ : 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` }))
+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),
+
+ isAutoRotationEnabled: supportsCredentialRotation
+ ? z.boolean().optional()
+ : z
+ .literal(false, {
+ errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })
+ })
+ .optional()
+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),
+
+ rotation: supportsCredentialRotation
+ ? CreateAppConnectionCredentialRotationSchema.optional()
+ : 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` }))
+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`)
+ })
+ .superRefine((data, ctx) => {
+ if (data.isAutoRotationEnabled && !data.rotation) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Rotation details is required when auto rotation is enabled",
+ path: ["rotation"]
+ });
+ }
+ });
export const GenericUpdateAppConnectionFieldsSchema = (
app: AppConnection,
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 8369521409..969a0e1b36 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -73,6 +73,7 @@ import { ValidateCircleCIConnectionCredentialsSchema } from "./circleci";
import { circleciConnectionService } from "./circleci/circleci-connection-service";
import { ValidateCloudflareConnectionCredentialsSchema } from "./cloudflare/cloudflare-connection-schema";
import { cloudflareConnectionService } from "./cloudflare/cloudflare-connection-service";
+import { TAppConnectionCredentialRotationServiceFactory } from "./credential-rotation";
import { ValidateDatabricksConnectionCredentialsSchema } from "./databricks";
import { databricksConnectionService } from "./databricks/databricks-connection-service";
import { ValidateDbtConnectionCredentialsSchema } from "./dbt";
@@ -143,6 +144,7 @@ export type TAppConnectionServiceFactoryDep = {
gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
projectDAL: Pick<TProjectDALFactory, "findProjectById">;
+ appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;
};
export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;
@@ -209,7 +211,8 @@ export const appConnectionServiceFactory = ({
gatewayV2Service,
gatewayDAL,
gatewayV2DAL,
- projectDAL
+ projectDAL,
+ appConnectionCredentialRotationService
}: TAppConnectionServiceFactoryDep) => {
const listAppConnections = async (actor: OrgServiceActor, app?: AppConnection, projectId?: string) => {
let appConnections: TAppConnections[];
@@ -368,7 +371,16 @@ export const appConnectionServiceFactory = ({
};
const createAppConnection = async (
- { method, app, credentials, gatewayId, projectId, ...params }: TCreateAppConnectionDTO,
+ {
+ method,
+ app,
+ credentials,
+ gatewayId,
+ projectId,
+ rotation,
+ isAutoRotationEnabled,
+ ...params
+ }: TCreateAppConnectionDTO,
actor: OrgServiceActor
) => {
const { permission: orgPermission } = await permissionService.getOrgPermission({
@@ -449,21 +461,39 @@ export const appConnectionServiceFactory = ({
try {
const createConnection = async (connectionCredentials: TAppConnection["credentials"]) => {
- const encryptedCredentials = await encryptAppConnectionCredentials({
- credentials: connectionCredentials,
- orgId: actor.orgId,
- kmsService,
- projectId
- });
+ return appConnectionDAL.transaction(async (tx) => {
+ const encryptedCredentials = await encryptAppConnectionCredentials({
+ credentials: connectionCredentials,
+ orgId: actor.orgId,
+ kmsService,
+ projectId
+ });
- return appConnectionDAL.create({
- orgId: actor.orgId,
- encryptedCredentials,
- method,
- app,
- gatewayId,
- projectId,
- ...params
+ const appConnection = await appConnectionDAL.create(
+ {
+ orgId: actor.orgId,
+ encryptedCredentials,
+ method,
+ app,
+ gatewayId,
+ projectId,
+ isAutoRotationEnabled,
+ ...params
+ },
+ tx
+ );
+
+ if (isAutoRotationEnabled && rotation) {
+ await appConnectionCredentialRotationService.createRotation(
+ {
+ connectionId: appConnection.id,
+ ...rotation
+ },
+ tx
+ );
+ }
+
+ return appConnection;
});
};
diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.ts
index 9fb3c290e6..d43823b26b 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -412,7 +412,16 @@ export type TSqlConnectionInput =
export type TCreateAppConnectionDTO = Pick<
TAppConnectionInput,
- "credentials" | "method" | "name" | "app" | "description" | "isPlatformManagedCredentials" | "gatewayId" | "projectId"
+ | "credentials"
+ | "method"
+ | "name"
+ | "app"
+ | "description"
+ | "isPlatformManagedCredentials"
+ | "gatewayId"
+ | "projectId"
+ | "rotation"
+ | "isAutoRotationEnabled"
>;
export type TUpdateAppConnectionDTO = Partial<Omit<TCreateAppConnectionDTO, "method" | "app" | "projectId">> & {
@@ -566,5 +575,6 @@ export type TAppConnectionTransitionCredentialsToPlatform = (
export type TAppConnectionBaseConfig = {
supportsPlatformManagedCredentials?: boolean;
+ supportsCredentialRotation?: boolean;
supportsGateways?: boolean;
};
diff --git a/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts b/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts
index 7916ac92db..00515c49ad 100644
--- a/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts
+++ b/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts
@@ -113,6 +113,38 @@ export const getAzureClientSecretsConnectionListItem = () => {
};
};
+const getAzureConnectionApplicationObjectId = async (
+ connectionId: string,
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+) => {
+ const appConnection = await appConnectionDAL.findById(connectionId);
+ if (!appConnection) {
+ throw new NotFoundError({ message: `Connection with ID '${connectionId}' not found` });
+ }
+
+ if (appConnection.method !== AzureClientSecretsConnectionMethod.ClientSecret) {
+ return null;
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: appConnection.orgId,
+ kmsService,
+ projectId: appConnection.projectId,
+ encryptedCredentials: appConnection.encryptedCredentials
+ })) as TAzureClientSecretsConnectionClientSecretCredentials;
+
+ if (!credentials.applicationObjectId) {
+ // then we need to make an api call to get it
+ const { data } = await request.get<{ value: { appId: string }[] }>(
+ `https://graph.microsoft.com/v1.0/applications?$filter=appId eq '${credentials.clientId}'`
+ );
+ return data.value[0].appId;
+ }
+
+ return credentials.applicationObjectId;
+};
+
export const getAzureConnectionAccessToken = async (
connectionId: string,
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">,
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.ts
index 910244d9e9..e00fb0ec78 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
@@ -78,6 +78,7 @@ export const AzureClientSecretsConnectionClientSecretOutputCredentialsSchema = z
clientId: z.string(),
clientSecret: z.string(),
tenantId: z.string(),
+ applicationObjectId: z.string().optional(),
accessToken: z.string(),
expiresAt: z.number()
});
diff --git a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts
index 3c03237896..53eedff946 100644
--- a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts
+++ b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts
@@ -66,7 +66,7 @@ export const ValidateAzureKeyVaultConnectionCredentialsSchema = z.discriminatedU
]);
export const CreateAzureKeyVaultConnectionSchema = ValidateAzureKeyVaultConnectionCredentialsSchema.and(
- GenericCreateAppConnectionFieldsSchema(AppConnection.AzureKeyVault)
+ GenericCreateAppConnectionFieldsSchema(AppConnection.AzureKeyVault, { supportsCredentialRotation: true })
);
export const UpdateAzureKeyVaultConnectionSchema = z
diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-dal.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-dal.ts
new file mode 100644
index 0000000000..2a90f65cf4
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-dal.ts
@@ -0,0 +1,63 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+export type TAppConnectionCredentialRotationDALFactory = ReturnType<typeof appConnectionCredentialRotationDALFactory>;
+
+export const appConnectionCredentialRotationDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AppConnectionCredentialRotation);
+
+ const findByConnectionId = async (connectionId: string, tx?: Knex) => {
+ const rotation = await (tx || db.replicaNode())(TableName.AppConnectionCredentialRotation)
+ .where(`${TableName.AppConnectionCredentialRotation}.connectionId`, connectionId)
+ .first();
+
+ return rotation || null;
+ };
+
+ const findRotationsDueForQueue = async (rotateBy: Date, tx?: Knex) => {
+ const rotations = await (tx || db.replicaNode())(TableName.AppConnectionCredentialRotation)
+ .join(
+ TableName.AppConnection,
+ `${TableName.AppConnectionCredentialRotation}.connectionId`,
+ `${TableName.AppConnection}.id`
+ )
+ .where(`${TableName.AppConnection}.isAutoRotationEnabled`, true)
+ .where(`${TableName.AppConnectionCredentialRotation}.nextRotationAt`, "<=", rotateBy)
+ .select(selectAllTableCols(TableName.AppConnectionCredentialRotation))
+ .select(db.ref("orgId").withSchema(TableName.AppConnection));
+
+ return rotations;
+ };
+
+ const findByIdWithConnection = async (id: string, tx?: Knex) => {
+ const result = await (tx || db.replicaNode())(TableName.AppConnectionCredentialRotation)
+ .where(`${TableName.AppConnectionCredentialRotation}.id`, id)
+ .join(
+ TableName.AppConnection,
+ `${TableName.AppConnectionCredentialRotation}.connectionId`,
+ `${TableName.AppConnection}.id`
+ )
+ .select(
+ selectAllTableCols(TableName.AppConnectionCredentialRotation),
+ db.ref("orgId").withSchema(TableName.AppConnection),
+ db.ref("name").withSchema(TableName.AppConnection).as("connectionName"),
+ db.ref("app").withSchema(TableName.AppConnection).as("connectionApp"),
+ db.ref("method").withSchema(TableName.AppConnection).as("connectionMethod"),
+ db.ref("encryptedCredentials").withSchema(TableName.AppConnection).as("connectionEncryptedCredentials"),
+ db.ref("isAutoRotationEnabled").withSchema(TableName.AppConnection)
+ )
+ .first();
+
+ return result || null;
+ };
+
+ return {
+ ...orm,
+ findByConnectionId,
+ findRotationsDueForQueue,
+ findByIdWithConnection
+ };
+};
diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-enums.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-enums.ts
new file mode 100644
index 0000000000..bdbec0e302
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-enums.ts
@@ -0,0 +1,8 @@
+export enum AppConnectionCredentialRotationStrategy {
+ AzureClientSecret = "azure-client-secret"
+}
+
+export enum AppConnectionCredentialRotationStatus {
+ Success = "success",
+ Failed = "failed"
+}
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.ts
new file mode 100644
index 0000000000..a7ae55b8b8
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-fns.ts
@@ -0,0 +1,267 @@
+import { AxiosError } from "axios";
+
+import { getConfig } from "@app/lib/config/env";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+import { AppConnectionCredentialRotationStatus } from "./app-connection-credential-rotation-enums";
+import {
+ TAppConnectionCredentialRotation,
+ TAppConnectionCredentialRotationGeneratedCredentials,
+ TAppConnectionCredentialRotationRaw
+} from "./app-connection-credential-rotation-types";
+
+const getNextUTCDayInterval = ({ hours, minutes }: { hours: number; minutes: number } = { hours: 0, minutes: 0 }) => {
+ const now = new Date();
+
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, hours, minutes, 0, 0));
+};
+
+const getNextUTCMinuteInterval = ({ minutes }: { hours: number; minutes: number } = { hours: 0, minutes: 0 }) => {
+ const now = new Date();
+ return new Date(
+ Date.UTC(
+ now.getUTCFullYear(),
+ now.getUTCMonth(),
+ now.getUTCDate(),
+ now.getUTCHours(),
+ now.getUTCMinutes() + 1,
+ minutes,
+ 0
+ )
+ );
+};
+
+export const getNextUtcRotationInterval = (rotateAtUtc?: { hours: number; minutes: number }) => {
+ const appCfg = getConfig();
+
+ if (appCfg.isRotationDevelopmentMode) {
+ if (appCfg.isTestMode) {
+ return new Date(Date.now() + 365 * 24 * 60 * 60 * 1000);
+ }
+ return getNextUTCMinuteInterval(rotateAtUtc);
+ }
+
+ return getNextUTCDayInterval(rotateAtUtc);
+};
+
+export const calculateNextRotationAt = ({
+ rotateAtUtc,
+ isAutoRotationEnabled,
+ rotationInterval,
+ rotationStatus,
+ isManualRotation,
+ ...params
+}: {
+ isAutoRotationEnabled: boolean;
+ lastRotatedAt: Date;
+ rotateAtUtc: { hours: number; minutes: number };
+ rotationInterval: number;
+ rotationStatus: string;
+ isManualRotation: boolean;
+}) => {
+ if (!isAutoRotationEnabled) return null;
+
+ if (rotationStatus === AppConnectionCredentialRotationStatus.Failed) {
+ return getNextUtcRotationInterval(rotateAtUtc);
+ }
+
+ const lastRotatedAt = new Date(params.lastRotatedAt);
+ const appCfg = getConfig();
+
+ if (appCfg.isRotationDevelopmentMode) {
+ const nextRotation = new Date(lastRotatedAt.getTime() + rotationInterval * 60 * 1000);
+ nextRotation.setUTCSeconds(rotateAtUtc.minutes);
+ nextRotation.setUTCMilliseconds(0);
+
+ if (isManualRotation && lastRotatedAt.getUTCSeconds() >= rotateAtUtc.minutes) {
+ nextRotation.setUTCMinutes(nextRotation.getUTCMinutes() + 1);
+ }
+
+ return nextRotation;
+ }
+
+ const nextRotation = new Date(lastRotatedAt);
+ nextRotation.setUTCHours(rotateAtUtc.hours);
+ nextRotation.setUTCMinutes(rotateAtUtc.minutes);
+ nextRotation.setUTCSeconds(0);
+ nextRotation.setUTCMilliseconds(0);
+
+ if (
+ isManualRotation &&
+ (lastRotatedAt.getUTCHours() > rotateAtUtc.hours ||
+ (lastRotatedAt.getUTCHours() === rotateAtUtc.hours && lastRotatedAt.getUTCMinutes() >= rotateAtUtc.minutes))
+ ) {
+ nextRotation.setUTCDate(nextRotation.getUTCDate() + rotationInterval + 1);
+ } else {
+ nextRotation.setUTCDate(nextRotation.getUTCDate() + rotationInterval);
+ }
+
+ return nextRotation;
+};
+
+export const encryptCredentialRotationGeneratedCredentials = async ({
+ orgId,
+ generatedCredentials,
+ kmsService
+}: {
+ orgId: string;
+ generatedCredentials: TAppConnectionCredentialRotationGeneratedCredentials;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ const { cipherTextBlob } = encryptor({
+ plainText: Buffer.from(JSON.stringify(generatedCredentials))
+ });
+
+ return cipherTextBlob;
+};
+
+export const decryptCredentialRotationGeneratedCredentials = async ({
+ orgId,
+ encryptedGeneratedCredentials,
+ kmsService
+}: {
+ orgId: string;
+ encryptedGeneratedCredentials: Buffer;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ const decryptedPlainTextBlob = decryptor({
+ cipherTextBlob: encryptedGeneratedCredentials
+ });
+
+ return JSON.parse(decryptedPlainTextBlob.toString()) as TAppConnectionCredentialRotationGeneratedCredentials;
+};
+
+export const encryptStrategyConfig = async ({
+ orgId,
+ config,
+ kmsService
+}: {
+ orgId: string;
+ config: Record<string, unknown>;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ const { cipherTextBlob } = encryptor({
+ plainText: Buffer.from(JSON.stringify(config))
+ });
+
+ return cipherTextBlob;
+};
+
+export const decryptStrategyConfig = async <T>({
+ orgId,
+ encryptedStrategyConfig,
+ kmsService
+}: {
+ orgId: string;
+ encryptedStrategyConfig: Buffer;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ const decryptedPlainTextBlob = decryptor({
+ cipherTextBlob: encryptedStrategyConfig
+ });
+
+ return JSON.parse(decryptedPlainTextBlob.toString()) as T;
+};
+
+export const encryptRotationMessage = async ({
+ orgId,
+ message,
+ kmsService
+}: {
+ orgId: string;
+ message: string;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ const { cipherTextBlob } = encryptor({
+ plainText: Buffer.from(message)
+ });
+
+ return cipherTextBlob;
+};
+
+export const expandCredentialRotation = async (
+ { encryptedLastRotationMessage, ...rotation }: TAppConnectionCredentialRotationRaw,
+ orgId: string,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+): Promise<TAppConnectionCredentialRotation> => {
+ let lastRotationMessage: string | null = null;
+
+ if (encryptedLastRotationMessage) {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ lastRotationMessage = decryptor({
+ cipherTextBlob: encryptedLastRotationMessage
+ }).toString();
+ }
+
+ return {
+ ...rotation,
+ lastRotationMessage
+ };
+};
+
+const MAX_MESSAGE_LENGTH = 1024;
+
+export const parseRotationErrorMessage = (err: unknown): string => {
+ let errorMessage = "Infisical encountered an issue while rotating credentials: ";
+
+ if (err instanceof AxiosError) {
+ errorMessage += err?.response?.data
+ ? JSON.stringify(err?.response?.data)
+ : (err?.message ?? "An unknown error occurred.");
+ } else {
+ errorMessage += (err as Error)?.message || "An unknown error occurred.";
+ }
+
+ return errorMessage.length <= MAX_MESSAGE_LENGTH
+ ? errorMessage
+ : `${errorMessage.substring(0, MAX_MESSAGE_LENGTH - 3)}...`;
+};
+
+export const getCredentialRotationJobOptions = ({
+ id,
+ nextRotationAt
+}: Pick<TAppConnectionCredentialRotationRaw, "id" | "nextRotationAt">) => {
+ const appCfg = getConfig();
+
+ return {
+ jobId: `app-connection-credential-rotation-rotate-${id}`,
+ attempts: appCfg.isRotationDevelopmentMode ? 1 : 5,
+ removeOnFail: true,
+ removeOnComplete: true,
+ backoff: {
+ type: "exponential" as const,
+ delay: 1000
+ },
+ delay: nextRotationAt ? Number(nextRotationAt) - Date.now() : undefined
+ };
+};
diff --git a/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts
new file mode 100644
index 0000000000..1700f68ce6
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-queue.ts
@@ -0,0 +1,160 @@
+import { v4 as uuidv4 } from "uuid";
+
+import { getConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+
+import { TAppConnectionCredentialRotationDALFactory } from "./app-connection-credential-rotation-dal";
+import { getCredentialRotationJobOptions, getNextUtcRotationInterval } from "./app-connection-credential-rotation-fns";
+import { TAppConnectionCredentialRotationServiceFactory } from "./app-connection-credential-rotation-service";
+import {
+ TAppConnectionCredentialRotationRotateJobPayload,
+ TAppConnectionCredentialRotationSendNotificationJobPayload
+} from "./app-connection-credential-rotation-types";
+
+type TAppConnectionCredentialRotationQueueFactoryDep = {
+ queueService: TQueueServiceFactory;
+ appConnectionCredentialRotationDAL: Pick<
+ TAppConnectionCredentialRotationDALFactory,
+ "findRotationsDueForQueue" | "findByIdWithConnection"
+ >;
+ appConnectionCredentialRotationService: Pick<TAppConnectionCredentialRotationServiceFactory, "rotateCredentials">;
+};
+
+export const appConnectionCredentialRotationQueueFactory = async ({
+ queueService,
+ appConnectionCredentialRotationDAL,
+ appConnectionCredentialRotationService
+}: TAppConnectionCredentialRotationQueueFactoryDep) => {
+ const appCfg = getConfig();
+
+ if (appCfg.isRotationDevelopmentMode) {
+ logger.warn("App Connection Credential Rotation is in development mode.");
+ }
+
+ // Worker for individual rotation jobs
+ queueService.start(
+ QueueName.AppConnectionCredentialRotationRotate,
+ async (job) => {
+ const { rotationId, queuedAt, isManualRotation } = job.data;
+ const retryCount = job.attemptsMade;
+ const retryLimit = job.opts.attempts || 1;
+
+ const logDetails = `[rotationId=${rotationId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
+
+ try {
+ const rotation = await appConnectionCredentialRotationDAL.findByIdWithConnection(rotationId);
+
+ if (!rotation) {
+ logger.warn(`credentialRotationQueue: Rotation ${rotationId} not found, skipping`);
+ return;
+ }
+
+ if (!rotation.isAutoRotationEnabled && !isManualRotation) {
+ logger.info(`credentialRotationQueue: Skipping - Auto-Rotation Disabled ${logDetails}`);
+ return;
+ }
+
+ if (rotation.lastRotatedAt && new Date(rotation.lastRotatedAt).getTime() >= new Date(queuedAt).getTime()) {
+ logger.info(`credentialRotationQueue: Skipping - Rotated Since Queue ${logDetails}`);
+ return;
+ }
+
+ await appConnectionCredentialRotationService.rotateCredentials(rotationId, {
+ jobId: job.id || uuidv4(),
+ shouldSendNotification: true,
+ isFinalAttempt: retryCount === retryLimit,
+ isManualRotation
+ });
+
+ logger.info(`credentialRotationQueue: Credentials Rotated ${logDetails}`);
+ } catch (error) {
+ logger.error(error, `credentialRotationQueue: Failed to Rotate ${logDetails}`);
+ throw error;
+ }
+ },
+ {
+ persistence: true
+ }
+ );
+
+ // Worker for scheduling and notifications
+ queueService.start(QueueName.AppConnectionCredentialRotation, async (job) => {
+ if (job.name === QueueJobs.AppConnectionCredentialRotationQueueRotations) {
+ try {
+ const rotateBy = getNextUtcRotationInterval();
+ const currentTime = new Date();
+
+ const rotations = await appConnectionCredentialRotationDAL.findRotationsDueForQueue(rotateBy);
+
+ logger.info(
+ `credentialRotationQueue: Queue Rotations [currentTime=${currentTime.toISOString()}] [rotateBy=${rotateBy.toISOString()}] [count=${rotations.length}]`
+ );
+
+ for await (const rotation of rotations) {
+ logger.info(
+ `credentialRotationQueue: Queue Rotation [rotationId=${rotation.id}] [nextRotationAt=${
+ rotation.nextRotationAt ? new Date(rotation.nextRotationAt).toISOString() : "null"
+ }]`
+ );
+
+ const data: TAppConnectionCredentialRotationRotateJobPayload = {
+ rotationId: rotation.id,
+ connectionId: rotation.connectionId,
+ queuedAt: currentTime
+ };
+
+ if (appCfg.isTestMode) {
+ logger.warn("credentialRotationQueue: Manually rotating for test mode");
+ await appConnectionCredentialRotationService.rotateCredentials(rotation.id, {
+ jobId: uuidv4(),
+ shouldSendNotification: true,
+ isFinalAttempt: true,
+ isManualRotation: false
+ });
+ } else {
+ await queueService.queue(
+ QueueName.AppConnectionCredentialRotationRotate,
+ QueueJobs.AppConnectionCredentialRotationRotate,
+ data,
+ getCredentialRotationJobOptions(rotation)
+ );
+ }
+ }
+ } catch (error) {
+ logger.error(error, "credentialRotationQueue: Queue Rotations Error:");
+ throw error;
+ }
+ } else if (job.name === QueueJobs.AppConnectionCredentialRotationSendNotification) {
+ const payload = job.data as TAppConnectionCredentialRotationSendNotificationJobPayload;
+ try {
+ logger.info(`credentialRotationQueue: Sending Failure Notification [connectionId=${payload.connectionId}]`);
+
+ // Notification sending can be expanded later with email + in-app notifications
+ logger.warn(
+ `credentialRotationQueue: Credential rotation failed for connection "${payload.connectionName}" (strategy: ${payload.strategy}). Last attempt: ${payload.lastRotationAttemptedAt.toISOString()}`
+ );
+ } catch (error) {
+ logger.error(
+ error,
+ `credentialRotationQueue: Failed to Send Notification [connectionId=${payload.connectionId}]`
+ );
+ throw error;
+ }
+ }
+ });
+
+ // Schedule the cron job
+ await queueService.queue(
+ QueueName.AppConnectionCredentialRotation,
+ QueueJobs.AppConnectionCredentialRotationQueueRotations,
+ undefined,
+ {
+ jobId: "app-connection-credential-rotation-cron",
+ repeat: {
+ pattern: appCfg.isRotationDevelopmentMode ? "* * * * *" : "0 0 * * *",
+ key: "app-connection-credential-rotation-cron"
+ }
+ }
+ );
+};
diff --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.ts
new file mode 100644
index 0000000000..800b5e2e17
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-schemas.ts
@@ -0,0 +1,42 @@
+import { z } from "zod";
+
+import { AppConnectionCredentialRotationStatus } from "./app-connection-credential-rotation-enums";
+
+export const CreateAppConnectionCredentialRotationSchema = z.object({
+ rotationInterval: z.number().int().min(1).max(365),
+ rotateAtUtc: z.object({
+ hours: z.number().int().min(0).max(23),
+ minutes: z.number().int().min(0).max(59)
+ })
+});
+
+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()
+});
+
+export const SanitizedAppConnectionCredentialRotationSchema = z.object({
+ id: z.string().uuid(),
+ connectionId: z.string().uuid(),
+ strategy: z.string(),
+ rotationInterval: z.number(),
+ rotateAtUtc: z.object({
+ hours: z.number(),
+ minutes: z.number()
+ }),
+ rotationStatus: z.nativeEnum(AppConnectionCredentialRotationStatus),
+ lastRotationAttemptedAt: z.date().nullable(),
+ lastRotatedAt: z.date().nullable(),
+ lastRotationMessage: z.string().nullable(),
+ lastRotationJobId: z.string().nullable(),
+ nextRotationAt: z.date().nullable(),
+ activeIndex: z.number(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
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.ts
new file mode 100644
index 0000000000..c30347f30e
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-service.ts
@@ -0,0 +1,533 @@
+import { Knex } from "knex";
+
+import { TKeyStoreFactory } from "@app/keystore/keystore";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { TQueueServiceFactory } from "@app/queue";
+import { QueueJobs, QueueName } from "@app/queue/queue-service";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ decryptAppConnectionCredentials,
+ encryptAppConnectionCredentials
+} from "@app/services/app-connection/app-connection-fns";
+import { AzureKeyVaultConnectionMethod } from "@app/services/app-connection/azure-key-vault/azure-key-vault-connection-enums";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TAppConnection } from "../app-connection-types";
+import { TAppConnectionCredentialRotationDALFactory } from "./app-connection-credential-rotation-dal";
+import {
+ AppConnectionCredentialRotationStatus,
+ AppConnectionCredentialRotationStrategy
+} from "./app-connection-credential-rotation-enums";
+import {
+ calculateNextRotationAt,
+ decryptCredentialRotationGeneratedCredentials,
+ decryptStrategyConfig,
+ encryptCredentialRotationGeneratedCredentials,
+ encryptRotationMessage,
+ encryptStrategyConfig,
+ expandCredentialRotation,
+ parseRotationErrorMessage
+} from "./app-connection-credential-rotation-fns";
+import {
+ TAppConnectionCredentialRotationGeneratedCredentials,
+ TAzureClientSecretStrategyConfig,
+ TCreateAppConnectionCredentialRotationDTO,
+ TTriggerAppConnectionCredentialRotationDTO,
+ TUpdateAppConnectionCredentialRotationDTO
+} from "./app-connection-credential-rotation-types";
+import {
+ createAzureClientSecret,
+ getApplicationObjectId,
+ listAzurePasswordCredentials,
+ revokeAzureClientSecret,
+ validateAzureClientSecretRotationConfig
+} from "./providers/azure-client-secret-credential-rotation";
+
+const MAX_GENERATED_CREDENTIALS_LENGTH = 2;
+
+const STRATEGY_MAP: Record<string, AppConnectionCredentialRotationStrategy> = {
+ [AppConnection.AzureKeyVault]: AppConnectionCredentialRotationStrategy.AzureClientSecret
+};
+
+export type TAppConnectionCredentialRotationServiceFactoryDep = {
+ appConnectionCredentialRotationDAL: TAppConnectionCredentialRotationDALFactory;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
+ queueService: TQueueServiceFactory;
+};
+
+export type TAppConnectionCredentialRotationServiceFactory = ReturnType<
+ typeof appConnectionCredentialRotationServiceFactory
+>;
+
+export const appConnectionCredentialRotationServiceFactory = ({
+ appConnectionCredentialRotationDAL,
+ appConnectionDAL,
+ kmsService,
+ keyStore,
+ queueService
+}: TAppConnectionCredentialRotationServiceFactoryDep) => {
+ /**
+ * Decrypt connection credentials and extract clientId, clientSecret, tenantId.
+ */
+ const getConnectionClientCredentials = async (connection: {
+ orgId: string;
+ encryptedCredentials: Buffer;
+ projectId?: string | null;
+ }) => {
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: connection.orgId,
+ encryptedCredentials: connection.encryptedCredentials,
+ kmsService,
+ projectId: connection.projectId
+ })) as { clientId: string; clientSecret: string; tenantId: string; applicationObjectId?: string };
+
+ return credentials;
+ };
+
+ /**
+ * Update the connection's stored credentials with a new client secret and optionally save applicationObjectId.
+ */
+ const updateConnectionCredentials = async (
+ connectionId: string,
+ newClientSecret: string,
+ applicationObjectId?: string,
+ tx?: Knex
+ ) => {
+ const connection = await appConnectionDAL.findById(connectionId, tx);
+ if (!connection) throw new NotFoundError({ message: `Connection ${connectionId} not found` });
+
+ const credentials = await getConnectionClientCredentials(connection);
+
+ const updatedCredentials = {
+ ...credentials,
+ clientSecret: newClientSecret,
+ ...(applicationObjectId && { applicationObjectId })
+ } as TAppConnection["credentials"];
+
+ const encryptedCredentials = await encryptAppConnectionCredentials({
+ orgId: connection.orgId,
+ credentials: updatedCredentials,
+ kmsService,
+ projectId: connection.projectId
+ });
+
+ await appConnectionDAL.updateById(
+ connectionId,
+ {
+ encryptedCredentials
+ },
+ tx
+ );
+ };
+
+ /**
+ * Create credential rotation for a connection.
+ * Permission checks are handled by the caller (app-connection-endpoints).
+ */
+ const createRotation = async (dto: TCreateAppConnectionCredentialRotationDTO, tx?: Knex) => {
+ const { connectionId, rotationInterval, rotateAtUtc } = dto;
+
+ const connection = await appConnectionDAL.findById(connectionId, tx);
+ if (!connection) throw new NotFoundError({ message: `Connection ${connectionId} not found` });
+
+ // Validate connection type supports rotation
+ if (connection.app !== AppConnection.AzureKeyVault) {
+ throw new BadRequestError({ message: "Credential rotation is only supported for Azure Key Vault connections" });
+ }
+
+ if (connection.method !== AzureKeyVaultConnectionMethod.ClientSecret) {
+ throw new BadRequestError({
+ message: "Credential rotation is only supported for Client Secret auth method"
+ });
+ }
+
+ // Auto-infer strategy from connection type
+ const strategy = STRATEGY_MAP[connection.app];
+ if (!strategy) {
+ throw new BadRequestError({ message: `No rotation strategy available for ${connection.app} connections` });
+ }
+
+ // Check if rotation config already exists
+ const existingRotation = await appConnectionCredentialRotationDAL.findByConnectionId(connectionId, tx);
+ if (existingRotation) {
+ throw new BadRequestError({ message: "Credential rotation is already configured for this connection" });
+ }
+
+ // Get the connection's own credentials for self-rotation
+ const credentials = await getConnectionClientCredentials(connection);
+
+ // Auto-detect applicationObjectId if not already stored
+ let { applicationObjectId } = credentials;
+ if (!applicationObjectId) {
+ applicationObjectId = await getApplicationObjectId(credentials);
+ }
+
+ const strategyConfig: TAzureClientSecretStrategyConfig = { objectId: applicationObjectId };
+
+ // Validate strategy config (check objectId is accessible via Graph API)
+ await validateAzureClientSecretRotationConfig(strategyConfig, credentials);
+
+ // List existing password credentials before creating a new one, so we can track the original
+ const existingCredentials = await listAzurePasswordCredentials(strategyConfig, credentials);
+
+ // Perform initial credential issuance
+ const newCredential = await createAzureClientSecret(strategyConfig, credentials, rotationInterval, 0);
+
+ // Update the connection to use the new credential and save applicationObjectId
+ await updateConnectionCredentials(connectionId, newCredential.clientSecret, applicationObjectId, tx);
+
+ // Track the original credential at index 1 so it gets revoked on the first rotation cycle.
+ // This maintains the dual-credential pattern: two active secrets at all times for zero downtime.
+ const originalCredential = existingCredentials.find((cred) => cred.keyId !== newCredential.keyId);
+ const generatedCredentials: TAppConnectionCredentialRotationGeneratedCredentials = [
+ newCredential,
+ originalCredential
+ ? { keyId: originalCredential.keyId, clientSecret: credentials.clientSecret, createdAt: "" }
+ : null
+ ];
+
+ const now = new Date();
+
+ const encryptedGeneratedCreds = await encryptCredentialRotationGeneratedCredentials({
+ orgId: connection.orgId,
+ generatedCredentials,
+ kmsService
+ });
+
+ const encryptedConfig = await encryptStrategyConfig({
+ orgId: connection.orgId,
+ config: strategyConfig,
+ kmsService
+ });
+
+ const nextRotationAt = calculateNextRotationAt({
+ rotateAtUtc,
+ isAutoRotationEnabled: true,
+ rotationInterval,
+ rotationStatus: AppConnectionCredentialRotationStatus.Success,
+ isManualRotation: true,
+ lastRotatedAt: now
+ });
+
+ const create = async (trx: Knex) => {
+ return appConnectionCredentialRotationDAL.create(
+ {
+ connectionId,
+ strategy,
+ encryptedStrategyConfig: encryptedConfig,
+ rotationInterval,
+ rotateAtUtc: JSON.stringify(rotateAtUtc),
+ rotationStatus: AppConnectionCredentialRotationStatus.Success,
+ lastRotatedAt: now,
+ lastRotationAttemptedAt: now,
+ nextRotationAt,
+ activeIndex: 0,
+ encryptedGeneratedCredentials: encryptedGeneratedCreds
+ },
+ trx
+ );
+ };
+
+ const rotation = tx ? await create(tx) : await appConnectionDAL.transaction(create);
+
+ return expandCredentialRotation(rotation, connection.orgId, kmsService);
+ };
+
+ /**
+ * Update credential rotation config for a connection.
+ * Permission checks are handled by the caller.
+ */
+ const updateRotation = async (dto: TUpdateAppConnectionCredentialRotationDTO, tx?: Knex) => {
+ const { connectionId, rotationInterval, rotateAtUtc, isAutoRotationEnabled } = dto;
+
+ const connection = await appConnectionDAL.findById(connectionId, tx);
+ if (!connection) throw new NotFoundError({ message: `Connection ${connectionId} not found` });
+
+ const existingRotation = await appConnectionCredentialRotationDAL.findByConnectionId(connectionId, tx);
+ if (!existingRotation) {
+ 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 (isAutoRotationEnabled === false) {
+ if (tx) {
+ await update(tx);
+ } else {
+ await appConnectionDAL.transaction(update);
+ }
+
+ return null;
+ }
+
+ // Build update payload
+ const updateData: Record<string, unknown> = {};
+
+ if (rotationInterval !== undefined) {
+ updateData.rotationInterval = rotationInterval;
+ }
+
+ if (rotateAtUtc !== undefined) {
+ updateData.rotateAtUtc = JSON.stringify(rotateAtUtc);
+ }
+
+ // Recalculate nextRotationAt if schedule changed
+ if (rotationInterval !== undefined || rotateAtUtc !== undefined) {
+ const resolvedRotateAtUtc = rotateAtUtc || (existingRotation.rotateAtUtc as { hours: number; minutes: number });
+ const resolvedInterval = rotationInterval ?? existingRotation.rotationInterval;
+
+ if (existingRotation.lastRotatedAt) {
+ updateData.nextRotationAt = calculateNextRotationAt({
+ rotateAtUtc: resolvedRotateAtUtc,
+ isAutoRotationEnabled: true,
+ rotationInterval: resolvedInterval,
+ rotationStatus: existingRotation.rotationStatus,
+ isManualRotation: false,
+ lastRotatedAt: existingRotation.lastRotatedAt
+ });
+ }
+ }
+
+ if (isAutoRotationEnabled !== undefined) {
+ await appConnectionDAL.updateById(connectionId, { isAutoRotationEnabled }, tx);
+ }
+
+ const updated = await appConnectionCredentialRotationDAL.updateById(existingRotation.id, updateData, tx);
+ return expandCredentialRotation(updated, connection.orgId, kmsService);
+ };
+
+ /**
+ * Get credential rotation config for a connection.
+ * Permission checks are handled by the caller.
+ */
+ const getRotationByConnectionId = async (connectionId: string, tx?: Knex) => {
+ const connection = await appConnectionDAL.findById(connectionId, tx);
+ if (!connection) throw new NotFoundError({ message: `Connection ${connectionId} not found` });
+
+ const rotation = await appConnectionCredentialRotationDAL.findByConnectionId(connectionId, tx);
+ if (!rotation) return null;
+
+ return expandCredentialRotation(rotation, connection.orgId, kmsService);
+ };
+
+ /**
+ * Trigger a manual credential rotation.
+ * Permission checks are handled by the caller.
+ */
+ const triggerRotation = async (dto: TTriggerAppConnectionCredentialRotationDTO, tx?: Knex) => {
+ const { connectionId } = dto;
+
+ const connection = await appConnectionDAL.findById(connectionId, tx);
+ if (!connection) throw new NotFoundError({ message: `Connection ${connectionId} not found` });
+
+ const rotation = await appConnectionCredentialRotationDAL.findByConnectionId(connectionId, tx);
+ if (!rotation) {
+ throw new NotFoundError({ message: "Credential rotation is not configured for this connection" });
+ }
+
+ await queueService.queue(
+ QueueName.AppConnectionCredentialRotationRotate,
+ QueueJobs.AppConnectionCredentialRotationRotate,
+ {
+ rotationId: rotation.id,
+ connectionId,
+ queuedAt: new Date(),
+ isManualRotation: true
+ },
+ {
+ jobId: `app-connection-credential-rotation-manual-${rotation.id}-${Date.now()}`,
+ removeOnFail: true,
+ removeOnComplete: true
+ }
+ );
+
+ return expandCredentialRotation(rotation, connection.orgId, kmsService);
+ };
+
+ /**
+ * Core rotation logic — called by the queue worker.
+ * Uses two-credential self-rotation pattern.
+ */
+ const rotateCredentials = async (
+ rotationId: string,
+ options: {
+ jobId: string;
+ shouldSendNotification: boolean;
+ isFinalAttempt: boolean;
+ isManualRotation?: boolean;
+ }
+ ) => {
+ const rotationWithConnection = await appConnectionCredentialRotationDAL.findByIdWithConnection(rotationId);
+ if (!rotationWithConnection) throw new NotFoundError({ message: `Rotation ${rotationId} not found` });
+
+ const {
+ connectionId,
+ strategy,
+ encryptedStrategyConfig: encryptedConfig,
+ encryptedGeneratedCredentials: encryptedGenCreds,
+ activeIndex,
+ rotationInterval,
+ connectionName,
+ orgId,
+ isAutoRotationEnabled
+ } = rotationWithConnection;
+
+ const now = new Date();
+ const rotateAtUtc = rotationWithConnection.rotateAtUtc as { hours: number; minutes: number };
+
+ try {
+ // Acquire lock to prevent concurrent rotations
+ const lockKey = `credential-rotation-lock-${rotationId}`;
+ const lock = await keyStore.acquireLock([lockKey], 60_000);
+
+ try {
+ // Decrypt connection credentials (for Graph API self-rotation)
+ const connection = await appConnectionDAL.findById(connectionId);
+ if (!connection) throw new Error(`Connection ${connectionId} not found`);
+
+ const credentials = await getConnectionClientCredentials(connection);
+
+ // Decrypt strategy config and generated credentials
+ const config = await decryptStrategyConfig<TAzureClientSecretStrategyConfig>({
+ orgId,
+ encryptedStrategyConfig: encryptedConfig,
+ kmsService
+ });
+
+ const generatedCredentials = await decryptCredentialRotationGeneratedCredentials({
+ orgId,
+ encryptedGeneratedCredentials: encryptedGenCreds,
+ kmsService
+ });
+
+ // Two-credential rotation: create-first, revoke-after.
+ // This ordering ensures that if create fails, we still have 2 valid secrets.
+ const inactiveIndex = (activeIndex + 1) % MAX_GENERATED_CREDENTIALS_LENGTH;
+ const inactiveCredential = generatedCredentials[inactiveIndex];
+
+ // Step 1: Create new credential first (safe — worst case we have 3 secrets temporarily)
+ const newCredential = await createAzureClientSecret(config, credentials, rotationInterval, inactiveIndex);
+
+ // Step 2: Update connection credentials with new secret
+ await updateConnectionCredentials(connectionId, newCredential.clientSecret);
+
+ // Step 3: Revoke old credential at inactive index (best-effort, non-fatal)
+ // If this fails, we have 3 secrets on Azure temporarily — they'll be cleaned up on the next cycle.
+ if (inactiveCredential?.keyId) {
+ try {
+ logger.info(
+ `credentialRotation: Revoking old credential keyId=${inactiveCredential.keyId} at index=${inactiveIndex} [rotationId=${rotationId}]`
+ );
+ await revokeAzureClientSecret(inactiveCredential.keyId, config, credentials);
+ } 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 index
+ const updatedGeneratedCredentials = [...generatedCredentials];
+ updatedGeneratedCredentials[inactiveIndex] = newCredential;
+
+ const encryptedUpdatedGenCreds = await encryptCredentialRotationGeneratedCredentials({
+ orgId,
+ generatedCredentials: updatedGeneratedCredentials,
+ kmsService
+ });
+
+ const nextRotationAt = calculateNextRotationAt({
+ rotateAtUtc,
+ isAutoRotationEnabled,
+ rotationInterval,
+ rotationStatus: AppConnectionCredentialRotationStatus.Success,
+ isManualRotation: options.isManualRotation ?? false,
+ lastRotatedAt: now
+ });
+
+ await appConnectionCredentialRotationDAL.updateById(rotationId, {
+ activeIndex: inactiveIndex,
+ encryptedGeneratedCredentials: encryptedUpdatedGenCreds,
+ rotationStatus: AppConnectionCredentialRotationStatus.Success,
+ lastRotatedAt: now,
+ lastRotationAttemptedAt: now,
+ lastRotationJobId: options.jobId,
+ nextRotationAt,
+ encryptedLastRotationMessage: null
+ });
+
+ logger.info(
+ `credentialRotation: Successfully rotated [rotationId=${rotationId}] [connectionId=${connectionId}]`
+ );
+ } finally {
+ await lock.release();
+ }
+ } catch (error) {
+ logger.error(error, `credentialRotation: Failed to rotate [rotationId=${rotationId}]`);
+
+ const errorMessage = parseRotationErrorMessage(error);
+ const encryptedMessage = await encryptRotationMessage({
+ orgId,
+ message: errorMessage,
+ kmsService
+ });
+
+ const nextRotationAt = calculateNextRotationAt({
+ rotateAtUtc,
+ isAutoRotationEnabled,
+ rotationInterval,
+ rotationStatus: AppConnectionCredentialRotationStatus.Failed,
+ isManualRotation: options.isManualRotation ?? false,
+ lastRotatedAt: now
+ });
+
+ await appConnectionCredentialRotationDAL.updateById(rotationId, {
+ rotationStatus: AppConnectionCredentialRotationStatus.Failed,
+ lastRotationAttemptedAt: now,
+ lastRotationJobId: options.jobId,
+ encryptedLastRotationMessage: encryptedMessage,
+ nextRotationAt
+ });
+
+ if (options.shouldSendNotification && options.isFinalAttempt) {
+ await queueService.queue(
+ QueueName.AppConnectionCredentialRotation,
+ QueueJobs.AppConnectionCredentialRotationSendNotification,
+ {
+ connectionId,
+ connectionName,
+ orgId,
+ strategy,
+ lastRotationAttemptedAt: now
+ },
+ {
+ jobId: `app-connection-credential-rotation-notification-${rotationId}-${Date.now()}`,
+ removeOnFail: true,
+ removeOnComplete: true
+ }
+ );
+ }
+
+ throw error;
+ }
+ };
+
+ return {
+ createRotation,
+ updateRotation,
+ getRotationByConnectionId,
+ triggerRotation,
+ rotateCredentials
+ };
+};
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.ts
new file mode 100644
index 0000000000..59135146d9
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/app-connection-credential-rotation-types.ts
@@ -0,0 +1,65 @@
+import { z } from "zod";
+
+import { TAppConnectionCredentialRotations } from "../../../db/schemas/app-connection-credential-rotations";
+import { CreateAppConnectionCredentialRotationSchema } from "./app-connection-credential-rotation-schemas";
+
+export type TAppConnectionCredentialRotationRaw = TAppConnectionCredentialRotations;
+
+export type TAppConnectionCredentialRotation = Omit<
+ TAppConnectionCredentialRotationRaw,
+ "encryptedLastRotationMessage"
+> & {
+ lastRotationMessage: string | null;
+};
+
+export type TCreateAppConnectionCredentialRotationSchema = z.infer<typeof CreateAppConnectionCredentialRotationSchema>;
+
+// Strategy config types
+export type TAzureClientSecretStrategyConfig = {
+ objectId: string;
+};
+
+export type TAppConnectionCredentialRotationStrategyConfig = TAzureClientSecretStrategyConfig;
+
+// Generated credentials types
+export type TAzureClientSecretGeneratedCredential = {
+ keyId: string;
+ clientSecret: string;
+ createdAt: string;
+};
+
+export type TAppConnectionCredentialRotationGeneratedCredentials = (TAzureClientSecretGeneratedCredential | null)[];
+
+// DTOs
+export type TCreateAppConnectionCredentialRotationDTO = {
+ connectionId: string;
+ rotationInterval: number;
+ rotateAtUtc: { hours: number; minutes: number };
+};
+
+export type TUpdateAppConnectionCredentialRotationDTO = {
+ connectionId: string;
+ rotationInterval?: number;
+ rotateAtUtc?: { hours: number; minutes: number };
+ isAutoRotationEnabled?: boolean;
+};
+
+export type TTriggerAppConnectionCredentialRotationDTO = {
+ connectionId: string;
+};
+
+// Queue payloads
+export type TAppConnectionCredentialRotationRotateJobPayload = {
+ rotationId: string;
+ connectionId: string;
+ queuedAt: Date;
+ isManualRotation?: boolean;
+};
+
+export type TAppConnectionCredentialRotationSendNotificationJobPayload = {
+ connectionId: string;
+ connectionName: string;
+ orgId: string;
+ strategy: string;
+ lastRotationAttemptedAt: Date;
+};
diff --git a/backend/src/services/app-connection/credential-rotation/index.ts b/backend/src/services/app-connection/credential-rotation/index.ts
new file mode 100644
index 0000000000..47a4d5ee2f
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/index.ts
@@ -0,0 +1,13 @@
+export { appConnectionCredentialRotationDALFactory } from "./app-connection-credential-rotation-dal";
+export type { TAppConnectionCredentialRotationDALFactory } from "./app-connection-credential-rotation-dal";
+export { AppConnectionCredentialRotationStrategy, AppConnectionCredentialRotationStatus } from "./app-connection-credential-rotation-enums";
+export { appConnectionCredentialRotationServiceFactory } from "./app-connection-credential-rotation-service";
+export type {
+ TAppConnectionCredentialRotationServiceFactory,
+ TAppConnectionCredentialRotationServiceFactoryDep
+} from "./app-connection-credential-rotation-service";
+export { appConnectionCredentialRotationQueueFactory } from "./app-connection-credential-rotation-queue";
+export type {
+ TAppConnectionCredentialRotationRotateJobPayload,
+ TAppConnectionCredentialRotationSendNotificationJobPayload
+} from "./app-connection-credential-rotation-types";
diff --git a/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret-credential-rotation.ts b/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret-credential-rotation.ts
new file mode 100644
index 0000000000..2b16b7f29d
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/providers/azure-client-secret-credential-rotation.ts
@@ -0,0 +1,335 @@
+/* eslint-disable no-await-in-loop */
+import { AxiosError } from "axios";
+
+import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+
+import {
+ TAzureClientSecretGeneratedCredential,
+ TAzureClientSecretStrategyConfig
+} from "../app-connection-credential-rotation-types";
+
+const GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
+const EXPIRY_PADDING_IN_DAYS = 3;
+
+type AzureAddPasswordResponse = {
+ keyId: string;
+ secretText: string;
+ displayName: string;
+ endDateTime: string;
+};
+
+type AzureErrorResponse = { error: { message: string } };
+
+const sleep = (ms: number) =>
+ new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+
+/**
+ * Gets a Graph API access token using the connection's own credentials (client credentials grant).
+ * This token is ephemeral and NOT stored in the connection's accessToken field.
+ */
+const GRAPH_TOKEN_MAX_RETRIES = 3;
+const GRAPH_TOKEN_RETRY_DELAY_MS = 2000;
+
+const isInvalidClientSecretError = (error: unknown): boolean => {
+ if (!(error instanceof AxiosError)) return false;
+ const desc = (error.response?.data as { error_description?: string })?.error_description || "";
+ return desc.includes("AADSTS7000215");
+};
+
+export const getGraphApiToken = async (
+ credentials: {
+ clientId: string;
+ clientSecret: string;
+ tenantId: string;
+ },
+ attempt = 0
+): Promise<string> => {
+ const { clientId, clientSecret, tenantId } = credentials;
+
+ const tokenUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
+
+ try {
+ const { data } = await request.post<{ access_token: string }>(
+ tokenUrl,
+ new URLSearchParams({
+ grant_type: "client_credentials",
+ client_id: clientId,
+ client_secret: clientSecret,
+ scope: "https://graph.microsoft.com/.default"
+ }).toString(),
+ {
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded"
+ }
+ }
+ );
+
+ return data.access_token;
+ } catch (error: unknown) {
+ // Retry on AADSTS7000215 (invalid client secret) — this can happen when a newly created
+ // secret hasn't propagated in Azure AD yet.
+ if (isInvalidClientSecretError(error) && attempt < GRAPH_TOKEN_MAX_RETRIES) {
+ const delay = GRAPH_TOKEN_RETRY_DELAY_MS * 2 ** attempt;
+ logger.info(
+ `credentialRotation: Graph API token auth failed (secret not propagated?), retrying in ${delay}ms (attempt ${attempt + 1}/${GRAPH_TOKEN_MAX_RETRIES})`
+ );
+ await sleep(delay);
+ return getGraphApiToken(credentials, attempt + 1);
+ }
+
+ if (error instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to obtain Graph API token for self-rotation: ${
+ (error.response?.data as { error_description?: string })?.error_description ||
+ error?.message ||
+ "Unknown error"
+ }`
+ });
+ }
+ throw new BadRequestError({
+ message: "Failed to obtain Graph API token for self-rotation"
+ });
+ }
+};
+
+const parseAzureError = (error: unknown, context: string): never => {
+ if (error instanceof AxiosError) {
+ let message: string | undefined;
+ if (
+ error.response?.data &&
+ typeof error.response.data === "object" &&
+ "error" in error.response.data &&
+ typeof (error.response.data as AzureErrorResponse).error.message === "string"
+ ) {
+ message = (error.response.data as AzureErrorResponse).error.message;
+ }
+ throw new BadRequestError({
+ message: `${context}: ${message || error.message || "Unknown error"}`
+ });
+ }
+ throw new BadRequestError({
+ message: `${context}: Unable to validate connection`
+ });
+};
+
+/**
+ * Looks up the Azure AD Application Object ID from a client ID (appId) using the Graph API.
+ */
+export const getApplicationObjectId = async (credentials: {
+ clientId: string;
+ clientSecret: string;
+ tenantId: string;
+}): Promise<string> => {
+ const accessToken = await getGraphApiToken(credentials);
+ const endpoint = `${GRAPH_API_BASE}/applications?$filter=appId eq '${credentials.clientId}'&$select=id`;
+
+ try {
+ const { data } = await request.get<{ value: Array<{ id: string }> }>(endpoint, {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json"
+ }
+ });
+
+ if (!data.value?.length) {
+ throw new BadRequestError({
+ message: `Could not find Azure AD application for clientId ${credentials.clientId}. Ensure the app registration has Application.ReadWrite.OwnedBy permission.`
+ });
+ }
+
+ return data.value[0].id;
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+ parseAzureError(error, `Failed to look up Azure AD application object ID for clientId ${credentials.clientId}`);
+
+ throw error; // unreachable, parseAzureError always throws
+ }
+};
+
+/**
+ * Validates the strategy config by checking the app's objectId is accessible via Graph API.
+ */
+export const validateAzureClientSecretRotationConfig = async (
+ config: TAzureClientSecretStrategyConfig,
+ credentials: { clientId: string; clientSecret: string; tenantId: string }
+) => {
+ const accessToken = await getGraphApiToken(credentials);
+ const endpoint = `${GRAPH_API_BASE}/applications/${config.objectId}`;
+
+ try {
+ await request.get(endpoint, {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json"
+ }
+ });
+ } catch (error: unknown) {
+ parseAzureError(error, `Failed to access Azure AD application ${config.objectId}`);
+ }
+};
+
+const AZURE_CONCURRENT_REQUEST_MAX_RETRIES = 3;
+const AZURE_CONCURRENT_REQUEST_BASE_DELAY_MS = 2000;
+
+const isAzureConcurrentRequestError = (error: unknown): boolean => {
+ if (!(error instanceof AxiosError)) return false;
+ const message = (error.response?.data as AzureErrorResponse)?.error?.message || error.message || "";
+ return message.includes("concurrent requests");
+};
+
+/**
+ * Creates a new client secret on the Azure AD application.
+ * Retries on Azure's transient "concurrent requests" error with exponential backoff.
+ */
+export const createAzureClientSecret = async (
+ config: TAzureClientSecretStrategyConfig,
+ credentials: { clientId: string; clientSecret: string; tenantId: string },
+ rotationInterval: number,
+ index?: number,
+ attempt = 0
+): Promise<TAzureClientSecretGeneratedCredential> => {
+ const accessToken = await getGraphApiToken(credentials);
+ const endpoint = `${GRAPH_API_BASE}/applications/${config.objectId}/addPassword`;
+
+ const now = new Date();
+ const formattedDate = `${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(
+ 2,
+ "0"
+ )}-${now.getFullYear()}`;
+
+ const endDateTime = new Date();
+ endDateTime.setDate(now.getDate() + rotationInterval * 2 + EXPIRY_PADDING_IN_DAYS);
+
+ try {
+ const { data } = await request.post<AzureAddPasswordResponse>(
+ endpoint,
+ {
+ passwordCredential: {
+ displayName: `Infisical Managed Credential (${formattedDate}) (idx-${index})`,
+ endDateTime: endDateTime.toISOString()
+ }
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json"
+ }
+ }
+ );
+
+ if (!data?.secretText || !data?.keyId) {
+ throw new Error("Invalid response from Azure: missing secretText or keyId.");
+ }
+
+ return {
+ keyId: data.keyId,
+ clientSecret: data.secretText,
+ createdAt: now.toISOString()
+ };
+ } catch (error: unknown) {
+ if (isAzureConcurrentRequestError(error) && attempt < AZURE_CONCURRENT_REQUEST_MAX_RETRIES) {
+ const delay = AZURE_CONCURRENT_REQUEST_BASE_DELAY_MS * 2 ** attempt;
+ logger.info(
+ `credentialRotation: Azure concurrent request error, retrying in ${delay}ms (attempt ${attempt + 1}/${AZURE_CONCURRENT_REQUEST_MAX_RETRIES})`
+ );
+ await sleep(delay);
+ return createAzureClientSecret(config, credentials, rotationInterval, index, attempt + 1);
+ }
+
+ if (error instanceof BadRequestError) throw error;
+ parseAzureError(error, `Failed to create client secret on Azure AD app ${config.objectId}`);
+
+ throw new BadRequestError({
+ message: `Failed to create client secret on Azure AD app ${config.objectId}: ${(error as Error)?.message || "Unknown error"}`
+ });
+ }
+};
+
+/**
+ * Lists all password credentials on the Azure AD application.
+ */
+export const listAzurePasswordCredentials = async (
+ config: TAzureClientSecretStrategyConfig,
+ credentials: { clientId: string; clientSecret: string; tenantId: string }
+): Promise<Array<{ keyId: string; displayName: string }>> => {
+ const accessToken = await getGraphApiToken(credentials);
+ const endpoint = `${GRAPH_API_BASE}/applications/${config.objectId}?$select=passwordCredentials`;
+
+ try {
+ const { data } = await request.get<{ passwordCredentials: Array<{ keyId: string; displayName: string }> }>(
+ endpoint,
+ {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json"
+ }
+ }
+ );
+
+ return data.passwordCredentials || [];
+ } catch (error: unknown) {
+ logger.warn(error, `Failed to list password credentials on app ${config.objectId}`);
+ return [];
+ }
+};
+
+/**
+ * Checks if a credential with the given keyId exists on the Azure AD application.
+ */
+export const azureCredentialExists = async (
+ keyId: string,
+ config: TAzureClientSecretStrategyConfig,
+ credentials: { clientId: string; clientSecret: string; tenantId: string }
+): Promise<boolean> => {
+ const passwordCredentials = await listAzurePasswordCredentials(config, credentials);
+ return passwordCredentials.some((credential) => credential.keyId === keyId);
+};
+
+/**
+ * Revokes a client secret from the Azure AD application.
+ * Retries on Azure's transient "concurrent requests" error with exponential backoff.
+ */
+export const revokeAzureClientSecret = async (
+ keyId: string,
+ config: TAzureClientSecretStrategyConfig,
+ credentials: { clientId: string; clientSecret: string; tenantId: string },
+ attempt = 0
+): Promise<void> => {
+ const exists = await azureCredentialExists(keyId, config, credentials);
+ if (!exists) {
+ logger.info(`Credential keyId=${keyId} does not exist on app ${config.objectId}, skipping revocation`);
+ return;
+ }
+
+ const accessToken = await getGraphApiToken(credentials);
+ const endpoint = `${GRAPH_API_BASE}/applications/${config.objectId}/removePassword`;
+
+ try {
+ await request.post(
+ endpoint,
+ { keyId },
+ {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json"
+ }
+ }
+ );
+ } catch (error: unknown) {
+ if (isAzureConcurrentRequestError(error) && attempt < AZURE_CONCURRENT_REQUEST_MAX_RETRIES) {
+ const delay = AZURE_CONCURRENT_REQUEST_BASE_DELAY_MS * 2 ** attempt;
+ logger.info(
+ `credentialRotation: Azure concurrent request error on revoke, retrying in ${delay}ms (attempt ${attempt + 1}/${AZURE_CONCURRENT_REQUEST_MAX_RETRIES})`
+ );
+ await sleep(delay);
+ await revokeAzureClientSecret(keyId, config, credentials, attempt + 1);
+ return;
+ }
+
+ parseAzureError(error, `Failed to revoke client secret keyId=${keyId} from app ${config.objectId}`);
+ }
+};
diff --git a/backend/src/services/app-connection/credential-rotation/providers/index.ts b/backend/src/services/app-connection/credential-rotation/providers/index.ts
new file mode 100644
index 0000000000..0cbb7a410d
--- /dev/null
+++ b/backend/src/services/app-connection/credential-rotation/providers/index.ts
@@ -0,0 +1,8 @@
+export {
+ createAzureClientSecret,
+ getApplicationObjectId,
+ getGraphApiToken,
+ listAzurePasswordCredentials,
+ revokeAzureClientSecret,
+ validateAzureClientSecretRotationConfig
+} from "./azure-client-secret-credential-rotation";
diff --git a/backend/src/services/external-migration/vault-external-migration-config-dal.ts b/backend/src/services/external-migration/vault-external-migration-config-dal.ts
index 34ff8757ac..453432b6ed 100644
--- a/backend/src/services/external-migration/vault-external-migration-config-dal.ts
+++ b/backend/src/services/external-migration/vault-external-migration-config-dal.ts
@@ -27,6 +27,7 @@ export const vaultExternalMigrationConfigDALFactory = (db: TDbClient) => {
db.ref("app").withSchema(TableName.AppConnection).as("appConnectionApp"),
db.ref("encryptedCredentials").withSchema(TableName.AppConnection).as("appConnectionEncryptedCredentials"),
db.ref("orgId").withSchema(TableName.AppConnection).as("appConnectionOrgId"),
+ db.ref("isAutoRotationEnabled").withSchema(TableName.AppConnection).as("appConnectionIsAutoRotationEnabled"),
db.ref("method").withSchema(TableName.AppConnection).as("appConnectionMethod"),
db.ref("description").withSchema(TableName.AppConnection).as("appConnectionDescription"),
db.ref("version").withSchema(TableName.AppConnection).as("appConnectionVersion"),
@@ -54,7 +55,8 @@ export const vaultExternalMigrationConfigDALFactory = (db: TDbClient) => {
gatewayId: result.appConnectionGatewayId,
projectId: result.appConnectionProjectId,
createdAt: result.appConnectionCreatedAt,
- updatedAt: result.appConnectionUpdatedAt
+ updatedAt: result.appConnectionUpdatedAt,
+ isAutoRotationEnabled: result.appConnectionIsAutoRotationEnabled
}
: undefined
};
diff --git a/backend/src/services/secret-sync/secret-sync-dal.ts b/backend/src/services/secret-sync/secret-sync-dal.ts
index 64d2c0bdb2..cf39e8d839 100644
--- a/backend/src/services/secret-sync/secret-sync-dal.ts
+++ b/backend/src/services/secret-sync/secret-sync-dal.ts
@@ -32,6 +32,7 @@ const baseSecretSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: Secre
db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),
db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),
db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),
+ db.ref("isAutoRotationEnabled").withSchema(TableName.AppConnection).as("connectionIsAutoRotationEnabled"),
db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),
db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),
db
@@ -69,6 +70,7 @@ const expandSecretSync = (
connectionIsPlatformManagedCredentials,
connectionGatewayId,
connectionProjectId,
+ connectionIsAutoRotationEnabled,
...el
} = secretSync;
@@ -89,7 +91,8 @@ const expandSecretSync = (
version: connectionVersion,
isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,
gatewayId: connectionGatewayId,
- projectId: connectionProjectId
+ projectId: connectionProjectId,
+ isAutoRotationEnabled: connectionIsAutoRotationEnabled
},
folder: folder
? {