Skip to content

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

84.5 KB
Raw Blame
import { ForbiddenError, subject } from "@casl/ability";
import { Knex } from "knex";
import isEqual from "lodash.isequal";

import { ActionProjectType, SecretType, TableName } from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { hasSecretReadValueOrDescribePermission } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
  ProjectPermissionSecretActions,
  ProjectPermissionSecretRotationActions,
  ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { auth0ClientSecretRotationFactory } from "@app/ee/services/secret-rotation-v2/auth0-client-secret/auth0-client-secret-rotation-fns";
import { azureClientSecretRotationFactory } from "@app/ee/services/secret-rotation-v2/azure-client-secret/azure-client-secret-rotation-fns";
import { cloudflareApiTokenRotationFactory } from "@app/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns";
import { cloudflareR2AccessKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-fns";
import { convexAccessKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/convex-access-key/convex-access-key-rotation-fns";
import { databricksServicePrincipalSecretRotationFactory } from "@app/ee/services/secret-rotation-v2/databricks-service-principal-secret/databricks-service-principal-secret-rotation-fns";
import { datadogApiKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/datadog-api-key/datadog-api-key-rotation-fns";
import { datadogApplicationKeySecretRotationFactory } from "@app/ee/services/secret-rotation-v2/datadog-application-key-secret/datadog-application-key-secret-rotation-fns";
import { fireworksApiKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/fireworks-api-key/fireworks-api-key-rotation-fns";
import { gcpServiceAccountKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/gcp-service-account-key/gcp-service-account-key-rotation-fns";
import { ldapPasswordRotationFactory } from "@app/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns";
import { salesforceOauthCredentialsRotationFactory } from "@app/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns";
import { SecretRotation, SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
import {
  calculateNextRotationAt,
  decryptSecretRotationCredentials,
  encryptSecretRotationCredentials,
  expandSecretRotation,
  getNextUtcRotationInterval,
  getSecretRotationRotateSecretJobOptions,
  getWebhookSanitizedErrorMessage,
  listSecretRotationOptions,
  parseRotationErrorMessage,
  throwOnImmutableParameterUpdate
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-fns";
import {
  getSecretRotationConnectionApps,
  SECRET_ROTATION_NAME_MAP
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-maps";
import {
  TCheckSecretRotationV2Credentials,
  TCreateSecretRotationV2DTO,
  TDeleteSecretRotationV2DTO,
  TFindSecretRotationV2ByIdDTO,
  TFindSecretRotationV2ByNameDTO,
  TGetDashboardSecretRotationsV2,
  TGetDashboardSecretRotationV2Count,
  TListSecretRotationsV2ByProjectId,
  TMoveSecretRotationV2DTO,
  TQuickSearchSecretRotationsV2,
  TRotateSecretRotationV2,
  TRotationFactory,
  TSecretRotationRotateGeneratedCredentials,
  TSecretRotationV2,
  TSecretRotationV2GeneratedCredentials,
  TSecretRotationV2PermissionContext,
  TSecretRotationV2Raw,
  TSecretRotationV2TemporaryParameters,
  TSecretRotationV2WithConnection,
  TUpdateSecretRotationV2DTO
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
import { sqlCredentialsRotationFactory } from "@app/ee/services/secret-rotation-v2/shared/sql-credentials";
import { snowflakeUserKeyPairRotationFactory } from "@app/ee/services/secret-rotation-v2/snowflake-user-key-pair/snowflake-user-key-pair-rotation-fns";
import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, InternalServerError, NotFoundError } from "@app/lib/errors";
import { takeRowScanWindow } from "@app/lib/fn";
import { recordSecretRotationOutcomeMetric, recordSecretRotationStatusChangeMetric } from "@app/lib/telemetry/metrics";
import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { ActorType } from "@app/services/auth/auth-type";
import { EventModificationType } from "@app/services/event-outbox/event-definition";
import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";
import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { previousSecretLocation } from "@app/services/secret-folder/secret-folder-events";
import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
import { createSecretBlindIndexer } from "@app/services/secret-v2-bridge/secret-blind-index-fns";
import { emitSecretsModified } from "@app/services/secret-v2-bridge/secret-events";
import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";
import {
  fnSecretBulkDelete,
  fnSecretBulkInsert,
  fnSecretBulkUpdate,
  fnUpdateMovedSecretReferences,
  reshapeBridgeSecret
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";
import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";
import { convertSecretRotationToValidationRuleProvider } from "@app/services/secret-validation-rule/secret-validation-rule-fns";
import { TSecretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";
import { TSecretQueueFactory } from "@app/services/secret/secret-queue";
import { SecretsOrderBy } from "@app/services/secret/secret-types";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { WebhookEvents } from "@app/services/webhook/webhook-types";

import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
import { awsIamUserSecretRotationFactory } from "./aws-iam-user-secret/aws-iam-user-secret-rotation-fns";
import { dbtServiceTokenRotationFactory } from "./dbt-service-token/dbt-service-token-rotation-fns";
import { hpIloRotationFactory } from "./hp-ilo-rotation/hp-ilo-rotation-fns";
import { HpIloRotationMethod } from "./hp-ilo-rotation/hp-ilo-rotation-schemas";
import { THpIloRotation, THpIloRotationGeneratedCredentials } from "./hp-ilo-rotation/hp-ilo-rotation-types";
import { litellmApiKeyRotationFactory } from "./litellm-api-key/litellm-api-key-rotation-fns";
import { mongodbCredentialsRotationFactory } from "./mongodb-credentials/mongodb-credentials-rotation-fns";
import { oktaClientSecretRotationFactory } from "./okta-client-secret/okta-client-secret-rotation-fns";
import { openRouterApiKeyRotationFactory } from "./open-router-api-key/open-router-api-key-rotation-fns";
import { openAIServiceAccountRotationFactory } from "./openai-service-account/openai-service-account-rotation-fns";
import { redisCredentialsRotationFactory } from "./redis-credentials/redis-credentials-rotation-fns";
import { TSecretRotationV2DALFactory } from "./secret-rotation-v2-dal";
import { stripeApiKeyRotationFactory } from "./stripe-api-key/stripe-api-key-rotation-fns";
import { supabaseApiKeyRotationFactory } from "./supabase-api-key/supabase-api-key-rotation-fns";
import { unixLinuxLocalAccountRotationFactory } from "./unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns";
import { UnixLinuxLocalAccountRotationMethod } from "./unix-linux-local-account-rotation/unix-linux-local-account-rotation-schemas";
import {
  TUnixLinuxLocalAccountRotation,
  TUnixLinuxLocalAccountRotationGeneratedCredentials
} from "./unix-linux-local-account-rotation/unix-linux-local-account-rotation-types";
import { windowsLocalAccountRotationFactory } from "./windows-local-account-rotation/windows-local-account-rotation-fns";
import { WindowsLocalAccountRotationMethod } from "./windows-local-account-rotation/windows-local-account-rotation-schemas";
import {
  TWindowsLocalAccountRotation,
  TWindowsLocalAccountRotationGeneratedCredentials
} from "./windows-local-account-rotation/windows-local-account-rotation-types";

type TLocalAccountRotation = TUnixLinuxLocalAccountRotation | TWindowsLocalAccountRotation | THpIloRotation;
type TLocalAccountRotationGeneratedCredentials =
  | TUnixLinuxLocalAccountRotationGeneratedCredentials
  | TWindowsLocalAccountRotationGeneratedCredentials
  | THpIloRotationGeneratedCredentials;

export type TSecretRotationV2ServiceFactoryDep = {
  secretRotationV2DAL: TSecretRotationV2DALFactory;
  appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
  permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
  projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
  keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
  folderDAL: Pick<
    TSecretFolderDALFactory,
    "findBySecretPath" | "findBySecretPathMultiEnv" | "findSecretPathByFolderIds"
  >;
  secretV2BridgeDAL: Pick<
    TSecretV2BridgeDALFactory,
    | "bulkUpdate"
    | "insertMany"
    | "deleteMany"
    | "upsertSecretReferences"
    | "find"
    | "findOne"
    | "updateById"
    | "findReferencedSecretReferencesBySecretKey"
    | "updateSecretReferenceEnvAndPath"
    | "invalidateSecretCacheByProjectId"
  >;
  secretVersionV2BridgeDAL: Pick<TSecretVersionV2DALFactory, "insertMany" | "findLatestVersionMany" | "update">;
  secretVersionTagV2BridgeDAL: Pick<TSecretVersionV2TagDALFactory, "insertMany">;
  resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
  secretTagDAL: Pick<TSecretTagDALFactory, "saveTagsToSecretV2" | "deleteTagsToSecretV2" | "find">;
  secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;
  queueService: Pick<TQueueServiceFactory, "queue">;
  appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById" | "transaction">;
  folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;
  eventEmitter: TEventEmitter;
  gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
  gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
  telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
  secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "findConstraintsForGeneratedSecret">;
};

export type TSecretRotationV2ServiceFactory = ReturnType<typeof secretRotationV2ServiceFactory>;

const MAX_GENERATED_CREDENTIALS_LENGTH = 2;

type TRotationFactoryImplementation = TRotationFactory<
  TSecretRotationV2WithConnection,
  TSecretRotationV2GeneratedCredentials,
  TSecretRotationV2TemporaryParameters
>;
const SECRET_ROTATION_FACTORY_MAP: Record<SecretRotation, TRotationFactoryImplementation> = {
  [SecretRotation.PostgresCredentials]: sqlCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.MsSqlCredentials]: sqlCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.MySqlCredentials]: sqlCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.OracleDBCredentials]: sqlCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.Auth0ClientSecret]: auth0ClientSecretRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.AzureClientSecret]: azureClientSecretRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.AwsIamUserSecret]: awsIamUserSecretRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.LdapPassword]: ldapPasswordRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.OktaClientSecret]: oktaClientSecretRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.RedisCredentials]: redisCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.MongoDBCredentials]: mongodbCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.DatabricksServicePrincipalSecret]:
    databricksServicePrincipalSecretRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.UnixLinuxLocalAccount]: unixLinuxLocalAccountRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.DbtServiceToken]: dbtServiceTokenRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.WindowsLocalAccount]: windowsLocalAccountRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.OpenRouterApiKey]: openRouterApiKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.LiteLLMApiKey]: litellmApiKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.OpenAIServiceAccount]: openAIServiceAccountRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.HpIloLocalAccount]: hpIloRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.SupabaseApiKey]: supabaseApiKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.SalesforceOauthCredentials]:
    salesforceOauthCredentialsRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.DatadogApplicationKeySecret]:
    datadogApplicationKeySecretRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.DatadogApiKey]: datadogApiKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.ConvexAccessKey]: convexAccessKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.FireworksApiKey]: fireworksApiKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.SnowflakeUserKeyPair]: snowflakeUserKeyPairRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.CloudflareApiToken]: cloudflareApiTokenRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.CloudflareR2AccessKey]: cloudflareR2AccessKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.StripeApiKey]: stripeApiKeyRotationFactory as TRotationFactoryImplementation,
  [SecretRotation.GcpServiceAccountKey]: gcpServiceAccountKeyRotationFactory as TRotationFactoryImplementation
};

