Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refac: remove files related to snapshot feature
adilsonf8d7d9c887d8
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.tsindex d17fa59990..da75b774fc 100644--- a/backend/src/ee/routes/v1/index.ts+++ b/backend/src/ee/routes/v1/index.ts@@ -52,7 +52,6 @@ import { registerSecretApprovalRequestRouter } from "./secret-approval-request-rimport { registerSecretRouter } from "./secret-router";import { registerSecretScanningRouter } from "./secret-scanning-router";import { registerSecretVersionRouter } from "./secret-version-router";-import { registerSnapshotRouter } from "./snapshot-router";import { registerSshCaRouter } from "./ssh-certificate-authority-router";import { registerSshCertRouter } from "./ssh-certificate-router";import { registerSshCertificateTemplateRouter } from "./ssh-certificate-template-router";@@ -89,7 +88,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {{ prefix: "/projects" });- await server.register(registerSnapshotRouter, { prefix: "/secret-snapshot" });await server.register(registerPITRouter, { prefix: "/pit" });await server.register(registerDeprecatedSecretApprovalPolicyRouter, { prefix: "/secret-approvals" });await server.register(registerSecretApprovalRequestRouter, {diff --git a/backend/src/ee/routes/v1/snapshot-router.ts b/backend/src/ee/routes/v1/snapshot-router.tsdeleted file mode 100644index 8c73adf5f6..0000000000--- a/backend/src/ee/routes/v1/snapshot-router.ts+++ /dev/null@@ -1,93 +0,0 @@-import { z } from "zod";--import { SecretSnapshotsSchema } from "@app/db/schemas";-import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { SanitizedTagSchema, secretRawSchema } from "@app/server/routes/sanitizedSchemas";-import { AuthMode } from "@app/services/auth/auth-type";--export const registerSnapshotRouter = async (server: FastifyZodProvider) => {- server.route({- method: "GET",- url: "/:secretSnapshotId",- config: {- rateLimit: readLimit- },- schema: {- params: z.object({- secretSnapshotId: z.string().trim()- }),- response: {- 200: z.object({- secretSnapshot: z.object({- id: z.string().uuid(),- projectId: z.string(),- environment: z.object({- id: z.string().uuid(),- slug: z.string(),- name: z.string()- }),- secretVersions: secretRawSchema- .omit({ _id: true, environment: true, workspace: true, type: true })- .extend({- secretValueHidden: z.boolean(),- secretId: z.string(),- tags: SanitizedTagSchema.array(),- isRotatedSecret: z.boolean().optional()- })- .array(),- folderVersion: z.object({ id: z.string(), name: z.string() }).array(),- createdAt: z.date(),- updatedAt: z.date()- })- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const secretSnapshot = await server.services.snapshot.getSnapshotData({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- id: req.params.secretSnapshotId- });-- return { secretSnapshot };- }- });-- server.route({- method: "POST",- url: "/:secretSnapshotId/rollback",- config: {- rateLimit: writeLimit- },- schema: {- hide: true,- deprecated: true,- tags: [ApiDocsTags.Projects],- description: "(Deprecated) Roll back project secrets to those captured in a secret snapshot version.",- security: [- {- bearerAuth: []- }- ],- params: z.object({- secretSnapshotId: z.string().trim().describe(PROJECTS.ROLLBACK_TO_SNAPSHOT.secretSnapshotId)- }),- response: {- 200: z.object({- secretSnapshot: SecretSnapshotsSchema- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async () => {- throw new Error(- "This endpoint is deprecated. Please use the new PIT recovery system. More information is available at: https://infisical.com/docs/documentation/platform/pit-recovery."- );- }- });-};diff --git a/backend/src/ee/services/secret-snapshot/secret-snapshot-service.ts b/backend/src/ee/services/secret-snapshot/secret-snapshot-service.tsdeleted file mode 100644index ccd9b8177f..0000000000--- a/backend/src/ee/services/secret-snapshot/secret-snapshot-service.ts+++ /dev/null@@ -1,400 +0,0 @@-/* eslint-disable @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument */-// akhilmhdh: I did this, quite strange bug with eslint. Everything do have a type stil has this error-import { ForbiddenError, subject } from "@casl/ability";--import { ActionProjectType } from "@app/db/schemas";-import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";-import { InternalServerError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";-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 { TSecretDALFactory } from "@app/services/secret/secret-dal";-import { INFISICAL_SECRET_VALUE_HIDDEN_MASK } from "@app/services/secret/secret-fns";-import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";-import { TSecretVersionTagDALFactory } from "@app/services/secret/secret-version-tag-dal";-import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";-import { TSecretFolderVersionDALFactory } from "@app/services/secret-folder/secret-folder-version-dal";-import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";-import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";-import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";-import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";--import { TLicenseServiceFactory } from "../license/license-service";-import {- hasSecretReadValueOrDescribePermission,- throwIfMissingSecretReadValueOrDescribePermission-} from "../permission/permission-fns";-import { TPermissionServiceFactory } from "../permission/permission-service-types";-import {- ProjectPermissionCommitsActions,- ProjectPermissionSecretActions,- ProjectPermissionSub-} from "../permission/project-permission";-import { TGetSnapshotDataDTO, TProjectSnapshotCountDTO, TProjectSnapshotListDTO } from "./secret-snapshot-types";-import { TSnapshotDALFactory } from "./snapshot-dal";-import { TSnapshotFolderDALFactory } from "./snapshot-folder-dal";-import { TSnapshotSecretDALFactory } from "./snapshot-secret-dal";-import { TSnapshotSecretV2DALFactory } from "./snapshot-secret-v2-dal";-import { getFullFolderPath } from "./snapshot-service-fns";--type TSecretSnapshotServiceFactoryDep = {- snapshotDAL: TSnapshotDALFactory;- snapshotSecretDAL: TSnapshotSecretDALFactory;- snapshotSecretV2BridgeDAL: TSnapshotSecretV2DALFactory;- snapshotFolderDAL: TSnapshotFolderDALFactory;- secretVersionDAL: Pick<TSecretVersionDALFactory, "insertMany" | "findLatestVersionByFolderId">;- secretVersionV2BridgeDAL: Pick<TSecretVersionV2DALFactory, "insertMany" | "findLatestVersionByFolderId" | "findOne">;- folderVersionDAL: Pick<TSecretFolderVersionDALFactory, "findLatestVersionByFolderId" | "insertMany" | "findOne">;- secretDAL: Pick<TSecretDALFactory, "delete" | "insertMany">;- secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "delete" | "insertMany">;- secretTagDAL: Pick<TSecretTagDALFactory, "saveTagsToSecret" | "saveTagsToSecretV2">;- secretVersionTagDAL: Pick<TSecretVersionTagDALFactory, "insertMany">;- secretVersionV2TagBridgeDAL: Pick<TSecretVersionV2TagDALFactory, "insertMany">;- folderDAL: Pick<TSecretFolderDALFactory, "findById" | "findBySecretPath" | "delete" | "insertMany" | "find">;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;- licenseService: Pick<TLicenseServiceFactory, "isValidLicense">;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;- projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;- folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;-};--export type TSecretSnapshotServiceFactory = ReturnType<typeof secretSnapshotServiceFactory>;--export const secretSnapshotServiceFactory = ({- snapshotDAL,- folderVersionDAL,- secretVersionDAL,- snapshotSecretDAL,- snapshotFolderDAL,- folderDAL,- permissionService,- licenseService,- secretVersionV2BridgeDAL,- snapshotSecretV2BridgeDAL,- kmsService,- projectBotService-}: TSecretSnapshotServiceFactoryDep) => {- const projectSecretSnapshotCount = async ({- environment,- projectId,- actorId,- actor,- actorOrgId,- actorAuthMethod,- path- }: TProjectSnapshotCountDTO) => {- const { permission } = await permissionService.getProjectPermission({- actor,- actorId,- projectId,- actorAuthMethod,- actorOrgId,- actionProjectType: ActionProjectType.SecretManager- });- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCommitsActions.Read,- subject(ProjectPermissionSub.Commits, {- secretPath: path,- environment- })- );-- // We need to check if the user has access to the secrets in the folder. If we don't do this, a user could theoretically access snapshot secret values even if they don't have read access to the secrets in the folder.- throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {- environment,- secretPath: path- });-- const folder = await folderDAL.findBySecretPath(projectId, environment, path);- if (!folder) {- throw new NotFoundError({- message: `Folder with path '${path}' not found in environment with slug '${environment}'`- });- }-- return snapshotDAL.countOfSnapshotsByFolderId(folder.id);- };-- const listSnapshots = async ({- environment,- projectId,- actorId,- actor,- actorOrgId,- actorAuthMethod,- path,- limit = 20,- offset = 0- }: TProjectSnapshotListDTO) => {- const { permission } = await permissionService.getProjectPermission({- actor,- actorId,- projectId,- actorAuthMethod,- actorOrgId,- actionProjectType: ActionProjectType.SecretManager- });- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCommitsActions.Read,- subject(ProjectPermissionSub.Commits, {- secretPath: path,- environment- })- );-- // We need to check if the user has access to the secrets in the folder. If we don't do this, a user could theoretically access snapshot secret values even if they don't have read access to the secrets in the folder.- throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {- environment,- secretPath: path- });-- const folder = await folderDAL.findBySecretPath(projectId, environment, path);- if (!folder)- throw new NotFoundError({- message: `Folder with path '${path}' not found in environment with slug '${environment}'`- });-- const snapshots = await snapshotDAL.find({ folderId: folder.id }, { limit, offset, sort: [["createdAt", "desc"]] });- return snapshots;- };-- const getSnapshotData = async ({ actorId, actor, actorOrgId, actorAuthMethod, id }: TGetSnapshotDataDTO) => {- const snapshot = await snapshotDAL.findById(id);- if (!snapshot) throw new NotFoundError({ message: `Snapshot with ID '${id}' not found` });- const { permission } = await permissionService.getProjectPermission({- actor,- actorId,- projectId: snapshot.projectId,- actorAuthMethod,- actorOrgId,- actionProjectType: ActionProjectType.SecretManager- });-- const shouldUseBridge = snapshot.projectVersion === 3;- let snapshotDetails;- if (shouldUseBridge) {- const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId: snapshot.projectId- });- const encryptedSnapshotDetails = await snapshotDAL.findSecretSnapshotV2DataById(id);-- const fullFolderPath = await getFullFolderPath({- folderDAL,- folderId: encryptedSnapshotDetails.folderId,- envId: encryptedSnapshotDetails.environment.id- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCommitsActions.Read,- subject(ProjectPermissionSub.Commits, {- secretPath: fullFolderPath,- environment: encryptedSnapshotDetails.environment.slug- })- );-- snapshotDetails = {- ...encryptedSnapshotDetails,- secretVersions: encryptedSnapshotDetails.secretVersions.map((el) => {- const canReadValue = hasSecretReadValueOrDescribePermission(- permission,- ProjectPermissionSecretActions.ReadValue,- {- environment: encryptedSnapshotDetails.environment.slug,- secretPath: fullFolderPath,- secretName: el.key,- secretTags: el.tags.length ? el.tags.map((tag) => tag.slug) : undefined- }- );-- let secretValue = "";- if (canReadValue) {- secretValue = el.encryptedValue- ? secretManagerDecryptor({ cipherTextBlob: el.encryptedValue }).toString()- : "";- } else {- secretValue = INFISICAL_SECRET_VALUE_HIDDEN_MASK;- }-- return {- ...el,- secretKey: el.key,- secretValueHidden: !canReadValue,- secretValue,- secretComment: el.encryptedComment- ? secretManagerDecryptor({ cipherTextBlob: el.encryptedComment }).toString()- : ""- };- })- };- } else {- const encryptedSnapshotDetails = await snapshotDAL.findSecretSnapshotDataById(id);-- const fullFolderPath = await getFullFolderPath({- folderDAL,- folderId: encryptedSnapshotDetails.folderId,- envId: encryptedSnapshotDetails.environment.id- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCommitsActions.Read,- subject(ProjectPermissionSub.Commits, {- secretPath: fullFolderPath,- environment: encryptedSnapshotDetails.environment.slug- })- );-- const { botKey } = await projectBotService.getBotKey(snapshot.projectId);- if (!botKey)- throw new NotFoundError({ message: `Project bot key not found for project with ID '${snapshot.projectId}'` });-- snapshotDetails = {- ...encryptedSnapshotDetails,- secretVersions: encryptedSnapshotDetails.secretVersions.map((el) => {- const secretKey = crypto.encryption().symmetric().decrypt({- ciphertext: el.secretKeyCiphertext,- iv: el.secretKeyIV,- tag: el.secretKeyTag,- key: botKey,- keySize: SymmetricKeySize.Bits128- });-- const canReadValue = hasSecretReadValueOrDescribePermission(- permission,- ProjectPermissionSecretActions.ReadValue,- {- environment: encryptedSnapshotDetails.environment.slug,- secretPath: fullFolderPath,- secretName: secretKey,- secretTags: el.tags.length ? el.tags.map((tag) => tag.slug) : undefined- }- );-- let secretValue = "";-- if (canReadValue) {- secretValue = crypto.encryption().symmetric().decrypt({- ciphertext: el.secretValueCiphertext,- iv: el.secretValueIV,- tag: el.secretValueTag,- key: botKey,- keySize: SymmetricKeySize.Bits128- });- } else {- secretValue = INFISICAL_SECRET_VALUE_HIDDEN_MASK;- }-- return {- ...el,- secretKey,- secretValueHidden: !canReadValue,- secretValue,- secretComment:- el.secretCommentTag && el.secretCommentIV && el.secretCommentCiphertext- ? crypto.encryption().symmetric().decrypt({- ciphertext: el.secretCommentCiphertext,- iv: el.secretCommentIV,- tag: el.secretCommentTag,- key: botKey,- keySize: SymmetricKeySize.Bits128- })- : ""- };- })- };- }-- return snapshotDetails;- };-- const performSnapshot = async (folderId: string) => {- try {- if (!licenseService.isValidLicense) throw new InternalServerError({ message: "Invalid license" });- const folder = await folderDAL.findById(folderId);- if (!folder) throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });- const shouldUseSecretV2Bridge = folder.projectVersion === 3;-- if (shouldUseSecretV2Bridge) {- const snapshot = await snapshotDAL.transaction(async (tx) => {- const secretVersions = await secretVersionV2BridgeDAL.findLatestVersionByFolderId(folderId, tx);- const folderVersions = await folderVersionDAL.findLatestVersionByFolderId(folderId, tx);- const newSnapshot = await snapshotDAL.create(- {- folderId,- envId: folder.environment.envId,- parentFolderId: folder.parentId- },- tx- );-- const snapshotSecrets = await snapshotSecretV2BridgeDAL.batchInsert(- secretVersions.map(({ id }) => ({- secretVersionId: id,- envId: folder.environment.envId,- snapshotId: newSnapshot.id- })),- tx- );-- const snapshotFolders = await snapshotFolderDAL.batchInsert(- folderVersions.map(({ id }) => ({- folderVersionId: id,- envId: folder.environment.envId,- snapshotId: newSnapshot.id- })),- tx- );-- return { ...newSnapshot, secrets: snapshotSecrets, folder: snapshotFolders };- });- return snapshot;- }-- const snapshot = await snapshotDAL.transaction(async (tx) => {- const secretVersions = await secretVersionDAL.findLatestVersionByFolderId(folderId, tx);- const folderVersions = await folderVersionDAL.findLatestVersionByFolderId(folderId, tx);- const newSnapshot = await snapshotDAL.create(- {- folderId,- envId: folder.environment.envId,- parentFolderId: folder.parentId- },- tx- );- const snapshotSecrets = await snapshotSecretDAL.insertMany(- secretVersions.map(({ id }) => ({- secretVersionId: id,- envId: folder.environment.envId,- snapshotId: newSnapshot.id- })),- tx- );- const snapshotFolders = await snapshotFolderDAL.insertMany(- folderVersions.map(({ id }) => ({- folderVersionId: id,- envId: folder.environment.envId,- snapshotId: newSnapshot.id- })),- tx- );-- return { ...newSnapshot, secrets: snapshotSecrets, folder: snapshotFolders };- });-- return snapshot;- } catch (error) {- // this to avoid snapshot errors- logger.error("Failed to perform snasphot");- logger.error(error);- }- };-- return {- performSnapshot,- projectSecretSnapshotCount,- listSnapshots,- getSnapshotData- };-};diff --git a/backend/src/ee/services/secret-snapshot/secret-snapshot-types.ts b/backend/src/ee/services/secret-snapshot/secret-snapshot-types.tsdeleted file mode 100644index b0fee1a62e..0000000000--- a/backend/src/ee/services/secret-snapshot/secret-snapshot-types.ts+++ /dev/null@@ -1,21 +0,0 @@-import { TProjectPermission } from "@app/lib/types";--export type TProjectSnapshotCountDTO = {- environment: string;- path: string;-} & TProjectPermission;--export type TProjectSnapshotListDTO = {- environment: string;- path: string;- offset?: number;- limit?: number;-} & TProjectPermission;--export type TGetSnapshotDataDTO = {- id: string;-} & Omit<TProjectPermission, "projectId">;--export type TRollbackSnapshotDTO = {- id: string;-} & Omit<TProjectPermission, "projectId">;diff --git a/backend/src/ee/services/secret-snapshot/snapshot-dal.ts b/backend/src/ee/services/secret-snapshot/snapshot-dal.tsdeleted file mode 100644index f27251e77c..0000000000--- a/backend/src/ee/services/secret-snapshot/snapshot-dal.ts+++ /dev/null@@ -1,910 +0,0 @@-/* eslint-disable no-await-in-loop,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument */-import { Knex } from "knex";-import { z } from "zod";--import { TDbClient } from "@app/db";-import {- SecretVersionsSchema,- SecretVersionsV2Schema,- TableName,- TSecretFolderVersions,- TSecretSnapshotFolders,- TSecretSnapshots,- TSecretVersions,- TSecretVersionsV2-} from "@app/db/schemas";-import { DatabaseError } from "@app/lib/errors";-import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";-import { logger } from "@app/lib/logger";--export type TSnapshotDALFactory = ReturnType<typeof snapshotDALFactory>;--export const snapshotDALFactory = (db: TDbClient) => {- const secretSnapshotOrm = ormify(db, TableName.Snapshot);-- const findById = async (id: string, tx?: Knex) => {- try {- const data = await (tx || db.replicaNode())(TableName.Snapshot)- .where(`${TableName.Snapshot}.id`, id)- .join(TableName.Environment, `${TableName.Snapshot}.envId`, `${TableName.Environment}.id`)- .whereNull(`${TableName.Environment}.deleteAfter`)- .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)- .select(selectAllTableCols(TableName.Snapshot))- .select(- db.ref("id").withSchema(TableName.Environment).as("envId"),- db.ref("projectId").withSchema(TableName.Environment),- db.ref("name").withSchema(TableName.Environment).as("envName"),- db.ref("slug").withSchema(TableName.Environment).as("envSlug"),- db.ref("version").withSchema(TableName.Project).as("projectVersion")- )- .first();- if (data) {- const { envId, envName, envSlug } = data;- return { ...data, envId, enviroment: { id: envId, name: envName, slug: envSlug } };- }- } catch (error) {- throw new DatabaseError({ error, name: "FindById" });- }- };-- const countOfSnapshotsByFolderId = async (folderId: string, tx?: Knex) => {- try {- const doc = await (tx || db.replicaNode())(TableName.Snapshot)- .where({ folderId })- .groupBy(["folderId"])- .count("folderId")- .first();- return parseInt((doc?.count as string) || "0", 10);- } catch (error) {- throw new DatabaseError({ error, name: "CountOfProjectSnapshot" });- }- };-- const findSecretSnapshotDataById = async (snapshotId: string, tx?: Knex) => {- try {- const data = await (tx || db.replicaNode())(TableName.Snapshot)- .where(`${TableName.Snapshot}.id`, snapshotId)- .join(TableName.Environment, `${TableName.Snapshot}.envId`, `${TableName.Environment}.id`)- .whereNull(`${TableName.Environment}.deleteAfter`)- .leftJoin(TableName.SnapshotSecret, `${TableName.Snapshot}.id`, `${TableName.SnapshotSecret}.snapshotId`)- .leftJoin(- TableName.SecretVersion,- `${TableName.SnapshotSecret}.secretVersionId`,- `${TableName.SecretVersion}.id`- )- .leftJoin(- TableName.SecretVersionTag,- `${TableName.SecretVersionTag}.${TableName.SecretVersion}Id`,- `${TableName.SecretVersion}.id`- )- .leftJoin(- TableName.SecretTag,- `${TableName.SecretVersionTag}.${TableName.SecretTag}Id`,- `${TableName.SecretTag}.id`- )- .leftJoin(TableName.SnapshotFolder, `${TableName.SnapshotFolder}.snapshotId`, `${TableName.Snapshot}.id`)- .leftJoin<TSecretFolderVersions>(- TableName.SecretFolderVersion,- `${TableName.SnapshotFolder}.folderVersionId`,- `${TableName.SecretFolderVersion}.id`- )- .select(selectAllTableCols(TableName.SecretVersion))- .select(- db.ref("id").withSchema(TableName.Snapshot).as("snapshotId"),- db.ref("createdAt").withSchema(TableName.Snapshot).as("snapshotCreatedAt"),- db.ref("updatedAt").withSchema(TableName.Snapshot).as("snapshotUpdatedAt"),- db.ref("id").withSchema(TableName.Environment).as("envId"),- db.ref("name").withSchema(TableName.Environment).as("envName"),- db.ref("slug").withSchema(TableName.Environment).as("envSlug"),- db.ref("projectId").withSchema(TableName.Environment),- db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),- db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId"),- db.ref("id").withSchema(TableName.SecretTag).as("tagId"),- db.ref("id").withSchema(TableName.SecretVersionTag).as("tagVersionId"),- db.ref("color").withSchema(TableName.SecretTag).as("tagColor"),- db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug")- );- return sqlNestRelationships({- data,- key: "snapshotId",- parentMapper: ({- snapshotId: id,- folderId,- projectId,- envId,- envSlug,- envName,- snapshotCreatedAt: createdAt,- snapshotUpdatedAt: updatedAt- }) => ({- id,- folderId,- projectId,- createdAt,- updatedAt,- environment: { id: envId, slug: envSlug, name: envName }- }),- childrenMapper: [- {- key: "id",- label: "secretVersions" as const,- mapper: (el) => SecretVersionsSchema.parse(el),- childrenMapper: [- {- key: "tagVersionId",- label: "tags" as const,- mapper: ({ tagId: id, tagSlug: slug, tagColor: color, tagVersionId: vId }) => ({- id,- name: slug,- slug,- color,- vId- })- }- ]- },- {- key: "folderVerId",- label: "folderVersion" as const,- mapper: ({ folderVerId: id, folderVerName: name }) => ({ id, name })- }- ]- })?.[0];- } catch (error) {- throw new DatabaseError({ error, name: "FindSecretSnapshotDataById" });- }- };-- const findSecretSnapshotV2DataById = async (snapshotId: string, tx?: Knex) => {- try {- const data = await (tx || db.replicaNode())(TableName.Snapshot)- .where(`${TableName.Snapshot}.id`, snapshotId)- .join(TableName.Environment, `${TableName.Snapshot}.envId`, `${TableName.Environment}.id`)- .whereNull(`${TableName.Environment}.deleteAfter`)- .leftJoin(TableName.SnapshotSecretV2, `${TableName.Snapshot}.id`, `${TableName.SnapshotSecretV2}.snapshotId`)- .leftJoin(- TableName.SecretVersionV2,- `${TableName.SnapshotSecretV2}.secretVersionId`,- `${TableName.SecretVersionV2}.id`- )- .leftJoin(- TableName.SecretVersionV2Tag,- `${TableName.SecretVersionV2Tag}.${TableName.SecretVersionV2}Id`,- `${TableName.SecretVersionV2}.id`- )- .leftJoin(- TableName.SecretTag,- `${TableName.SecretVersionV2Tag}.${TableName.SecretTag}Id`,- `${TableName.SecretTag}.id`- )- .leftJoin(TableName.SnapshotFolder, `${TableName.SnapshotFolder}.snapshotId`, `${TableName.Snapshot}.id`)- .leftJoin<TSecretFolderVersions>(- TableName.SecretFolderVersion,- `${TableName.SnapshotFolder}.folderVersionId`,- `${TableName.SecretFolderVersion}.id`- )- .leftJoin(- TableName.SecretRotationV2SecretMapping,- `${TableName.SecretRotationV2SecretMapping}.secretId`,- `${TableName.SecretVersionV2}.secretId`- )- .select(selectAllTableCols(TableName.SecretVersionV2))- .select(- db.ref("id").withSchema(TableName.Snapshot).as("snapshotId"),- db.ref("createdAt").withSchema(TableName.Snapshot).as("snapshotCreatedAt"),- db.ref("updatedAt").withSchema(TableName.Snapshot).as("snapshotUpdatedAt"),- db.ref("id").withSchema(TableName.Environment).as("envId"),- db.ref("name").withSchema(TableName.Environment).as("envName"),- db.ref("slug").withSchema(TableName.Environment).as("envSlug"),- db.ref("projectId").withSchema(TableName.Environment),- db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),- db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId"),- db.ref("id").withSchema(TableName.SecretTag).as("tagId"),- db.ref("id").withSchema(TableName.SecretVersionV2Tag).as("tagVersionId"),- db.ref("color").withSchema(TableName.SecretTag).as("tagColor"),- db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"),- db.ref("rotationId").withSchema(TableName.SecretRotationV2SecretMapping)- );- return sqlNestRelationships({- data,- key: "snapshotId",- parentMapper: ({- snapshotId: id,- folderId,- projectId,- envId,- envSlug,- envName,- snapshotCreatedAt: createdAt,- snapshotUpdatedAt: updatedAt- }) => ({- id,- folderId,- projectId,- createdAt,- updatedAt,- environment: { id: envId, slug: envSlug, name: envName }- }),- childrenMapper: [- {- key: "id",- label: "secretVersions" as const,- mapper: (el) => ({- ...SecretVersionsV2Schema.parse(el),- isRotatedSecret: Boolean(el.rotationId),- rotationId: el.rotationId- }),- childrenMapper: [- {- key: "tagVersionId",- label: "tags" as const,- mapper: ({ tagId: id, tagSlug: slug, tagColor: color, tagVersionId: vId }) => ({- id,- name: slug,- slug,- color,- vId- })- }- ]- },- {- key: "folderVerId",- label: "folderVersion" as const,- mapper: ({ folderVerId: id, folderVerName: name }) => ({ id, name })- }- ]- })?.[0];- } catch (error) {- throw new DatabaseError({ error, name: "FindSecretSnapshotDataById" });- }- };-- // this is used for rollback- // from a starting snapshot it will collect all the secrets and folder of that- // then it will start go through recursively the below folders latest snapshots then their child folder snapshot until leaf node- // the recursive part find all snapshot id- // then joins with respective secrets and folder- const findRecursivelySnapshots = async (snapshotId: string, tx?: Knex) => {- try {- const data = await (tx || db.replicaNode())- .withRecursive("parent", (qb) => {- void qb- .from(TableName.Snapshot)- .leftJoin<TSecretSnapshotFolders>(- TableName.SnapshotFolder,- `${TableName.SnapshotFolder}.snapshotId`,- `${TableName.Snapshot}.id`- )- .leftJoin<TSecretFolderVersions>(- TableName.SecretFolderVersion,- `${TableName.SnapshotFolder}.folderVersionId`,- `${TableName.SecretFolderVersion}.id`- )- .select(selectAllTableCols(TableName.Snapshot))- .select({ depth: 1 })- .select(- db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),- db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId")- )- .where(`${TableName.Snapshot}.id`, snapshotId)- .union(- (cb) =>- void cb- .select(selectAllTableCols(TableName.Snapshot))- .select({ depth: db.raw("parent.depth + 1") })- .select(- db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),- db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId")- )- .from(TableName.Snapshot)- .join<TSecretSnapshots, TSecretSnapshots & { secretId: string; max: number }>(- db(TableName.Snapshot).groupBy("folderId").max("createdAt").select("folderId").as("latestVersion"),- `${TableName.Snapshot}.createdAt`,- "latestVersion.max"- )- .leftJoin<TSecretSnapshotFolders>(- TableName.SnapshotFolder,- `${TableName.SnapshotFolder}.snapshotId`,- `${TableName.Snapshot}.id`- )- .leftJoin<TSecretFolderVersions>(- TableName.SecretFolderVersion,- `${TableName.SnapshotFolder}.folderVersionId`,- `${TableName.SecretFolderVersion}.id`- )- .join("parent", "parent.folderVerId", `${TableName.Snapshot}.folderId`)- );- })- .orderBy("depth", "asc")- .from<TSecretSnapshots & { folderVerId: string; folderVerName: string }>("parent")- .leftJoin<TSecretSnapshots>(TableName.SnapshotSecret, `parent.id`, `${TableName.SnapshotSecret}.snapshotId`)- .leftJoin<TSecretVersions>(- TableName.SecretVersion,- `${TableName.SnapshotSecret}.secretVersionId`,- `${TableName.SecretVersion}.id`- )- .leftJoin(- TableName.SecretVersionTag,- `${TableName.SecretVersionTag}.${TableName.SecretVersion}Id`,- `${TableName.SecretVersion}.id`- )- .leftJoin(- TableName.SecretTag,- `${TableName.SecretVersionTag}.${TableName.SecretTag}Id`,- `${TableName.SecretTag}.id`- )- .leftJoin<{ latestSecretVersion: number }>(- (tx || db)(TableName.SecretVersion)- .groupBy("secretId")- .select("secretId")- .max("version")- .as("secGroupByMaxVersion"),- `${TableName.SecretVersion}.secretId`,- "secGroupByMaxVersion.secretId"- )- .leftJoin<{ latestFolderVersion: number }>(- (tx || db)(TableName.SecretFolderVersion)- .groupBy("folderId")- .select("folderId")- .max("version")- .as("folderGroupByMaxVersion"),- `parent.folderId`,- "folderGroupByMaxVersion.folderId"- )- .select(selectAllTableCols(TableName.SecretVersion))- .select(- db.ref("id").withSchema("parent").as("snapshotId"),- db.ref("folderId").withSchema("parent").as("snapshotFolderId"),- db.ref("parentFolderId").withSchema("parent").as("snapshotParentFolderId"),- db.ref("folderVerName").withSchema("parent"),- db.ref("folderVerId").withSchema("parent"),- db.ref("max").withSchema("secGroupByMaxVersion").as("latestSecretVersion"),- db.ref("max").withSchema("folderGroupByMaxVersion").as("latestFolderVersion"),- db.ref("id").withSchema(TableName.SecretTag).as("tagId"),- db.ref("id").withSchema(TableName.SecretVersionTag).as("tagVersionId"),- db.ref("color").withSchema(TableName.SecretTag).as("tagColor"),- db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug")- );-- const formated = sqlNestRelationships({- data,- key: "snapshotId",- parentMapper: ({ snapshotId: id, snapshotFolderId: folderId, snapshotParentFolderId: parentFolderId }) => ({- id,- folderId,- parentFolderId- }),- childrenMapper: [- {- key: "id",- label: "secretVersions" as const,- mapper: (el) => ({- ...SecretVersionsSchema.parse(el),- latestSecretVersion: el.latestSecretVersion as number- }),- childrenMapper: [- {- key: "tagVersionId",- label: "tags" as const,- mapper: ({ tagId: id, tagSlug: slug, tagColor: color, tagVersionId: vId }) => ({- id,- name: slug,- slug,- color,- vId- })- }- ]- },- {- key: "folderVerId",- label: "folderVersion" as const,- mapper: ({ folderVerId: id, folderVerName: name, latestFolderVersion }) => ({- id,- name,- latestFolderVersion: latestFolderVersion as number- })- }- ]- });- return formated;- } catch (error) {- throw new DatabaseError({ error, name: "FindRecursivelySnapshots" });- }- };-- // this is used for rollback- // from a starting snapshot it will collect all the secrets and folder of that- // then it will start go through recursively the below folders latest snapshots then their child folder snapshot until leaf node- // the recursive part find all snapshot id- // then joins with respective secrets and folder- const findRecursivelySnapshotsV2Bridge = async (snapshotId: string, tx?: Knex) => {- try {- const data = await (tx || db.replicaNode())- .withRecursive("parent", (qb) => {- void qb- .from(TableName.Snapshot)- .leftJoin<TSecretSnapshotFolders>(- TableName.SnapshotFolder,- `${TableName.SnapshotFolder}.snapshotId`,- `${TableName.Snapshot}.id`- )- .leftJoin<TSecretFolderVersions>(- TableName.SecretFolderVersion,- `${TableName.SnapshotFolder}.folderVersionId`,- `${TableName.SecretFolderVersion}.id`- )- .select(selectAllTableCols(TableName.Snapshot))- .select({ depth: 1 })- .select(- db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),- db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId")- )- .where(`${TableName.Snapshot}.id`, snapshotId)- .union(- (cb) =>- void cb- .select(selectAllTableCols(TableName.Snapshot))- .select({ depth: db.raw("parent.depth + 1") })- .select(- db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),- db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId")- )- .from(TableName.Snapshot)- .join<TSecretSnapshots, TSecretSnapshots & { secretId: string; max: number }>(- db(TableName.Snapshot).groupBy("folderId").max("createdAt").select("folderId").as("latestVersion"),- `${TableName.Snapshot}.createdAt`,- "latestVersion.max"- )- .leftJoin<TSecretSnapshotFolders>(- TableName.SnapshotFolder,- `${TableName.SnapshotFolder}.snapshotId`,- `${TableName.Snapshot}.id`- )- .leftJoin<TSecretFolderVersions>(- TableName.SecretFolderVersion,- `${TableName.SnapshotFolder}.folderVersionId`,- `${TableName.SecretFolderVersion}.id`- )- .join("parent", "parent.folderVerId", `${TableName.Snapshot}.folderId`)- );- })- .orderBy("depth", "asc")- .from<TSecretSnapshots & { folderVerId: string; folderVerName: string }>("parent")- .leftJoin<TSecretSnapshots>(TableName.SnapshotSecretV2, `parent.id`, `${TableName.SnapshotSecretV2}.snapshotId`)- .leftJoin<TSecretVersionsV2>(- TableName.SecretVersionV2,- `${TableName.SnapshotSecretV2}.secretVersionId`,- `${TableName.SecretVersionV2}.id`- )- .leftJoin(- TableName.SecretVersionV2Tag,- `${TableName.SecretVersionV2Tag}.${TableName.SecretVersionV2}Id`,- `${TableName.SecretVersionV2}.id`- )- .leftJoin(- TableName.SecretTag,- `${TableName.SecretVersionV2Tag}.${TableName.SecretTag}Id`,- `${TableName.SecretTag}.id`- )- .leftJoin(- TableName.SecretRotationV2SecretMapping,- `${TableName.SecretVersionV2}.secretId`,- `${TableName.SecretRotationV2SecretMapping}.secretId`- )- .leftJoin<{ latestSecretVersion: number }>(- (tx || db)(TableName.SecretVersionV2)- .groupBy("secretId")- .select("secretId")- .max("version")- .as("secGroupByMaxVersion"),- `${TableName.SecretVersionV2}.secretId`,- "secGroupByMaxVersion.secretId"- )- .leftJoin<{ latestFolderVersion: number }>(- (tx || db)(TableName.SecretFolderVersion)- .groupBy("folderId")- .select("folderId")- .max("version")- .as("folderGroupByMaxVersion"),- `parent.folderId`,- "folderGroupByMaxVersion.folderId"- )- .select(selectAllTableCols(TableName.SecretVersionV2))- .select(- db.ref("id").withSchema("parent").as("snapshotId"),- db.ref("folderId").withSchema("parent").as("snapshotFolderId"),- db.ref("parentFolderId").withSchema("parent").as("snapshotParentFolderId"),- db.ref("folderVerName").withSchema("parent"),- db.ref("folderVerId").withSchema("parent"),- db.ref("max").withSchema("secGroupByMaxVersion").as("latestSecretVersion"),- db.ref("max").withSchema("folderGroupByMaxVersion").as("latestFolderVersion"),- db.ref("id").withSchema(TableName.SecretTag).as("tagId"),- db.ref("id").withSchema(TableName.SecretVersionV2Tag).as("tagVersionId"),- db.ref("color").withSchema(TableName.SecretTag).as("tagColor"),- db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"),- db.ref("rotationId").withSchema(TableName.SecretRotationV2SecretMapping)- );-- const formated = sqlNestRelationships({- data,- key: "snapshotId",- parentMapper: ({ snapshotId: id, snapshotFolderId: folderId, snapshotParentFolderId: parentFolderId }) => ({- id,- folderId,- parentFolderId- }),- childrenMapper: [- {- key: "id",- label: "secretVersions" as const,- mapper: (el) => ({- ...SecretVersionsV2Schema.parse(el),- latestSecretVersion: el.latestSecretVersion as number,- isRotatedSecret: Boolean(el.rotationId)- }),- childrenMapper: [- {- key: "tagVersionId",- label: "tags" as const,- mapper: ({ tagId: id, tagSlug: slug, tagColor: color, tagVersionId: vId }) => ({- id,- name: slug,- slug,- color,- vId- })- }- ]- },- {- key: "folderVerId",- label: "folderVersion" as const,- mapper: ({ folderVerId: id, folderVerName: name, latestFolderVersion }) => ({- id,- name,- latestFolderVersion: latestFolderVersion as number- })- }- ]- });- return formated;- } catch (error) {- throw new DatabaseError({ error, name: "FindRecursivelySnapshots" });- }- };-- // instead of copying all child folders- // we will take the latest snapshot of those folders- // when we need to rollback we will pull from these snapshots- const findLatestSnapshotByFolderId = async (folderId: string, tx?: Knex) => {- try {- const docs = await (tx || db.replicaNode())(TableName.Snapshot)- .where(`${TableName.Snapshot}.folderId`, folderId)- .join<TSecretSnapshots>(- (tx || db.replicaNode())(TableName.Snapshot)- .groupBy("folderId")- .max("createdAt")- .select("folderId")- .as("latestVersion"),- (bd) => {- bd.on(`${TableName.Snapshot}.folderId`, "latestVersion.folderId").andOn(- `${TableName.Snapshot}.createdAt`,- "latestVersion.max"- );- }- )- .first();- return docs;- } catch (error) {- throw new DatabaseError({ error, name: "FindLatestVersionByFolderId" });- }- };-- /**- * Prunes excess snapshots from the database to ensure only a specified number of recent snapshots are retained for each folder.- *- * This function operates in three main steps:- * 1. Pruning snapshots from current folders.- * 2. Pruning snapshots from non-current folders (versioned ones).- * 3. Removing orphaned snapshots that do not belong to any existing folder or folder version.- *- * The function processes snapshots in batches, determined by the `PRUNE_FOLDER_BATCH_SIZE` constant,- * to manage the large datasets without overwhelming the DB.- *- * Steps:- * - Fetch a batch of folder IDs.- * - For each batch, use a Common Table Expression (CTE) to rank snapshots within each folder by their creation date.- * - Identify and delete snapshots that exceed the project's point-in-time version limit (`pitVersionLimit`).- * - Repeat the process for versioned folders.- * - Finally, delete orphaned snapshots that do not have an associated folder.- */- const pruneExcessSnapshots = async () => {- const PRUNE_FOLDER_BATCH_SIZE = 10000;- const ORPHAN_PRUNE_BATCH_SIZE = 10000;- const ORPHAN_QUERY_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes- const ORPHAN_MAX_RETRY_ON_FAILURE = 3;-- logger.info(`daily-resource-cleanup: pruning secret snapshots started`);- try {- let uuidOffset = "00000000-0000-0000-0000-000000000000";- // cleanup snapshots from current folders- // eslint-disable-next-line no-constant-condition, no-unreachable-loop- while (true) {- const folderBatch = await db(TableName.SecretFolder)- .where("id", ">", uuidOffset)- .where("isReserved", false)- .orderBy("id", "asc")- .limit(PRUNE_FOLDER_BATCH_SIZE)- .select("id");-- const batchEntries = folderBatch.map((folder) => folder.id);-- if (folderBatch.length) {- try {- logger.info(`Pruning snapshots in [range=${batchEntries[0]}:${batchEntries[batchEntries.length - 1]}]`);- await db(TableName.Snapshot)- .with("snapshot_cte", (qb) => {- void qb- .from(TableName.Snapshot)- .whereIn(`${TableName.Snapshot}.folderId`, batchEntries)- .select(- "folderId",- `${TableName.Snapshot}.id as id`,- db.raw(- `ROW_NUMBER() OVER (PARTITION BY ${TableName.Snapshot}."folderId" ORDER BY ${TableName.Snapshot}."createdAt" DESC) AS row_num`- )- );- })- .join(TableName.SecretFolder, `${TableName.SecretFolder}.id`, `${TableName.Snapshot}.folderId`)- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)- .join(TableName.Project, `${TableName.Project}.id`, `${TableName.Environment}.projectId`)- .join("snapshot_cte", "snapshot_cte.id", `${TableName.Snapshot}.id`)- .whereRaw(`snapshot_cte.row_num > ${TableName.Project}."pitVersionLimit"`)- .whereNull(`${TableName.Environment}.deleteAfter`)- .delete();- } catch (err) {- logger.error(- `Failed to prune snapshots from current folders in range ${batchEntries[0]}:${- batchEntries[batchEntries.length - 1]- }`- );- } finally {- uuidOffset = batchEntries[batchEntries.length - 1];- }- } else {- break;- }- }-- // cleanup snapshots from non-current folders- uuidOffset = "00000000-0000-0000-0000-000000000000";- // eslint-disable-next-line no-constant-condition- while (true) {- const folderBatch = await db(TableName.SecretFolderVersion)- .select("folderId")- .distinct("folderId")- .where("folderId", ">", uuidOffset)- .orderBy("folderId", "asc")- .limit(PRUNE_FOLDER_BATCH_SIZE);-- const batchEntries = folderBatch.map((folder) => folder.folderId);-- if (folderBatch.length) {- try {- logger.info(`Pruning snapshots in range ${batchEntries[0]}:${batchEntries[batchEntries.length - 1]}`);- await db(TableName.Snapshot)- .with("snapshot_cte", (qb) => {- void qb- .from(TableName.Snapshot)- .whereIn(`${TableName.Snapshot}.folderId`, batchEntries)- .select(- "folderId",- `${TableName.Snapshot}.id as id`,- db.raw(- `ROW_NUMBER() OVER (PARTITION BY ${TableName.Snapshot}."folderId" ORDER BY ${TableName.Snapshot}."createdAt" DESC) AS row_num`- )- );- })- .join(- TableName.SecretFolderVersion,- `${TableName.SecretFolderVersion}.folderId`,- `${TableName.Snapshot}.folderId`- )- .join(TableName.Environment, `${TableName.SecretFolderVersion}.envId`, `${TableName.Environment}.id`)- .join(TableName.Project, `${TableName.Project}.id`, `${TableName.Environment}.projectId`)- .join("snapshot_cte", "snapshot_cte.id", `${TableName.Snapshot}.id`)- .whereRaw(`snapshot_cte.row_num > ${TableName.Project}."pitVersionLimit"`)- .whereNull(`${TableName.Environment}.deleteAfter`)- .delete();- } catch (err) {- logger.error(- `Failed to prune snapshots from non-current folders in range ${batchEntries[0]}:${- batchEntries[batchEntries.length - 1]- }`- );- } finally {- uuidOffset = batchEntries[batchEntries.length - 1];- }- } else {- break;- }- }-- // cleanup orphaned snapshots (those that don't belong to an existing folder and folder version).- let orphanCursor = "00000000-0000-0000-0000-000000000000";- let orphanRetryCount = 0;- let orphanBatchHadRows = true;- logger.info(`daily-resource-cleanup: pruning orphaned secret snapshots started`);- while (orphanBatchHadRows) {- // Bind to a const so the transaction closure doesn't capture the mutable- // `orphanCursor` from the loop scope (no-loop-func).- const cursor = orphanCursor;- try {- const result = await db.transaction(async (trx) => {- // SET LOCAL: scope the timeout to this transaction so it auto-reverts on commit/rollback- // and doesn't leak back to the connection pool.- await trx.raw(`SET LOCAL statement_timeout = ${ORPHAN_QUERY_TIMEOUT_MS}`);-- const batch = await trx(TableName.Snapshot)- .where("id", ">", cursor)- .orderBy("id", "asc")- .limit(ORPHAN_PRUNE_BATCH_SIZE)- .select("id");-- if (batch.length === 0) {- return { nextCursor: cursor, scanned: 0, deleted: 0 };- }-- const batchIds = batch.map((row) => row.id);- const lastId = batchIds[batchIds.length - 1];-- const deleted = await trx(TableName.Snapshot)- .whereIn("id", batchIds)- .whereNotExists(- (qb) =>- void qb- .select(trx.raw("1"))- .from(TableName.SecretFolder)- .whereRaw(`"${TableName.SecretFolder}"."id" = "${TableName.Snapshot}"."folderId"`)- )- .whereNotExists(- (qb) =>- void qb- .select(trx.raw("1"))- .from(TableName.SecretFolderVersion)- .whereRaw(`"${TableName.SecretFolderVersion}"."folderId" = "${TableName.Snapshot}"."folderId"`)- )- .delete();-- return { nextCursor: lastId, scanned: batch.length, deleted };- });-- orphanCursor = result.nextCursor;- orphanBatchHadRows = result.scanned > 0;- orphanRetryCount = 0;- } catch (err) {- orphanRetryCount += 1;- logger.error(err, `Failed to prune orphaned snapshots starting after id=${cursor}`);- if (orphanRetryCount >= ORPHAN_MAX_RETRY_ON_FAILURE) {- logger.error(`Giving up on orphaned snapshot prune after ${ORPHAN_MAX_RETRY_ON_FAILURE} retries`);- break;- }- } finally {- await new Promise((resolve) => {- setTimeout(resolve, 10); // breathing room for the db between batches- });- }- }- } catch (error) {- throw new DatabaseError({ error, name: "SnapshotPrune" });- }- logger.info(`daily-resource-cleanup: pruning secret snapshots completed`);- };-- // special query for migration for secret v2- const findNSecretV1SnapshotByFolderId = async (folderId: string, n = 15, tx?: Knex) => {- try {- const query = (tx || db.replicaNode())(TableName.Snapshot)- .leftJoin(TableName.SnapshotSecret, `${TableName.Snapshot}.id`, `${TableName.SnapshotSecret}.snapshotId`)- .leftJoin(- TableName.SecretVersion,- `${TableName.SnapshotSecret}.secretVersionId`,- `${TableName.SecretVersion}.id`- )- .leftJoin(- TableName.SecretVersionTag,- `${TableName.SecretVersionTag}.${TableName.SecretVersion}Id`,- `${TableName.SecretVersion}.id`- )- .select(selectAllTableCols(TableName.SecretVersion))- .select(- db.ref("id").withSchema(TableName.Snapshot).as("snapshotId"),- db.ref("createdAt").withSchema(TableName.Snapshot).as("snapshotCreatedAt"),- db.ref("updatedAt").withSchema(TableName.Snapshot).as("snapshotUpdatedAt"),- db.ref("envId").withSchema(TableName.SnapshotSecret).as("snapshotEnvId"),- db.ref("id").withSchema(TableName.SecretVersionTag).as("secretVersionTagId"),- db.ref("secret_versionsId").withSchema(TableName.SecretVersionTag).as("secretVersionTagSecretId"),- db.ref("secret_tagsId").withSchema(TableName.SecretVersionTag).as("secretVersionTagSecretTagId"),- db.raw(- `DENSE_RANK() OVER (partition by ${TableName.Snapshot}."id" ORDER BY ${TableName.SecretVersion}."createdAt") as rank`- )- )- .orderBy(`${TableName.Snapshot}.createdAt`, "desc")- .where(`${TableName.Snapshot}.folderId`, folderId);- const data = await (tx || db.replicaNode())- .with("w", query)- .select("*")- .from<Awaited<typeof query>[number]>("w")- .andWhere("w.rank", "<", n);-- return sqlNestRelationships({- data,- key: "snapshotId",- parentMapper: ({ snapshotId: id, snapshotCreatedAt: createdAt, snapshotUpdatedAt: updatedAt }) => ({- id,- folderId,- createdAt,- updatedAt- }),- childrenMapper: [- {- key: "id",- label: "secretVersions" as const,- mapper: (el) => SecretVersionsSchema.extend({ snapshotEnvId: z.string() }).parse(el),- childrenMapper: [- {- key: "secretVersionTagId",- label: "tags" as const,- mapper: ({ secretVersionTagId, secretVersionTagSecretId, secretVersionTagSecretTagId }) => ({- id: secretVersionTagId,- secretVersionId: secretVersionTagSecretId,- secretTagId: secretVersionTagSecretTagId- })- }- ]- }- ]- });- } catch (error) {- throw new DatabaseError({ error, name: "FindSecretSnapshotDataById" });- }- };-- const deleteSnapshotsAboveLimit = async (folderId: string, n = 15, tx?: Knex) => {- try {- const query = await (tx || db)- .with("to_delete", (qb) => {- void qb- .select("id")- .from(TableName.Snapshot)- .where("folderId", folderId)- .orderBy("createdAt", "desc")- .offset(n);- })- .from(TableName.Snapshot)- .whereIn("id", (qb) => {- void qb.select("id").from("to_delete");- })- .delete();- return query;- } catch (error) {- throw new DatabaseError({ error, name: "DeleteSnapshotsAboveLimit" });- }- };-- return {- ...secretSnapshotOrm,- findById,- findLatestSnapshotByFolderId,- findRecursivelySnapshots,- findRecursivelySnapshotsV2Bridge,- countOfSnapshotsByFolderId,- findSecretSnapshotDataById,- findSecretSnapshotV2DataById,- pruneExcessSnapshots,- findNSecretV1SnapshotByFolderId,- deleteSnapshotsAboveLimit- };-};diff --git a/backend/src/ee/services/secret-snapshot/snapshot-folder-dal.ts b/backend/src/ee/services/secret-snapshot/snapshot-folder-dal.tsdeleted file mode 100644index e663e4a0fc..0000000000--- a/backend/src/ee/services/secret-snapshot/snapshot-folder-dal.ts+++ /dev/null@@ -1,11 +0,0 @@-import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";-import { ormify } from "@app/lib/knex";--export type TSnapshotFolderDALFactory = ReturnType<typeof snapshotFolderDALFactory>;--export const snapshotFolderDALFactory = (db: TDbClient) => {- const snapshotFolderOrm = ormify(db, TableName.SnapshotFolder);-- return snapshotFolderOrm;-};diff --git a/backend/src/ee/services/secret-snapshot/snapshot-secret-dal.ts b/backend/src/ee/services/secret-snapshot/snapshot-secret-dal.tsdeleted file mode 100644index d5fa106138..0000000000--- a/backend/src/ee/services/secret-snapshot/snapshot-secret-dal.ts+++ /dev/null@@ -1,10 +0,0 @@-import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";-import { ormify } from "@app/lib/knex";--export type TSnapshotSecretDALFactory = ReturnType<typeof snapshotSecretDALFactory>;--export const snapshotSecretDALFactory = (db: TDbClient) => {- const snapshotSecretOrm = ormify(db, TableName.SnapshotSecret);- return snapshotSecretOrm;-};diff --git a/backend/src/ee/services/secret-snapshot/snapshot-secret-v2-dal.ts b/backend/src/ee/services/secret-snapshot/snapshot-secret-v2-dal.tsdeleted file mode 100644index 6d5f5896dc..0000000000--- a/backend/src/ee/services/secret-snapshot/snapshot-secret-v2-dal.ts+++ /dev/null@@ -1,10 +0,0 @@-import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";-import { ormify } from "@app/lib/knex";--export type TSnapshotSecretV2DALFactory = ReturnType<typeof snapshotSecretV2DALFactory>;--export const snapshotSecretV2DALFactory = (db: TDbClient) => {- const snapshotSecretOrm = ormify(db, TableName.SnapshotSecretV2);- return snapshotSecretOrm;-};diff --git a/backend/src/ee/services/secret-snapshot/snapshot-service-fns.ts b/backend/src/ee/services/secret-snapshot/snapshot-service-fns.tsdeleted file mode 100644index cd5372c8d2..0000000000--- a/backend/src/ee/services/secret-snapshot/snapshot-service-fns.ts+++ /dev/null@@ -1,39 +0,0 @@-import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";--type GetFullFolderPath = {- folderDAL: Pick<TSecretFolderDALFactory, "findById" | "find">; // Added findAllInEnv- folderId: string;- envId: string;-};--export const getFullFolderPath = async ({ folderDAL, folderId, envId }: GetFullFolderPath): Promise<string> => {- // Helper function to remove duplicate slashes- const removeDuplicateSlashes = (path: string) => {- const chars = [];- let lastWasSlash = false;-- for (let i = 0; i < path.length; i += 1) {- const char = path[i];- if (char !== "/" || !lastWasSlash) chars.push(char);- lastWasSlash = char === "/";- }-- return chars.join("");- };-- // Fetch all folders at once based on environment ID to avoid multiple queries- const folders = await folderDAL.find({ envId });- const folderMap = new Map(folders.map((folder) => [folder.id, folder]));-- const buildPath = (currFolderId: string): string => {- const folder = folderMap.get(currFolderId);- if (!folder) return "";- const folderPathSegment = !folder.parentId && folder.name === "root" ? "/" : `/${folder.name}`;- if (folder.parentId) {- return removeDuplicateSlashes(`${buildPath(folder.parentId)}${folderPathSegment}`);- }- return removeDuplicateSlashes(folderPathSegment);- };-- return buildPath(folderId);-};