export class SecretRotationInProgressError extends BadRequestError {
  constructor() {
    super({ message: "A rotation is already in progress. Please try again shortly." });
  }
}

export const secretRotationV2ServiceFactory = ({
  secretRotationV2DAL,
  folderDAL,
  secretV2BridgeDAL,
  secretVersionV2BridgeDAL,
  secretVersionTagV2BridgeDAL,
  secretTagDAL,
  resourceMetadataDAL,
  permissionService,
  appConnectionService,
  projectBotService,
  licenseService,
  kmsService,
  auditLogService,
  secretQueueService,
  keyStore,
  queueService,
  folderCommitService,
  eventEmitter,
  appConnectionDAL,
  gatewayV2Service,
  gatewayPoolService,
  telemetryService,
  secretValidationRuleService
}: TSecretRotationV2ServiceFactoryDep) => {
  const $resolvePasswordValidationContext = async ({
    projectId,
    envId,
    secretPath,
    type
  }: {
    projectId: string;
    envId: string;
    secretPath: string;
    type: SecretRotation;
  }) => {
    const provider = convertSecretRotationToValidationRuleProvider(type);
    if (!provider) return undefined;

    const matched = await secretValidationRuleService.findConstraintsForGeneratedSecret({
      projectId,
      envId,
      secretPath,
      type: SecretValidationRuleType.SecretRotations,
      provider
    });
    if (!matched.ruleNames.length) return undefined;
    return matched;
  };

  const $markRotationSucceeded = async (rotationId: string, tx: Knex) =>
    (
      await secretRotationV2DAL.update(
        { id: rotationId, rotationStatus: SecretRotationStatus.Failed },
        { rotationStatus: SecretRotationStatus.Success },
        tx
      )
    ).length > 0;

  const $queueSendSecretRotationStatusNotification = async (secretRotation: TSecretRotationV2Raw) => {
    const appCfg = getConfig();
    if (!appCfg.isSmtpConfigured) return; // comment out if testing email sending

    const { name, type, projectId, lastRotationAttemptedAt, folder, environment, id } = secretRotation;

    await queueService.queue(
      QueueName.SecretRotationV2,
      QueueJobs.SecretRotationV2SendNotification,
      { secretRotation: { name, type, projectId, lastRotationAttemptedAt, folder, environment, id } },
      {
        jobId: `secret-rotation-v2-notifications-${secretRotation.id}`,
        attempts: 5,
        backoff: {
          type: "exponential",
          delay: 1000
        }
      }
    );
  };

  const $findConflictingSecrets = async ({
    secretKeys,
    folderId,
    tx
  }: {
    secretKeys: string[];
    folderId: string;
    tx?: Knex;
  }) =>
    secretV2BridgeDAL.find(
      {
        $in: {
          [`${TableName.SecretV2}.key` as "key"]: secretKeys
        },
        [`${TableName.SecretV2}.folderId` as "folderId"]: folderId,
        [`${TableName.SecretV2}.type` as "type"]: SecretType.Shared
      },
      tx ? { tx } : undefined
    );

  const $throwOnConflictingSecrets = async ({
    secretKeys,
    folderId,
    tx,
    secretPath
  }: {
    secretKeys: string[];
    folderId: string;
    tx?: Knex;
    secretPath: string;
  }) => {
    if (new Set(secretKeys).size !== secretKeys.length) {
      throw new BadRequestError({
        message: `Secrets mapping keys must be unique. "${secretKeys.join(", ")}" contains duplicate keys.`
      });
    }

    const conflictingSecrets = await $findConflictingSecrets({ secretKeys, folderId, tx });

    if (conflictingSecrets.length) {
      throw new BadRequestError({
        message: `The following secrets already exist at the path "${secretPath}": ${conflictingSecrets
          .map(({ key }) => key)
          .join(", ")}`
      });
    }
  };

  const getSecretRotationSubject = (
    rotation: {
      environment?: { slug: string };
      folder?: { path: string };
      connection?: { id: string };
    },
    overrides?: { environment?: string; secretPath?: string; connectionId?: string }
  ) => {
    const connectionId = overrides?.connectionId ?? rotation.connection?.id;
    const envSlug = overrides?.environment ?? rotation.environment?.slug;
    const secretPath = overrides?.secretPath ?? rotation.folder?.path;
    const hasAny = connectionId || envSlug || secretPath;
    if (!hasAny) return ProjectPermissionSub.SecretRotation;
    return subject(ProjectPermissionSub.SecretRotation, {
      ...(envSlug && { environment: envSlug }),
      ...(secretPath && { secretPath }),
      ...(connectionId && { connectionId })
    });
  };

  const listSecretRotationsByProjectId = async (
    { projectId, type }: TListSecretRotationsV2ByProjectId,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message: "Failed to access secret rotations due to plan restriction. Upgrade plan to access secret rotations."
      });

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Read,
      ProjectPermissionSub.SecretRotation
    );

    const secretRotations = await secretRotationV2DAL.find({
      ...(type && { type }),
      projectId
    });

    return Promise.all(
      secretRotations
        .filter((rotation) =>
          permission.can(ProjectPermissionSecretRotationActions.Read, getSecretRotationSubject(rotation))
        )
        .map((rotation) => expandSecretRotation(rotation, kmsService))
    );
  };

  const findSecretRotationById = async ({ type, rotationId }: TFindSecretRotationV2ByIdDTO, actor: OrgServiceActor) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message: "Failed to access secret rotation due to plan restriction. Upgrade plan to access secret rotations."
      });

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID "${rotationId}"`
      });

    const { projectId, connection } = secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Read,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    return expandSecretRotation(secretRotation, kmsService);
  };

  const findSecretRotationGeneratedCredentialsById = async (
    { type, rotationId }: TFindSecretRotationV2ByIdDTO,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message:
          "Failed to access secret rotation credentials due to plan restriction. Upgrade plan to access secret rotations credentials."
      });

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID "${rotationId}"`
      });

    const { projectId, connection, encryptedGeneratedCredentials } = secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.ReadGeneratedCredentials,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    const generatedCredentials = await decryptSecretRotationCredentials({
      projectId,
      encryptedGeneratedCredentials,
      kmsService
    });

    return {
      generatedCredentials,
      secretRotation: secretRotation as TSecretRotationV2
    };
  };

  const findSecretRotationByName = async (
    { type, rotationName, secretPath, environment, projectId }: TFindSecretRotationV2ByNameDTO,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message: "Failed to access secret rotation due to plan restriction. Upgrade plan to access secret rotations."
      });

    const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);

    if (!folder)
      throw new BadRequestError({
        message: `Could not find folder with path "${secretPath}" in environment "${environment}" for project with ID "${projectId}"`
      });

    // we prevent conflicting names within a folder
    const secretRotation = await secretRotationV2DAL.findOne({
      name: rotationName,
      folderId: folder.id
    });

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with name "${rotationName}"`
      });

    const { connection, id: rotationId } = secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Read,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    return expandSecretRotation(secretRotation, kmsService);
  };

  const createSecretRotation = async (
    {
      projectId,
      secretPath,
      environment,
      rotateAtUtc = { hours: 0, minutes: 0 },
      secretsMapping,
      temporaryParameters,
      ...payload
    }: TCreateSecretRotationV2DTO,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message: "Failed to create secret rotation due to plan restriction. Upgrade plan to create secret rotations."
      });

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

    const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);

    if (!shouldUseSecretV2Bridge)
      throw new BadRequestError({
        message:
          "Project version does not support Secret Rotation V2. Please upgrade your project via the Infiscal Dashboard to gain access."
      });

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Create,
      getSecretRotationSubject({
        environment: { slug: environment },
        folder: { path: secretPath },
        connection: payload.connectionId ? { id: payload.connectionId } : undefined
      })
    );

    const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);

    if (!folder)
      throw new BadRequestError({
        message: `Could not find folder with path "${secretPath}" in environment "${environment}" for project with ID "${projectId}"`
      });

    // validates permission to connect and app is valid for rotation type
    const connection = await appConnectionService.validateAppConnectionUsageById(
      getSecretRotationConnectionApps(payload.type),
      { connectionId: payload.connectionId, projectId },
      actor
    );

    const passwordValidationContext = await $resolvePasswordValidationContext({
      projectId,
      envId: folder.envId,
      secretPath,
      type: payload.type
    });

    const rotationFactory = SECRET_ROTATION_FACTORY_MAP[payload.type](
      {
        parameters: payload.parameters,
        secretsMapping,
        connection,
        rotationInterval: payload.rotationInterval
      } as TSecretRotationV2WithConnection,
      appConnectionDAL,
      kmsService,
      gatewayV2Service,
      gatewayPoolService,
      keyStore,
      passwordValidationContext
    );

    // Perform ALL validation checks BEFORE rotating credentials on the external system.
    // Check 1: Ensure no rotation with the same name exists at this path
    const conflictingRotation = await secretRotationV2DAL.findOne({
      name: payload.name,
      folderId: folder.id
    });

    if (conflictingRotation)
      throw new BadRequestError({
        message: `A Secret Rotation with the name "${payload.name}" already exists at the secret path "${secretPath}"`
      });

    // Check 2: Ensure no secrets with the mapped names already exist at this path
    // We do this check outside the transaction to fail fast before any credential rotation
    await $throwOnConflictingSecrets({
      secretPath,
      secretKeys: Object.values(secretsMapping),
      folderId: folder.id
    });

    try {
      const currentTime = new Date();

      // callback structure to support transactional rollback when possible
      const secretRotation = await rotationFactory.issueCredentials(async (newCredentials) => {
        const encryptedGeneratedCredentials = await encryptSecretRotationCredentials({
          generatedCredentials: [newCredentials] as TSecretRotationV2GeneratedCredentials,
          projectId,
          kmsService
        });

        // Resolved before the transaction opens, so a slow external KMS does not hold a connection
        // and the advisory lock while it answers.
        const { encryptor } = await kmsService.createCipherPairWithDataKey({
          type: KmsDataKey.SecretManager,
          projectId
        });
        const blindIndexer = await createSecretBlindIndexer({ projectId, orgId: actor.orgId, kmsService });

        return secretRotationV2DAL.transaction(async (tx) => {
          await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.SecretRotationV2Creation(folder.id)]);

          // We repeat the check here to handle race conditions
          await $throwOnConflictingSecrets({
            secretPath,
            secretKeys: Object.values(secretsMapping),
            tx,
            folderId: folder.id
          });

          const createdRotation = await secretRotationV2DAL.create(
            {
              folderId: folder.id,
              secretsMapping,
              ...payload,
              encryptedGeneratedCredentials,
              rotateAtUtc,
              rotationStatus: SecretRotationStatus.Success,
              lastRotationAttemptedAt: currentTime,
              lastRotatedAt: currentTime,
              nextRotationAt: calculateNextRotationAt({
                lastRotatedAt: currentTime,
                isAutoRotationEnabled: Boolean(payload.isAutoRotationEnabled),
                rotateAtUtc,
                rotationInterval: payload.rotationInterval,
                rotationStatus: SecretRotationStatus.Success,
                isManualRotation: true
              })
            },
            tx
          );

          const secretsPayload = rotationFactory.getSecretsPayload(newCredentials);

          const inputSecretsWithBlindIndex = await Promise.all(
            secretsPayload.map(async ({ key, value }) => ({
              key,
              encryptedValue: encryptor({
                plainText: Buffer.from(value)
              }).cipherTextBlob,
              blindIndexes: await blindIndexer.generateBlindIndexes(Buffer.from(value)),
              references: []
            }))
          );

          const mappedSecrets = await fnSecretBulkInsert({
            eventEmitter,
            eventScope: { projectId, environment, secretPath: folder.path },
            folderId: folder.id,
            orgId: connection.orgId,
            tx,
            inputSecrets: inputSecretsWithBlindIndex,
            secretDAL: secretV2BridgeDAL,
            secretVersionDAL: secretVersionV2BridgeDAL,
            secretVersionTagDAL: secretVersionTagV2BridgeDAL,
            secretTagDAL,
            folderCommitService,
            resourceMetadataDAL,
            actor: {
              type: actor.type,
              actorId: actor.id
            }
          });

          await secretRotationV2DAL.insertSecretMappings(
            mappedSecrets.map((secret) => ({
              secretId: secret.id,
              rotationId: createdRotation.id
            })),
            tx
          );

          return createdRotation;
        });
      }, temporaryParameters);

      await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
      await secretQueueService.syncSecrets({
        orgId: connection.orgId,
        secretPath,
        projectId,
        environmentSlug: environment,
        environmentName: folder.environment.name,
        excludeReplication: true
      });

      return await expandSecretRotation(secretRotation, kmsService);
    } catch (err) {
      if (err instanceof DatabaseError) {
        const error = err.error as { code: string; message: string; table: string };

        if (error.code === DatabaseErrorCode.UniqueViolation) {
          switch (error.table) {
            case TableName.SecretRotationV2:
              throw new BadRequestError({
                message: `A Secret Rotation with the name "${payload.name}" already exists at the secret path "${secretPath}"`
              });
            default:
              throw err;
          }
        }

        throw err;
      }

      if (err instanceof BadRequestError) throw err;

      throw new BadRequestError({
        message: parseRotationErrorMessage(err)
      });
    }
  };

  const updateSecretRotation = async (dto: TUpdateSecretRotationV2DTO, actor: OrgServiceActor) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message: "Failed to update secret rotation due to plan restriction. Upgrade plan to update secret rotations."
      });

    const { type, rotationId, ...payload } = dto;

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID ${rotationId}`
      });

    throwOnImmutableParameterUpdate(dto, secretRotation);

    const { folder, environment, projectId, folderId, connection } = secretRotation;
    const secretsMapping = secretRotation.secretsMapping as TSecretRotationV2["secretsMapping"];

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Edit,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    // A running rotation saves the next rotation time from the settings it started with, so an edit made
    // meanwhile would have its schedule overwritten when the rotation finishes.
    const isRotationOccurring = Boolean(await keyStore.getItem(KeyStorePrefixes.SecretRotationLock(secretRotation.id)));

    if (isRotationOccurring)
      throw new BadRequestError({
        message: "A rotation is currently in progress for this secret rotation. Please try again shortly."
      });

    const nextRotationAt = calculateNextRotationAt({
      ...(secretRotation as TSecretRotationV2),
      ...payload,
      isManualRotation: secretRotation.isLastRotationManual
    });

    let secretsMappingUpdated = false;

    try {
      const updatedSecretRotation = await secretRotationV2DAL.transaction(async (tx) => {
        await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.SecretRotationV2Creation(folder.id)]);

        if (payload.secretsMapping && !isEqual(payload.secretsMapping, secretsMapping)) {
          const currentMappingKeys = Object.values(secretsMapping);
          await $throwOnConflictingSecrets({
            secretPath: folder.path,
            secretKeys: Object.values(payload.secretsMapping).filter((key) => !currentMappingKeys.includes(key)),
            tx,
            folderId: folder.id
          });

          // update mapped secrets names
          await fnSecretBulkUpdate({
            eventEmitter,
            eventScope: { projectId, environment: environment.slug, secretPath: folder.path },
            folderId,
            orgId: connection.orgId,
            tx,
            inputSecrets: Object.entries(secretsMapping).map(([mappingKey, secretKey]) => ({
              filter: {
                key: secretKey,
                folderId,
                type: SecretType.Shared
              },
              data: {
                key: payload.secretsMapping![mappingKey as keyof TSecretRotationV2["secretsMapping"]]
              }
            })),
            secretDAL: secretV2BridgeDAL,
            secretVersionDAL: secretVersionV2BridgeDAL,
            secretVersionTagDAL: secretVersionTagV2BridgeDAL,
            secretTagDAL,
            folderCommitService,
            resourceMetadataDAL,
            actor: {
              type: actor.type,
              actorId: actor.id
            }
          });

          secretsMappingUpdated = true;
        }

        return secretRotationV2DAL.updateById(
          rotationId,
          {
            ...payload,
            nextRotationAt
          },
          tx
        );
      });

      if (secretsMappingUpdated) {
        await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
        await secretQueueService.syncSecrets({
          orgId: connection.orgId,
          secretPath: folder.path,
          projectId,
          environmentSlug: environment.slug,
          environmentName: environment.name,
          excludeReplication: true
        });
      }

      // queue for rotation if adjusted time falls before next cron
      if (nextRotationAt && nextRotationAt.getTime() < getNextUtcRotationInterval().getTime()) {
        await queueService.queue(
          QueueName.SecretRotationV2RotateSecrets,
          QueueJobs.SecretRotationV2RotateSecrets,
          { rotationId, queuedAt: new Date(), isManualRotation: true },
          getSecretRotationRotateSecretJobOptions(updatedSecretRotation)
        );
      }

      return await expandSecretRotation(updatedSecretRotation, kmsService);
    } catch (err) {
      if (err instanceof DatabaseError) {
        const error = err.error as { code: string; message: string; table: string };

        if (error.code === DatabaseErrorCode.UniqueViolation) {
          switch (error.table) {
            case TableName.SecretRotationV2:
              if (payload.name)
                throw new BadRequestError({
                  message: `A Secret Rotation with the name "${payload.name}" already exists at the secret path "${folder.path}"`
                });
              break;
            default:
              throw err;
          }
        }
      }

      if (err instanceof BadRequestError) throw err;

      throw err;
    }
  };

  const deleteSecretRotation = async (
    { type, rotationId, deleteSecrets, revokeGeneratedCredentials }: TDeleteSecretRotationV2DTO,
    actor: OrgServiceActor
  ) => {
    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID "${rotationId}"`
      });

    const { folder, environment, projectId, encryptedGeneratedCredentials, connection, folderId, secretsMapping } =
      secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Delete,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    const deleteTransaction = async () =>
      secretRotationV2DAL.transaction(async (tx) => {
        if (deleteSecrets) {
          await fnSecretBulkDelete({
            eventEmitter,
            eventScope: { projectId, environment: environment.slug, secretPath: folder.path },
            secretDAL: secretV2BridgeDAL,
            secretQueueService,
            inputSecrets: Object.values(secretsMapping as TSecretRotationV2["secretsMapping"]).map((secretKey) => ({
              secretKey,
              type: SecretType.Shared
            })),
            projectId,
            folderId,
            actorId: actor.id, // not actually used since rotated secrets are shared
            actorType: actor.type,
            folderCommitService,
            secretVersionDAL: secretVersionV2BridgeDAL,
            tx
          });
        }

        return secretRotationV2DAL.deleteById(rotationId, tx);
      });

    if (revokeGeneratedCredentials) {
      const appConnection = await decryptAppConnection(connection, kmsService);

      const passwordValidationContext = await $resolvePasswordValidationContext({
        projectId,
        envId: environment.id,
        secretPath: folder.path,
        type
      });

      const rotationFactory = SECRET_ROTATION_FACTORY_MAP[type](
        {
          ...secretRotation,
          connection: appConnection
        } as TSecretRotationV2WithConnection,
        appConnectionDAL,
        kmsService,
        gatewayV2Service,
        gatewayPoolService,
        keyStore,
        passwordValidationContext
      );

      const generatedCredentials = await decryptSecretRotationCredentials({
        encryptedGeneratedCredentials,
        projectId,
        kmsService
      });

      await rotationFactory.revokeCredentials(generatedCredentials, deleteTransaction);
    } else {
      await deleteTransaction();
    }

    if (deleteSecrets) {
      await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
      await secretQueueService.syncSecrets({
        orgId: connection.orgId,
        secretPath: folder.path,
        projectId,
        environmentSlug: environment.slug,
        environmentName: environment.name,
        excludeReplication: true
      });
    }

    return expandSecretRotation(secretRotation, kmsService);
  };

  const moveSecretRotation = async (
    { type, rotationId, destinationEnvironment, destinationSecretPath, overwriteDestination }: TMoveSecretRotationV2DTO,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message: "Failed to move secret rotation due to plan restriction. Upgrade plan to manage secret rotations."
      });

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID "${rotationId}"`
      });

    const { projectId, folderId: sourceFolderId, secretsMapping, folder, environment, connection } = secretRotation;

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    const isRotationOccurring = Boolean(await keyStore.getItem(KeyStorePrefixes.SecretRotationLock(secretRotation.id)));

    if (isRotationOccurring)
      throw new BadRequestError({
        message: "A rotation is currently in progress for this secret rotation. Please try again shortly."
      });

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Delete,
      getSecretRotationSubject(secretRotation)
    );

    const destinationFolder = await folderDAL.findBySecretPath(
      projectId,
      destinationEnvironment,
      destinationSecretPath
    );

    if (!destinationFolder)
      throw new NotFoundError({
        message: `Destination folder with path "${destinationSecretPath}" in environment "${destinationEnvironment}" not found`
      });

    if (destinationFolder.id === sourceFolderId)
      throw new BadRequestError({
        message: "Source and destination locations are the same"
      });

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.Create,
      getSecretRotationSubject(secretRotation, {
        environment: destinationEnvironment,
        secretPath: destinationSecretPath
      })
    );

    const mappedKeys = Object.values(secretsMapping as TSecretRotationV2["secretsMapping"]);

    const { encryptor: secretManagerEncryptor, decryptor: secretManagerDecryptor } =
      await kmsService.createCipherPairWithDataKey({
        type: KmsDataKey.SecretManager,
        projectId
      });
    const blindIndexer = await createSecretBlindIndexer({ projectId, orgId: actor.orgId, kmsService });

    const updatedRotation = await secretRotationV2DAL.transaction(async (tx) => {
      const conflictingRotation = await secretRotationV2DAL.findOne({
        name: secretRotation.name,
        folderId: destinationFolder.id
      });

      if (conflictingRotation)
        throw new BadRequestError({
          message: `A Secret Rotation with the name "${secretRotation.name}" already exists at the secret path "${destinationSecretPath}"`
        });

      const conflictingDestinationSecrets = await $findConflictingSecrets({
        secretKeys: mappedKeys,
        folderId: destinationFolder.id
      });

      if (conflictingDestinationSecrets.length && !overwriteDestination) {
        throw new BadRequestError({
          message: `The following secrets already exist at the destination path "${destinationSecretPath}": ${conflictingDestinationSecrets
            .map(({ key }) => key)
            .join(", ")}. Set "overwriteDestination" to true to replace them.`
        });
      }

      if (conflictingDestinationSecrets.length && overwriteDestination) {
        // Require secret-level delete permission.
        conflictingDestinationSecrets.forEach((conflictingSecret) => {
          ForbiddenError.from(permission).throwUnlessCan(
            ProjectPermissionSecretActions.Delete,
            subject(ProjectPermissionSub.Secrets, {
              environment: destinationEnvironment,
              secretPath: destinationSecretPath,
              secretName: conflictingSecret.key,
              secretTags: conflictingSecret.tags?.map((el) => el.slug)
            })
          );
        });

        const overwrittenSecrets = await secretV2BridgeDAL.deleteMany(
          conflictingDestinationSecrets.map((s) => ({ key: s.key, type: SecretType.Shared })),
          destinationFolder.id,
          actor.id,
          tx
        );
        await emitSecretsModified(
          eventEmitter,
          {
            projectId,
            environment: destinationEnvironment,
            secretPath: destinationFolder.path,
            modificationType: EventModificationType.Deleted
          },
          overwrittenSecrets,
          tx
        );
      }

      const sourceSecrets = await secretV2BridgeDAL.find(
        {
          $in: {
            [`${TableName.SecretV2}.key` as "key"]: mappedKeys
          },
          [`${TableName.SecretV2}.folderId` as "folderId"]: sourceFolderId,
          [`${TableName.SecretV2}.type` as "type"]: SecretType.Shared
        },
        { tx }
      );

      if (sourceSecrets.length) {
        await tx(TableName.SecretV2)
          .whereIn(
            "id",
            sourceSecrets.map((s) => s.id)
          )
          .update({ folderId: destinationFolder.id });

        await secretVersionV2BridgeDAL.update(
          {
            $in: {
              secretId: sourceSecrets.map((s) => s.id)
            }
          },
          { folderId: destinationFolder.id },
          tx
        );

        await emitSecretsModified(
          eventEmitter,
          {
            projectId,
            environment: destinationEnvironment,
            secretPath: destinationFolder.path,
            modificationType: EventModificationType.Updated,
            previous: previousSecretLocation(
              { environment: environment.slug, secretPath: folder.path },
              { environment: destinationEnvironment, secretPath: destinationFolder.path }
            )
          },
          sourceSecrets,
          tx
        );

        for await (const secret of sourceSecrets) {
          await fnUpdateMovedSecretReferences({
            orgId: actor.orgId,
            projectId,
            sourceEnvironment: environment.slug,
            sourceSecretPath: folder.path,
            sourceFolderId,
            destinationEnvironment,
            destinationSecretPath,
            destinationFolderId: destinationFolder.id,
            secretKey: secret.key,
            secretId: secret.id,
            secretDAL: secretV2BridgeDAL,
            secretVersionDAL: secretVersionV2BridgeDAL,
            folderCommitService,
            folderDAL,
            secretQueueService,
            eventEmitter,
            encryptor: ({ plainText }) => secretManagerEncryptor({ plainText }),
            decryptor: ({ cipherTextBlob }) => secretManagerDecryptor({ cipherTextBlob }),
            blindIndexer,
            tx
          });
        }
      }

      return secretRotationV2DAL.updateById(rotationId, { folderId: destinationFolder.id }, tx);
    });

    await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);

    await secretQueueService.syncSecrets({
      orgId: connection.orgId,
      secretPath: destinationSecretPath,
      projectId,
      environmentSlug: destinationEnvironment,
      environmentName: destinationFolder.environment.name,
      excludeReplication: true
    });

    await secretQueueService.syncSecrets({
      orgId: connection.orgId,
      secretPath: folder.path,
      projectId,
      environmentSlug: environment.slug,
      environmentName: environment.name,
      excludeReplication: true
    });

    return {
      secretRotation: await expandSecretRotation(updatedRotation, kmsService),
      sourceEnvironment: environment.slug,
      sourceSecretPath: folder.path
    };
  };

  const triggerFailedWebhook = async (
    projectId: string,
    environment: { slug: string; name: string; id: string },
    error: unknown,
    folder: { id: string; path: string },
    secretRotation: TSecretRotationV2Raw,
    isManualRotation: boolean
  ) => {
    const webhookErrorMessage = getWebhookSanitizedErrorMessage(error);

    await queueService.queue(
      QueueName.SecretWebhook,
      QueueJobs.SecWebhook,
      {
        type: WebhookEvents.SecretRotationFailed,
        payload: {
          projectId,
          environment: environment.slug,
          environmentName: environment.name,
          secretPath: folder.path,
          rotationName: secretRotation.name,
          triggeredManually: isManualRotation,
          errorMessage: webhookErrorMessage
        }
      },
      {
        jobId: `secret-rotation-webhook-${secretRotation.id}-${Date.now()}`,
        removeOnFail: { count: 5 },
        removeOnComplete: true,
        delay: 1000,
        attempts: 5,
        backoff: {
          type: "exponential",
          delay: 3000
        }
      }
    );
  };

  const rotateGeneratedCredentials = async (
    secretRotation: TSecretRotationV2Raw,
    {
      auditLogInfo,
      jobId,
      shouldSendNotification,
      isFinalAttempt = true,
      isManualRotation = false
    }: TSecretRotationRotateGeneratedCredentials = {}
  ) => {
    const {
      connection,
      folder,
      environment,
      encryptedGeneratedCredentials,
      activeIndex,
      projectId,
      type,
      folderId,
      id: rotationId,
      parameters,
      secretsMapping
    } = secretRotation;

    let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;
    try {
      lock = await keyStore.acquireLock([KeyStorePrefixes.SecretRotationLock(rotationId)], 60 * 1000);
    } catch (e) {
      throw new SecretRotationInProgressError();
    }

    try {
      const appConnection = await decryptAppConnection(connection, kmsService);

      const generatedCredentials = await decryptSecretRotationCredentials({
        projectId,
        encryptedGeneratedCredentials,
        kmsService
      });

      const inactiveIndex = (activeIndex + 1) % MAX_GENERATED_CREDENTIALS_LENGTH;

      const inactiveCredentials = generatedCredentials[inactiveIndex];
      const activeCredentials = generatedCredentials[activeIndex];

      const passwordValidationContext = await $resolvePasswordValidationContext({
        projectId,
        envId: environment.id,
        secretPath: folder.path,
        type: type as SecretRotation
      });

      const rotationFactory = SECRET_ROTATION_FACTORY_MAP[type as SecretRotation](
        {
          ...secretRotation,
          connection: appConnection
        } as TSecretRotationV2WithConnection,
        appConnectionDAL,
        kmsService,
        gatewayV2Service,
        gatewayPoolService,
        keyStore,
        passwordValidationContext
      );

      const updatedRotation = await rotationFactory.rotateCredentials(
        inactiveCredentials,
        async (newCredentials) => {
          const updatedCredentials = [...generatedCredentials];
          updatedCredentials[inactiveIndex] = newCredentials;

          const encryptedUpdatedCredentials = await encryptSecretRotationCredentials({
            projectId,
            generatedCredentials: updatedCredentials as TSecretRotationV2GeneratedCredentials,
            kmsService
          });

          // Resolved before the transaction opens, so a slow external KMS does not hold a connection
          // while it answers.
          const { encryptor } = await kmsService.createCipherPairWithDataKey({
            type: KmsDataKey.SecretManager,
            projectId
          });
          const blindIndexer = await createSecretBlindIndexer({ projectId, orgId: connection.orgId, kmsService });

          let isRecovery = false;
          const rotated = await secretRotationV2DAL.transaction(async (tx) => {
            const secretsPayload = rotationFactory.getSecretsPayload(newCredentials);

            // update mapped secrets with new credential values
            const inputSecretsWithBlindIndex = await Promise.all(
              secretsPayload.map(async ({ key, value }) => ({
                filter: {
                  key,
                  folderId,
                  type: SecretType.Shared
                },
                data: {
                  encryptedValue: encryptor({
                    plainText: Buffer.from(value)
                  }).cipherTextBlob,
                  blindIndexes: await blindIndexer.generateBlindIndexes(Buffer.from(value)),
                  references: []
                }
              }))
            );

            await fnSecretBulkUpdate({
              eventEmitter,
              eventScope: { projectId, environment: environment.slug, secretPath: folder.path },
              folderId,
              orgId: connection.orgId,
              tx,
              inputSecrets: inputSecretsWithBlindIndex,
              secretDAL: secretV2BridgeDAL,
              secretVersionDAL: secretVersionV2BridgeDAL,
              secretVersionTagDAL: secretVersionTagV2BridgeDAL,
              folderCommitService,
              actor: {
                type: ActorType.PLATFORM
              },
              secretTagDAL,
              resourceMetadataDAL
            });

            const currentTime = new Date();

            isRecovery = await $markRotationSucceeded(secretRotation.id, tx);
            return secretRotationV2DAL.updateById(
              secretRotation.id,
              {
                encryptedGeneratedCredentials: encryptedUpdatedCredentials,
                activeIndex: inactiveIndex,
                isLastRotationManual: isManualRotation,
                lastRotatedAt: currentTime,
                lastRotationAttemptedAt: currentTime,
                nextRotationAt: calculateNextRotationAt({
                  ...(secretRotation as TSecretRotationV2),
                  rotationStatus: SecretRotationStatus.Success,
                  lastRotatedAt: currentTime,
                  isManualRotation
                }),
                rotationStatus: SecretRotationStatus.Success,
                lastRotationJobId: jobId,
                encryptedLastRotationMessage: null
              },
              tx
            );
          });

          if (isRecovery) recordSecretRotationStatusChangeMetric({ type, newStatus: "healthy" });
          return rotated;
        },
        activeCredentials
      );

      await auditLogService.createAuditLog({
        ...(auditLogInfo ?? {
          actor: {
            type: ActorType.PLATFORM,
            metadata: {}
          }
        }),
        projectId,
        event: {
          type: EventType.SECRET_ROTATION_ROTATE_SECRETS,
          metadata: {
            type,
            rotationId,
            connectionId: connection.id,
            folderId,
            parameters,
            secretsMapping,
            status: SecretRotationStatus.Success,
            occurredAt: new Date(),
            message: null,
            jobId
          }
        }
      });

      await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
      await secretQueueService.syncSecrets({
        orgId: connection.orgId,
        secretPath: folder.path,
        projectId,
        environmentSlug: environment.slug,
        environmentName: environment.name,
        excludeReplication: true
      });

      recordSecretRotationOutcomeMetric({ type, outcome: "success", attemptsExhausted: isFinalAttempt });

      return updatedRotation;
    } catch (error) {
      const errorMessage = parseRotationErrorMessage(error);

      recordSecretRotationOutcomeMetric({ type, outcome: "failure", attemptsExhausted: isFinalAttempt });

      if (isManualRotation) {
        await triggerFailedWebhook(projectId, environment, error, folder, secretRotation, isManualRotation);
      }

      if (isFinalAttempt) {
        const { encryptor } = await kmsService.createCipherPairWithDataKey({
          type: KmsDataKey.SecretManager,
          projectId
        });

        const { cipherTextBlob: encryptedMessage } = encryptor({
          plainText: Buffer.from(errorMessage)
        });

        let isStatusChange = false;
        const updatedRotation = await secretRotationV2DAL.transaction(async (tx) => {
          isStatusChange =
            (
              await secretRotationV2DAL.update(
                { id: secretRotation.id, rotationStatus: SecretRotationStatus.Success },
                { rotationStatus: SecretRotationStatus.Failed },
                tx
              )
            ).length > 0;

          return secretRotationV2DAL.updateById(
            secretRotation.id,
            {
              rotationStatus: SecretRotationStatus.Failed,
              lastRotationJobId: jobId,
              lastRotationAttemptedAt: new Date(),
              encryptedLastRotationMessage: encryptedMessage,
              nextRotationAt: getNextUtcRotationInterval(secretRotation.rotateAtUtc as TSecretRotationV2["rotateAtUtc"])
            },
            tx
          );
        });

        if (isStatusChange) recordSecretRotationStatusChangeMetric({ type, newStatus: "failed" });

        if (shouldSendNotification) {
          await $queueSendSecretRotationStatusNotification(updatedRotation);
          await triggerFailedWebhook(projectId, environment, error, folder, secretRotation, isManualRotation);
        }

        void telemetryService
          .sendPostHogEvents({
            event: PostHogEventTypes.SecretRotationV2Failed,
            distinctId: `platform/${projectId}`,
            organizationId: connection.orgId,
            properties: {
              rotationId,
              type: type as SecretRotation,
              projectId
            }
          })
          .catch(() => {});
      }

      await auditLogService.createAuditLog({
        ...(auditLogInfo ?? {
          actor: {
            type: ActorType.PLATFORM,
            metadata: {}
          }
        }),
        projectId,
        event: {
          type: EventType.SECRET_ROTATION_ROTATE_SECRETS,
          metadata: {
            type,
            rotationId,
            connectionId: connection.id,
            folderId,
            parameters,
            secretsMapping,
            occurredAt: new Date(),
            status: SecretRotationStatus.Failed,
            message: isFinalAttempt ? "See Rotation status for details" : "Rotation will be re-attempted shortly...",
            jobId
          }
        }
      });

      throw new BadRequestError({ message: errorMessage });
    } finally {
      await lock.release();
    }
  };

  const rotateSecretRotation = async (
    { rotationId, type, auditLogInfo }: TRotateSecretRotationV2,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message:
          "Failed to rotate secret rotation secrets due to plan restriction. Upgrade plan to rotate secret rotation secrets."
      });

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID "${rotationId}"`
      });

    const { projectId, connection } = secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.RotateSecrets,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    const isRotationOccurring = Boolean(await keyStore.getItem(KeyStorePrefixes.SecretRotationLock(secretRotation.id)));

    if (isRotationOccurring)
      throw new BadRequestError({ message: `A rotation is already in progress. Please try again shortly.` });

    try {
      const updatedRotation = await rotateGeneratedCredentials(secretRotation, {
        auditLogInfo,
        isManualRotation: true
      });

      return await expandSecretRotation(updatedRotation, kmsService);
    } catch (err) {
      if (err instanceof SecretRotationInProgressError) throw err;
      throw new InternalServerError({
        message: (err as Error).message ?? "Failed to rotate secrets: check Rotation status for details."
      });
    }
  };

  const checkSecretRotationCredentials = async (
    { rotationId, type, auditLogInfo }: TCheckSecretRotationV2Credentials,
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message:
          "Failed to check secret rotation credentials due to plan restriction. Upgrade plan to check secret rotation credentials."
      });

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find ${SECRET_ROTATION_NAME_MAP[type]} Rotation with ID "${rotationId}"`
      });

    const { projectId, connection, encryptedGeneratedCredentials, activeIndex, folderId } = secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.ReadGeneratedCredentials,
      getSecretRotationSubject(secretRotation)
    );

    if (!getSecretRotationConnectionApps(type).includes(connection.app as AppConnection))
      throw new BadRequestError({
        message: `Secret Rotation with ID "${rotationId}" is not configured for ${SECRET_ROTATION_NAME_MAP[type]}`
      });

    const isRotationOccurring = Boolean(await keyStore.getItem(KeyStorePrefixes.SecretRotationLock(secretRotation.id)));

    if (isRotationOccurring)
      throw new BadRequestError({ message: `A rotation is in progress. Please try again shortly.` });

    const appConnection = await decryptAppConnection(connection, kmsService);

    const generatedCredentials = await decryptSecretRotationCredentials({
      projectId,
      encryptedGeneratedCredentials,
      kmsService
    });

    const activeCredentials = generatedCredentials?.[activeIndex];

    if (!activeCredentials)
      throw new BadRequestError({ message: "No active credentials are available to check for this rotation." });

    const rotationFactory = SECRET_ROTATION_FACTORY_MAP[type as SecretRotation](
      {
        ...secretRotation,
        connection: appConnection
      } as TSecretRotationV2WithConnection,
      appConnectionDAL,
      kmsService,
      gatewayV2Service,
      gatewayPoolService,
      keyStore
    );

    if (!rotationFactory.checkActiveCredentials)
      throw new BadRequestError({
        message: `Credential check is not yet supported for ${SECRET_ROTATION_NAME_MAP[type]} Rotations.`
      });

    let success = true;
    let errorMessage: string | undefined;

    try {
      await rotationFactory.checkActiveCredentials(activeCredentials);
    } catch (err) {
      success = false;
      errorMessage = (err as Error).message;
    }

    await auditLogService.createAuditLog({
      ...(auditLogInfo ?? { actor: { type: ActorType.PLATFORM, metadata: {} } }),
      projectId,
      event: {
        type: EventType.SECRET_ROTATION_CHECK_CREDENTIALS,
        metadata: {
          type,
          rotationId,
          connectionId: connection.id,
          folderId,
          success,
          errorMessage
        }
      }
    });

    if (!success)
      throw new BadRequestError({
        message: errorMessage ?? "Active credentials are no longer valid."
      });
  };

  const getDashboardSecretRotationCount = async (
    { projectId, environments, secretPath, search }: TGetDashboardSecretRotationV2Count,
    actor: OrgServiceActor
  ) => {
    // we don't check plan for dashboard like dynamic secret, actions will be prevented

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

    const permissiveEnvironments = environments.filter((environment) =>
      permission.can(
        ProjectPermissionSecretRotationActions.Read,
        subject(ProjectPermissionSub.SecretRotation, { environment, secretPath })
      )
    );

    if (!permissiveEnvironments.length) return 0;

    const folders = await folderDAL.findBySecretPathMultiEnv(projectId, permissiveEnvironments, secretPath);

    if (!folders.length) {
      throw new NotFoundError({
        message: `Folders with path '${secretPath}' in environments with slugs '${permissiveEnvironments.join(
          ", "
        )}' not found`
      });
    }

    const folderIds = folders.map((folder) => folder.id);

    // Fetch rotations (with search) then filter by per-rotation permission so connectionId
    // (and other) restrictions are enforced; findWithMappedSecretsCount cannot filter by connectionId.
    const secretRotations = await secretRotationV2DAL.findWithMappedSecrets(
      { $in: { folderId: folderIds }, search, projectId },
      {}
    );

    const rotationsForCount = secretRotations as (TSecretRotationV2PermissionContext & { name: string })[];
    const allowedRotations = rotationsForCount.filter((rotation) =>
      permission.can(ProjectPermissionSecretRotationActions.Read, getSecretRotationSubject(rotation))
    );
    const count = new Set(allowedRotations.map((r) => r.name)).size;

    return count;
  };

  const getDashboardSecretRotations = async (
    {
      projectId,
      environments,
      secretPath,
      search,
      limit,
      offset = 0,
      orderBy = SecretsOrderBy.Name,
      orderDirection = OrderByDirection.ASC
    }: TGetDashboardSecretRotationsV2,
    actor: OrgServiceActor
  ) => {
    // we don't check plan for dashboard like dynamic secret, actions will be prevented

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

    const permissiveEnvironments = environments.filter((environment) =>
      permission.can(
        ProjectPermissionSecretRotationActions.Read,
        subject(ProjectPermissionSub.SecretRotation, { environment, secretPath })
      )
    );

    if (!permissiveEnvironments.length) return [];

    const folders = await folderDAL.findBySecretPathMultiEnv(projectId, permissiveEnvironments, secretPath);

    if (!folders.length) {
      throw new NotFoundError({
        message: `Folders with path '${secretPath}' in environments with slugs '${permissiveEnvironments.join(
          ", "
        )}' not found`
      });
    }

    const folderIds = folders.map((folder) => folder.id);

    const secretRotationsRaw = await secretRotationV2DAL.findWithMappedSecrets(
      {
        $in: { folderId: folderIds },
        search,
        projectId
      },
      {
        limit,
        offset,
        sort: orderBy ? [[orderBy, orderDirection]] : undefined
      }
    );

    // Filter by per-rotation permission so connectionId (and other) restrictions are enforced.
    const secretRotations = secretRotationsRaw.filter((rotation: TSecretRotationV2PermissionContext) =>
      permission.can(ProjectPermissionSecretRotationActions.Read, getSecretRotationSubject(rotation))
    );

    const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
      type: KmsDataKey.SecretManager,
      projectId
    });

    const secretRotationsWithSecrets = await Promise.all(
      secretRotations.map(async ({ secrets, ...rotation }) => {
        const decryptedSecrets = secrets.map((secret) => {
          const canDescribeSecret = hasSecretReadValueOrDescribePermission(
            permission,
            ProjectPermissionSecretActions.DescribeSecret,
            {
              environment: rotation.environment.slug,
              secretPath: rotation.folder.path,
              secretName: secret.key,
              // TODO: scott/akhil our mapper seems to not propagate children's children types
              // @ts-expect-error eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-assignment
              secretTags: (secret.tags as { slug: string; name: string; color: string }[]).map((i) => i.slug)
            }
          );

          if (!canDescribeSecret) {
            return null; // return null so we know to display empty row in dashboard
          }

          const secretValueHidden = !hasSecretReadValueOrDescribePermission(
            permission,
            ProjectPermissionSecretActions.ReadValue,
            {
              environment: rotation.environment.slug,
              secretPath: rotation.folder.path,
              secretName: secret.key,
              // TODO: scott/akhil our mapper seems to not propagate children's children types
              // @ts-expect-error eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-assignment
              secretTags: (secret.tags as { slug: string; name: string; color: string }[]).map((i) => i.slug)
            }
          );
          return reshapeBridgeSecret(
            projectId,
            rotation.environment.slug,
            rotation.folder.path,
            {
              ...secret,
              secretMetadata: (
                secret as { secretMetadata: { key: string; value?: string; encryptedValue?: Buffer }[] }
              ).secretMetadata?.map((el) => ({
                isEncrypted: Boolean(el.encryptedValue),
                key: el.key,
                value: el.encryptedValue
                  ? secretManagerDecryptor({ cipherTextBlob: el.encryptedValue }).toString()
                  : el.value || ""
              })),
              value: secret.encryptedValue
                ? secretManagerDecryptor({ cipherTextBlob: secret.encryptedValue }).toString()
                : "",
              comment: secret.encryptedComment
                ? secretManagerDecryptor({ cipherTextBlob: secret.encryptedComment }).toString()
                : ""
            },
            secretValueHidden && secret.type === SecretType.Shared
          );
        });

        const expandedRotation = await expandSecretRotation(rotation, kmsService);

        return {
          ...expandedRotation,
          secrets: decryptedSecrets
        };
      })
    );

    return secretRotationsWithSecrets as (TSecretRotationV2 & {
      secrets: Awaited<ReturnType<typeof reshapeBridgeSecret>>[];
    })[];
  };

  const getQuickSearchSecretRotations = async (
    { folderMappings, filters: { search, limit, offset, orderDirection }, projectId }: TQuickSearchSecretRotationsV2,
    actor: OrgServiceActor
  ) => {
    const { permission } = await permissionService.getProjectPermission({
      actor: actor.type,
      actorId: actor.id,
      projectId,
      actorAuthMethod: actor.authMethod,
      actorOrgId: actor.orgId,
      actionProjectType: ActionProjectType.SecretManager
    });

    const permissiveFolderMappings = folderMappings.filter(({ path, environment }) =>
      permission.can(
        ProjectPermissionSecretRotationActions.Read,
        subject(ProjectPermissionSub.SecretRotation, { environment, secretPath: path })
      )
    );

    if (!permissiveFolderMappings.length) return { secretRotations: [], isLimitReached: false };

    // this result is paged by offset across separate requests, so the query needs a total order
    // (name alone ties across environments); scan one row past the limit to tell a full window
    // from a truncated one
    const scannedSecretRotations = await secretRotationV2DAL.find(
      {
        projectId,
        $search: {
          name: search
        },
        $in: {
          folderId: permissiveFolderMappings.map(({ folderId }) => folderId)
        }
      },
      {
        offset,
        limit: limit ? limit + 1 : undefined,
        sort: [
          ["name", orderDirection === OrderByDirection.DESC ? "desc" : "asc"],
          ["id", "asc"]
        ]
      }
    );

    // measure window saturation before the per-rotation permission filter, or a truncated scan
    // reads as complete whenever the filter drops rows
    const { items: windowedSecretRotations, isLimitReached } = takeRowScanWindow(scannedSecretRotations, limit);

    // Filter by per-rotation permission so connectionId (and other) restrictions are enforced.
    const secretRotations = windowedSecretRotations.filter((rotation) =>
      permission.can(ProjectPermissionSecretRotationActions.Read, getSecretRotationSubject(rotation))
    ) as TSecretRotationV2[];

    return { secretRotations, isLimitReached };
  };

  const reconcileLocalAccountRotation = async (
    {
      rotationId,
      type
    }: {
      rotationId: string;
      type:
        | SecretRotation.UnixLinuxLocalAccount
        | SecretRotation.WindowsLocalAccount
        | SecretRotation.HpIloLocalAccount;
    },
    actor: OrgServiceActor
  ) => {
    const plan = await licenseService.getPlan(actor.orgId);

    if (!plan.secretRotation)
      throw new BadRequestError({
        message:
          "Failed to reconcile secret rotation due to plan restriction. Upgrade plan to reconcile secret rotations."
      });

    const secretRotation = await secretRotationV2DAL.findById(rotationId);

    if (!secretRotation)
      throw new NotFoundError({
        message: `Could not find Secret Rotation with ID "${rotationId}"`
      });

    if (
      secretRotation.type !== SecretRotation.UnixLinuxLocalAccount &&
      secretRotation.type !== SecretRotation.WindowsLocalAccount &&
      secretRotation.type !== SecretRotation.HpIloLocalAccount
    )
      throw new BadRequestError({
        message: `Reconcile operation is only supported for Unix/Linux Local Account, Windows Local Account, and HP iLO Local Account rotations`
      });

    const { projectId, environment, folder, connection, encryptedGeneratedCredentials, parameters, folderId } =
      secretRotation;

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

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionSecretRotationActions.RotateSecrets,
      getSecretRotationSubject(secretRotation)
    );

    const localAccountParams = parameters as TLocalAccountRotation["parameters"];

    let loginAsTargetMethod;
    let loginAsRootMethod;

    if (type === SecretRotation.UnixLinuxLocalAccount) {
      loginAsTargetMethod = UnixLinuxLocalAccountRotationMethod.LoginAsTarget;
      loginAsRootMethod = UnixLinuxLocalAccountRotationMethod.LoginAsRoot;
    } else if (type === SecretRotation.WindowsLocalAccount) {
      loginAsTargetMethod = WindowsLocalAccountRotationMethod.LoginAsTarget;
      loginAsRootMethod = WindowsLocalAccountRotationMethod.LoginAsRoot;
    } else {
      loginAsTargetMethod = HpIloRotationMethod.LoginAsTarget;
      loginAsRootMethod = HpIloRotationMethod.LoginAsRoot;
    }

    // Only allow reconcile for login-as-target mode
    if (localAccountParams.rotationMethod !== loginAsTargetMethod) {
      throw new BadRequestError({
        message: `Reconcile operation is only supported for login-as-target mode Unix/Linux Local Account, Windows Local Account, and HP iLO Local Account rotations`
      });
    }

    // Get current generated credentials
    const generatedCredentials = await decryptSecretRotationCredentials({
      projectId,
      encryptedGeneratedCredentials,
      kmsService
    });

    const activeCredentials = generatedCredentials[
      secretRotation.activeIndex
    ] as TLocalAccountRotationGeneratedCredentials[number];
    const appConnection = await decryptAppConnection(connection, kmsService);

    const passwordValidationContext = await $resolvePasswordValidationContext({
      projectId,
      envId: environment.id,
      secretPath: folder.path,
      type
    });

    // Use the rotation factory to perform a rotation using the app connection credentials
    const rotationFactory = SECRET_ROTATION_FACTORY_MAP[type](
      {
        ...secretRotation,
        // Override rotation method to login-as-root so it uses the app connection credentials
        parameters: {
          ...localAccountParams,
          rotationMethod: loginAsRootMethod
        },
        connection: appConnection
      } as TSecretRotationV2WithConnection,
      appConnectionDAL,
      kmsService,
      gatewayV2Service,
      gatewayPoolService,
      keyStore,
      passwordValidationContext
    );

    // Issue new credentials using login-as-root mode (app connection credentials)
    const updatedRotation = await rotationFactory.issueCredentials(
      async (newCredentials) => {
        const localAccountCredentials = newCredentials as TLocalAccountRotationGeneratedCredentials[number];
        const updatedCredentials = [...generatedCredentials];
        updatedCredentials[secretRotation.activeIndex] = localAccountCredentials;

        const encryptedUpdatedCredentials = await encryptSecretRotationCredentials({
          projectId,
          generatedCredentials: updatedCredentials as TSecretRotationV2GeneratedCredentials,
          kmsService
        });

        // Resolved before the transaction opens, so a slow external KMS does not hold a connection
        // while it answers.
        const { encryptor } = await kmsService.createCipherPairWithDataKey({
          type: KmsDataKey.SecretManager,
          projectId
        });
        const blindIndexer = await createSecretBlindIndexer({ projectId, orgId: actor.orgId, kmsService });

        let isRecovery = false;
        const reconciled = await secretRotationV2DAL.transaction(async (tx) => {
          // Update the password secret with the new value
          const secretsMapping = secretRotation.secretsMapping as TLocalAccountRotation["secretsMapping"];
          const passwordBuffer = Buffer.from(localAccountCredentials.password);

          await fnSecretBulkUpdate({
            eventEmitter,
            eventScope: { projectId, environment: environment.slug, secretPath: folder.path },
            folderId,
            orgId: connection.orgId,
            tx,
            inputSecrets: [
              {
                filter: {
                  key: secretsMapping.password,
                  folderId,
                  type: SecretType.Shared
                },
                data: {
                  encryptedValue: encryptor({
                    plainText: passwordBuffer
                  }).cipherTextBlob,
                  blindIndexes: await blindIndexer.generateBlindIndexes(passwordBuffer),
                  references: []
                }
              }
            ],
            secretDAL: secretV2BridgeDAL,
            secretVersionDAL: secretVersionV2BridgeDAL,
            secretVersionTagDAL: secretVersionTagV2BridgeDAL,
            folderCommitService,
            actor: { type: ActorType.PLATFORM },
            secretTagDAL,
            resourceMetadataDAL
          });

          isRecovery = await $markRotationSucceeded(rotationId, tx);
          return secretRotationV2DAL.updateById(
            rotationId,
            {
              encryptedGeneratedCredentials: encryptedUpdatedCredentials,
              lastRotatedAt: new Date(),
              rotationStatus: SecretRotationStatus.Success
            },
            tx
          );
        });
        if (isRecovery) recordSecretRotationStatusChangeMetric({ type, newStatus: "healthy" });
        return reconciled;
      },
      { password: activeCredentials.password }
    );

    await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
    await secretQueueService.syncSecrets({
      orgId: connection.orgId,
      secretPath: folder.path,
      projectId,
      environmentSlug: environment.slug,
      environmentName: environment.name,
      excludeReplication: true
    });

    return {
      message: `${type === SecretRotation.UnixLinuxLocalAccount ? "Unix/Linux Local Account" : "Windows Local Account"} rotation credentials reconciled successfully`,
      reconciled: true,
      secretRotation: await expandSecretRotation(updatedRotation, kmsService)
    };
  };

  return {
    listSecretRotationOptions,
    listSecretRotationsByProjectId,
    createSecretRotation,
    updateSecretRotation,
    findSecretRotationById,
    findSecretRotationByName,
    deleteSecretRotation,
    moveSecretRotation,
    findSecretRotationGeneratedCredentialsById,
    rotateSecretRotation,
    rotateGeneratedCredentials,
    getDashboardSecretRotationCount,
    getDashboardSecretRotations,
    getQuickSearchSecretRotations,
    reconcileLocalAccountRotation,
    checkSecretRotationCredentials
  };
};